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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1366  ! raeburn     4: # $Id: loncommon.pm,v 1.1365 2021/09/05 05:55:50 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.973     raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
                   1284: =cut
                   1285: 
                   1286: sub help_open_topic {
1.973     raeburn  1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1288:     $text = "" if (not defined $text);
1.44      bowersj2 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1290:     $width = 500 if (not defined $width);
1.44      bowersj2 1291:     $height = 400 if (not defined $height);
                   1292:     my $filename = $topic;
                   1293:     $filename =~ s/ /_/g;
                   1294: 
1.48      bowersj2 1295:     my $template = "";
                   1296:     my $link;
1.572     banghart 1297:     
1.159     www      1298:     $topic=~s/\W/\_/g;
1.44      bowersj2 1299: 
1.572     banghart 1300:     if (!$stayOnPage) {
1.1033    www      1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1302:     } elsif ($stayOnPage eq 'popup') {
                   1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1304:     } else {
1.48      bowersj2 1305: 	$link = "/adm/help/${filename}.hlp";
                   1306:     }
                   1307: 
                   1308:     # Add the text
1.1314    raeburn  1309:     my $target = ' target="_top"';
                   1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1311:         $target = '';
                   1312:     }
1.755     neumanie 1313:     if ($text ne "") {	
1.763     bisitz   1314: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1315:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1316:                   .$text.'</a>';
1.48      bowersj2 1317:     }
                   1318: 
1.763     bisitz   1319:     # (Always) Add the graphic
1.179     matthew  1320:     my $title = &mt('Online Help');
1.667     raeburn  1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1322:     if ($imgid ne '') {
                   1323:         $imgid = ' id="'.$imgid.'"';
                   1324:     }
1.1314    raeburn  1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1326:               .'<img src="'.$helpicon.'" border="0"'
                   1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1329:               .' /></a>';
                   1330:     if ($text ne "") {	
                   1331:         $template.='</span>';
                   1332:     }
1.44      bowersj2 1333:     return $template;
                   1334: 
1.106     bowersj2 1335: }
                   1336: 
                   1337: # This is a quicky function for Latex cheatsheet editing, since it 
                   1338: # appears in at least four places
                   1339: sub helpLatexCheatsheet {
1.1037    www      1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1341:     my $out;
1.106     bowersj2 1342:     my $addOther = '';
1.732     raeburn  1343:     if ($topic) {
1.1037    www      1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1345:     }
                   1346:     $out = '<span>' # Start cheatsheet
                   1347: 	  .$addOther
                   1348:           .'<span>'
1.1037    www      1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	  .'</span> <span>'
1.1037    www      1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1352: 	  .'</span>';
1.732     raeburn  1353:     unless ($not_author) {
1.1186    kruse    1354:         $out .= '<span>'
                   1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1356:                .'</span> <span>'
                   1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	       .'</span>';
1.732     raeburn  1359:     }
1.763     bisitz   1360:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1361:     return $out;
1.172     www      1362: }
                   1363: 
1.430     albertel 1364: sub general_help {
                   1365:     my $helptopic='Student_Intro';
                   1366:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1367: 	$helptopic='Authoring_Intro';
1.907     raeburn  1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1369: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1370:     } elsif ($env{'request.role'}=~/^dc/) {
                   1371:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1372:     }
                   1373:     return $helptopic;
                   1374: }
                   1375: 
                   1376: sub update_help_link {
                   1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1378:     my $origurl = $ENV{'REQUEST_URI'};
                   1379:     $origurl=~s|^/~|/priv/|;
                   1380:     my $timestamp = time;
                   1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1382:         $$datum = &escape($$datum);
                   1383:     }
                   1384: 
                   1385:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1386:     my $output .= <<"ENDOUTPUT";
                   1387: <script type="text/javascript">
1.824     bisitz   1388: // <![CDATA[
1.430     albertel 1389: banner_link = '$banner_link';
1.824     bisitz   1390: // ]]>
1.430     albertel 1391: </script>
                   1392: ENDOUTPUT
                   1393:     return $output;
                   1394: }
                   1395: 
                   1396: # now just updates the help link and generates a blue icon
1.193     raeburn  1397: sub help_open_menu {
1.430     albertel 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1399: 	= @_;    
1.949     droeschl 1400:     $stayOnPage = 1;
1.430     albertel 1401:     my $output;
                   1402:     if ($component_help) {
                   1403: 	if (!$text) {
                   1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1405: 				       $width,$height);
                   1406: 	} else {
                   1407: 	    my $help_text;
                   1408: 	    $help_text=&unescape($topic);
                   1409: 	    $output='<table><tr><td>'.
                   1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1411: 				 $width,$height).'</td></tr></table>';
                   1412: 	}
                   1413:     }
                   1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1415:     return $output.$banner_link;
                   1416: }
                   1417: 
                   1418: sub top_nav_help {
                   1419:     my ($text) = @_;
1.436     albertel 1420:     $text = &mt($text);
1.949     droeschl 1421:     my $stay_on_page = 1;
                   1422: 
1.1168    raeburn  1423:     my ($link,$banner_link);
                   1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1426: 	                         : "javascript:helpMenu('open')";
                   1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1428:     }
1.201     raeburn  1429:     my $title = &mt('Get help');
1.1168    raeburn  1430:     if ($link) {
                   1431:         return <<"END";
1.436     albertel 1432: $banner_link
1.1159    raeburn  1433: <a href="$link" title="$title">$text</a>
1.436     albertel 1434: END
1.1168    raeburn  1435:     } else {
                   1436:         return '&nbsp;'.$text.'&nbsp;';
                   1437:     }
1.436     albertel 1438: }
                   1439: 
                   1440: sub help_menu_js {
1.1154    raeburn  1441:     my ($httphost) = @_;
1.949     droeschl 1442:     my $stayOnPage = 1;
1.436     albertel 1443:     my $width = 620;
                   1444:     my $height = 600;
1.430     albertel 1445:     my $helptopic=&general_help();
1.1154    raeburn  1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1448:     my $start_page =
                   1449:         &Apache::loncommon::start_page('Help Menu', undef,
                   1450: 				       {'frameset'    => 1,
                   1451: 					'js_ready'    => 1,
1.1154    raeburn  1452:                                         'use_absolute' => $httphost,
1.331     albertel 1453: 					'add_entries' => {
1.1168    raeburn  1454: 					    'border' => '0', 
1.579     raeburn  1455: 					    'rows'   => "110,*",},});
1.331     albertel 1456:     my $end_page =
                   1457:         &Apache::loncommon::end_page({'frameset' => 1,
                   1458: 				      'js_ready' => 1,});
                   1459: 
1.436     albertel 1460:     my $template .= <<"ENDTEMPLATE";
                   1461: <script type="text/javascript">
1.877     bisitz   1462: // <![CDATA[
1.253     albertel 1463: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1464: var banner_link = '';
1.243     raeburn  1465: function helpMenu(target) {
                   1466:     var caller = this;
                   1467:     if (target == 'open') {
                   1468:         var newWindow = null;
                   1469:         try {
1.262     albertel 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1471:         }
                   1472:         catch(error) {
                   1473:             writeHelp(caller);
                   1474:             return;
                   1475:         }
                   1476:         if (newWindow) {
                   1477:             caller = newWindow;
                   1478:         }
1.193     raeburn  1479:     }
1.243     raeburn  1480:     writeHelp(caller);
                   1481:     return;
                   1482: }
                   1483: function writeHelp(caller) {
1.1168    raeburn  1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1486:     caller.document.close();
                   1487:     caller.focus();
1.193     raeburn  1488: }
1.877     bisitz   1489: // END LON-CAPA Internal -->
1.253     albertel 1490: // ]]>
1.436     albertel 1491: </script>
1.193     raeburn  1492: ENDTEMPLATE
                   1493:     return $template;
                   1494: }
                   1495: 
1.172     www      1496: sub help_open_bug {
                   1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1498:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1500:     $text = "" if (not defined $text);
                   1501: 	$stayOnPage=1;
1.184     albertel 1502:     $width = 600 if (not defined $width);
                   1503:     $height = 600 if (not defined $height);
1.172     www      1504: 
                   1505:     $topic=~s/\W+/\+/g;
                   1506:     my $link='';
                   1507:     my $template='';
1.379     albertel 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1510:     if (!$stayOnPage)
                   1511:     {
                   1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1513:     }
                   1514:     else
                   1515:     {
                   1516: 	$link = $url;
                   1517:     }
1.1314    raeburn  1518: 
                   1519:     my $target = ' target="_top"';
                   1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1521:         $target = '';
                   1522:     }
1.172     www      1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
                   1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('Report a Bug');
1.215     albertel 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
                   1540: }
                   1541: 
                   1542: sub help_open_faq {
                   1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1544:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1546:     $text = "" if (not defined $text);
                   1547: 	$stayOnPage=1;
                   1548:     $width = 350 if (not defined $width);
                   1549:     $height = 400 if (not defined $height);
                   1550: 
                   1551:     $topic=~s/\W+/\+/g;
                   1552:     my $link='';
                   1553:     my $template='';
                   1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1555:     if (!$stayOnPage)
                   1556:     {
                   1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1558:     }
                   1559:     else
                   1560:     {
                   1561: 	$link = $url;
                   1562:     }
                   1563: 
                   1564:     # Add the text
                   1565:     if ($text ne "")
                   1566:     {
                   1567: 	$template .= 
1.173     www      1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1570:     }
                   1571: 
                   1572:     # Add the graphic
1.179     matthew  1573:     my $title = &mt('View the FAQ');
1.215     albertel 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1575:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1577: ENDTEMPLATE
                   1578:     if ($text ne '') { $template.='</td></tr></table>' };
                   1579:     return $template;
                   1580: 
1.44      bowersj2 1581: }
1.37      matthew  1582: 
1.180     matthew  1583: ###############################################################
                   1584: ###############################################################
                   1585: 
1.45      matthew  1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &change_content_javascript():
1.256     matthew  1589: 
                   1590: This and the next function allow you to create small sections of an
                   1591: otherwise static HTML page that you can update on the fly with
                   1592: Javascript, even in Netscape 4.
                   1593: 
                   1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1595: must be written to the HTML page once. It will prove the Javascript
                   1596: function "change(name, content)". Calling the change function with the
                   1597: name of the section 
                   1598: you want to update, matching the name passed to C<changable_area>, and
                   1599: the new content you want to put in there, will put the content into
                   1600: that area.
                   1601: 
                   1602: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1603: to contain room for the original contents. You need to "make space"
                   1604: for whatever changes you wish to make, and be B<sure> to check your
                   1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1606: it's adequate for updating a one-line status display, but little more.
                   1607: This script will set the space to 100% width, so you only need to
                   1608: worry about height in Netscape 4.
                   1609: 
                   1610: Modern browsers are much less limiting, and if you can commit to the
                   1611: user not using Netscape 4, this feature may be used freely with
                   1612: pretty much any HTML.
                   1613: 
                   1614: =cut
                   1615: 
                   1616: sub change_content_javascript {
                   1617:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1618:     if ($env{'browser.type'} eq 'netscape' &&
                   1619: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1620: 	return (<<NETSCAPE4);
                   1621: 	function change(name, content) {
                   1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1623: 	    doc.open();
                   1624: 	    doc.write(content);
                   1625: 	    doc.close();
                   1626: 	}
                   1627: NETSCAPE4
                   1628:     } else {
                   1629: 	# Otherwise, we need to use semi-standards-compliant code
                   1630: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1631: 	# is really scary, and every useful browser supports it
                   1632: 	return (<<DOMBASED);
                   1633: 	function change(name, content) {
                   1634: 	    element = document.getElementById(name);
                   1635: 	    element.innerHTML = content;
                   1636: 	}
                   1637: DOMBASED
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &changable_area($name,$origContent):
1.256     matthew  1644: 
                   1645: This provides a "changable area" that can be modified on the fly via
                   1646: the Javascript code provided in C<change_content_javascript>. $name is
                   1647: the name you will use to reference the area later; do not repeat the
                   1648: same name on a given HTML page more then once. $origContent is what
                   1649: the area will originally contain, which can be left blank.
                   1650: 
                   1651: =cut
                   1652: 
                   1653: sub changable_area {
                   1654:     my ($name, $origContent) = @_;
                   1655: 
1.258     albertel 1656:     if ($env{'browser.type'} eq 'netscape' &&
                   1657: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1658: 	# If this is netscape 4, we need to use the Layer tag
                   1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1660:     } else {
                   1661: 	return "<span id='$name'>$origContent</span>";
                   1662:     }
                   1663: }
                   1664: 
                   1665: =pod
                   1666: 
1.648     raeburn  1667: =item * &viewport_geometry_js 
1.590     raeburn  1668: 
                   1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: 
                   1674: sub viewport_geometry_js { 
                   1675:     return <<"GEOMETRY";
                   1676: var Geometry = {};
                   1677: function init_geometry() {
                   1678:     if (Geometry.init) { return };
                   1679:     Geometry.init=1;
                   1680:     if (window.innerHeight) {
                   1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1685:     }
                   1686:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1687:         Geometry.getViewportHeight =
                   1688:             function() { return document.documentElement.clientHeight; };
                   1689:         Geometry.getViewportWidth =
                   1690:             function() { return document.documentElement.clientWidth; };
                   1691: 
                   1692:         Geometry.getHorizontalScroll =
                   1693:             function() { return document.documentElement.scrollLeft; };
                   1694:         Geometry.getVerticalScroll =
                   1695:             function() { return document.documentElement.scrollTop; };
                   1696:     }
                   1697:     else if (document.body.clientHeight) {
                   1698:         Geometry.getViewportHeight =
                   1699:             function() { return document.body.clientHeight; };
                   1700:         Geometry.getViewportWidth =
                   1701:             function() { return document.body.clientWidth; };
                   1702:         Geometry.getHorizontalScroll =
                   1703:             function() { return document.body.scrollLeft; };
                   1704:         Geometry.getVerticalScroll =
                   1705:             function() { return document.body.scrollTop; };
                   1706:     }
                   1707: }
                   1708: 
                   1709: GEOMETRY
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &viewport_size_js()
1.590     raeburn  1715: 
                   1716: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1717: 
                   1718: =cut
                   1719: 
                   1720: sub viewport_size_js {
                   1721:     my $geometry = &viewport_geometry_js();
                   1722:     return <<"DIMS";
                   1723: 
                   1724: $geometry
                   1725: 
                   1726: function getViewportDims(width,height) {
                   1727:     init_geometry();
                   1728:     width.value = Geometry.getViewportWidth();
                   1729:     height.value = Geometry.getViewportHeight();
                   1730:     return;
                   1731: }
                   1732: 
                   1733: DIMS
                   1734: }
                   1735: 
                   1736: =pod
                   1737: 
1.648     raeburn  1738: =item * &resize_textarea_js()
1.565     albertel 1739: 
                   1740: emits the needed javascript to resize a textarea to be as big as possible
                   1741: 
                   1742: creates a function resize_textrea that takes two IDs first should be
                   1743: the id of the element to resize, second should be the id of a div that
                   1744: surrounds everything that comes after the textarea, this routine needs
                   1745: to be attached to the <body> for the onload and onresize events.
                   1746: 
1.648     raeburn  1747: =back
1.565     albertel 1748: 
                   1749: =cut
                   1750: 
                   1751: sub resize_textarea_js {
1.590     raeburn  1752:     my $geometry = &viewport_geometry_js();
1.565     albertel 1753:     return <<"RESIZE";
                   1754:     <script type="text/javascript">
1.824     bisitz   1755: // <![CDATA[
1.590     raeburn  1756: $geometry
1.565     albertel 1757: 
1.588     albertel 1758: function getX(element) {
                   1759:     var x = 0;
                   1760:     while (element) {
                   1761: 	x += element.offsetLeft;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return x;
                   1765: }
                   1766: function getY(element) {
                   1767:     var y = 0;
                   1768:     while (element) {
                   1769: 	y += element.offsetTop;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return y;
                   1773: }
                   1774: 
                   1775: 
1.565     albertel 1776: function resize_textarea(textarea_id,bottom_id) {
                   1777:     init_geometry();
                   1778:     var textarea        = document.getElementById(textarea_id);
                   1779:     //alert(textarea);
                   1780: 
1.588     albertel 1781:     var textarea_top    = getY(textarea);
1.565     albertel 1782:     var textarea_height = textarea.offsetHeight;
                   1783:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1784:     var bottom_top      = getY(bottom);
1.565     albertel 1785:     var bottom_height   = bottom.offsetHeight;
                   1786:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1787:     var fudge           = 23;
1.565     albertel 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1789:     if (new_height < 300) {
                   1790: 	new_height = 300;
                   1791:     }
                   1792:     textarea.style.height=new_height+'px';
                   1793: }
1.824     bisitz   1794: // ]]>
1.565     albertel 1795: </script>
                   1796: RESIZE
                   1797: 
                   1798: }
                   1799: 
1.1205    golterma 1800: sub colorfuleditor_js {
1.1248    raeburn  1801:     my $browse_or_search;
                   1802:     my $respath;
                   1803:     my ($cnum,$cdom) = &crsauthor_url();
                   1804:     if ($cnum) {
                   1805:         $respath = "/res/$cdom/$cnum/";
                   1806:         my %js_lt = &Apache::lonlocal::texthash(
                   1807:             sunm => 'Sub-directory name',
                   1808:             save => 'Save page to make this permanent',
                   1809:         );
                   1810:         &js_escape(\%js_lt);
                   1811:         $browse_or_search = <<"END";
                   1812: 
                   1813:     function toggleChooser(form,element,titleid,only,search) {
                   1814:         var disp = 'none';
                   1815:         if (document.getElementById('chooser_'+element)) {
                   1816:             var curr = document.getElementById('chooser_'+element).style.display;
                   1817:             if (curr == 'none') {
                   1818:                 disp='inline';
                   1819:                 if (form.elements['chooser_'+element].length) {
                   1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1821:                         form.elements['chooser_'+element][i].checked = false;
                   1822:                     }
                   1823:                 }
                   1824:                 toggleResImport(form,element);
                   1825:             }
                   1826:             document.getElementById('chooser_'+element).style.display = disp;
                   1827:         }
                   1828:     }
                   1829: 
                   1830:     function toggleCrsFile(form,element,numdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1833:             if (curr == 'none') {
                   1834:                 if (numdirs) {
                   1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1836:                     if (numdirs > 1) {
                   1837:                         window['select1'+element+'_changed']();
                   1838:                     }
                   1839:                 }
                   1840:             } 
                   1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1842:             
                   1843:         }
                   1844:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1846:             if (document.getElementById('uploadcrsres_'+element)) {
                   1847:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1848:             }
                   1849:         }
                   1850:         return;
                   1851:     }
                   1852: 
                   1853:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1856:         }
                   1857:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1859:             if (curr == 'none') {
                   1860:                 if (numcrsdirs) {
                   1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1862:                    form.elements['newsubdir_'+element][0].checked = true;
                   1863:                    toggleNewsubdir(form,element);
                   1864:                 }
                   1865:             }
                   1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1867:         }
                   1868:         return;
                   1869:     }
                   1870: 
                   1871:     function toggleResImport(form,element) {
                   1872:         var choices = new Array('crsres','upload');
                   1873:         for (var i=0; i<choices.length; i++) {
                   1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1876:             }
                   1877:         }
                   1878:     }
                   1879: 
                   1880:     function toggleNewsubdir(form,element) {
                   1881:         var newsub = form.elements['newsubdir_'+element];
                   1882:         if (newsub) {
                   1883:             if (newsub.length) {
                   1884:                 for (var j=0; j<newsub.length; j++) {
                   1885:                     if (newsub[j].checked) {
                   1886:                         if (document.getElementById('newsubdirname_'+element)) {
                   1887:                             if (newsub[j].value == '1') {
                   1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1889:                                 if (document.getElementById('newsubdir_'+element)) {
                   1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1891:                                 }
                   1892:                             } else {
                   1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1894:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1896:                             }
                   1897:                         }
                   1898:                         break; 
                   1899:                     }
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904: 
                   1905:     function updateCrsFile(form,element) {
                   1906:         var directory = form.elements['coursepath_'+element];
                   1907:         var filename = form.elements['coursefile_'+element];
                   1908:         var path = directory.options[directory.selectedIndex].value;
                   1909:         var file = filename.options[filename.selectedIndex].value;
                   1910:         form.elements[element].value = '$respath';
                   1911:         if (path == '/') {
                   1912:             form.elements[element].value += file;
                   1913:         } else {
                   1914:             form.elements[element].value += path+'/'+file;
                   1915:         }
                   1916:         unClean();
                   1917:         if (document.getElementById('previewimg_'+element)) {
                   1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1920:         }
                   1921:         if (document.getElementById('showimg_'+element)) {
                   1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1923:         }
                   1924:         toggleChooser(form,element);
                   1925:         return;
                   1926:     }
                   1927: 
                   1928:     function uploadDone(suffix,name) {
                   1929:         if (name) {
                   1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1931:             unClean();
                   1932:             toggleChooser(document.forms["lonhomework"],suffix);
                   1933:         }
                   1934:     }
                   1935: 
                   1936: \$(document).ready(function(){
                   1937: 
                   1938:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1940:             var buttonId = this.id;
                   1941:             var suffix = buttonId.toString();
                   1942:             suffix = suffix.replace(/^crsupload_/,'');
                   1943:             event.preventDefault();
                   1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1946:             \$(this.form).submit();
                   1947:             document.lonhomework.target = '';
                   1948:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1950:             }
                   1951:             return false;
                   1952:         }
                   1953:     });
                   1954: });
                   1955: END
                   1956:     }
1.1205    golterma 1957:     return <<"COLORFULEDIT"
                   1958: <script type="text/javascript">
                   1959: // <![CDATA[>
                   1960:     function fold_box(curDepth, lastresource){
                   1961: 
                   1962:     // we need a list because there can be several blocks you need to fold in one tag
                   1963:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1964:     // but there is only one folding button per tag
                   1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1966: 
                   1967:         if(block.item(0).style.display == 'none'){
                   1968: 
                   1969:             foldbutton.value = '@{[&mt("Hide")]}';
                   1970:             for (i = 0; i < block.length; i++){
                   1971:                 block.item(i).style.display = '';
                   1972:             }
                   1973:         }else{
                   1974: 
                   1975:             foldbutton.value = '@{[&mt("Show")]}';
                   1976:             for (i = 0; i < block.length; i++){
                   1977:                 // block.item(i).style.visibility = 'collapse';
                   1978:                 block.item(i).style.display = 'none';
                   1979:             }
                   1980:         };
                   1981:         saveState(lastresource);
                   1982:     }
                   1983: 
                   1984:     function saveState (lastresource) {
                   1985: 
                   1986:         var tag_list = getTagList();
                   1987:         if(tag_list != null){
                   1988:             var timestamp = new Date().getTime();
                   1989:             var key = lastresource;
                   1990: 
                   1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1992:             // starting with timestamp
                   1993:             var value = timestamp+';';
                   1994: 
                   1995:             // building the list of key-value pairs
                   1996:             for(var i = 0; i < tag_list.length; i++){
                   1997:                 value += tag_list[i]+',';
                   1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1999:             }
                   2000: 
                   2001:             // only iterate whole storage if nothing to override
                   2002:             if(localStorage.getItem(key) == null){        
                   2003: 
                   2004:                 // prevent storage from growing large
                   2005:                 if(localStorage.length > 50){
                   2006:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2008:                     var oldest_key;
                   2009:                     
                   2010:                     for(var i = 1; i < localStorage.length; i++){
                   2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2012:                             oldest_key = localStorage.key(i);
                   2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2014:                         }
                   2015:                     }
                   2016:                     localStorage.removeItem(oldest_key);
                   2017:                 }
                   2018:             }
                   2019:             localStorage.setItem(key,value);
                   2020:         }
                   2021:     }
                   2022: 
                   2023:     // restore folding status of blocks (on page load)
                   2024:     function restoreState (lastresource) {
                   2025:         if(localStorage.getItem(lastresource) != null){
                   2026:             var key = lastresource;
                   2027:             var value = localStorage.getItem(key);
                   2028:             var regex_delTimestamp = /^\d+;/;
                   2029: 
                   2030:             value.replace(regex_delTimestamp, '');
                   2031: 
                   2032:             var valueArr = value.split(';');
                   2033:             var pairs;
                   2034:             var elements;
                   2035:             for (var i = 0; i < valueArr.length; i++){
                   2036:                 pairs = valueArr[i].split(',');
                   2037:                 elements = document.getElementsByName(pairs[0]);
                   2038: 
                   2039:                 for (var j = 0; j < elements.length; j++){  
                   2040:                     elements[j].style.display = pairs[1];
                   2041:                     if (pairs[1] == "none"){
                   2042:                         var regex_id = /([_\\d]+)\$/;
                   2043:                         regex_id.exec(pairs[0]);
                   2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2045:                     }
                   2046:                 }
                   2047:             }
                   2048:         }
                   2049:     }
                   2050: 
                   2051:     function getTagList () {
                   2052:         
                   2053:         var stringToSearch = document.lonhomework.innerHTML;
                   2054: 
                   2055:         var ret = new Array();
                   2056:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2057:         var tag_list = stringToSearch.match(regex_findBlock);
                   2058: 
                   2059:         if(tag_list != null){
                   2060:             for(var i = 0; i < tag_list.length; i++){            
                   2061:                 ret.push(tag_list[i].replace(/"/, ''));
                   2062:             }
                   2063:         }
                   2064:         return ret;
                   2065:     }
                   2066: 
                   2067:     function saveScrollPosition (resource) {
                   2068:         var tag_list = getTagList();
                   2069: 
                   2070:         // we dont always want to jump to the first block
                   2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2072:         if(\$(window).scrollTop() > 170){
                   2073:             if(tag_list != null){
                   2074:                 var result;
                   2075:                 for(var i = 0; i < tag_list.length; i++){
                   2076:                     if(isElementInViewport(tag_list[i])){
                   2077:                         result += tag_list[i]+';';
                   2078:                     }
                   2079:                 }
                   2080:                 sessionStorage.setItem('anchor_'+resource, result);
                   2081:             }
                   2082:         } else {
                   2083:             // we dont need to save zero, just delete the item to leave everything tidy
                   2084:             sessionStorage.removeItem('anchor_'+resource);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     function restoreScrollPosition(resource){
                   2089: 
                   2090:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2091:         if(elem != null){
                   2092:             var tag_list = elem.split(';');
                   2093:             var elem_list;
                   2094: 
                   2095:             for(var i = 0; i < tag_list.length; i++){
                   2096:                 elem_list = document.getElementsByName(tag_list[i]);
                   2097:                 
                   2098:                 if(elem_list.length > 0){
                   2099:                     elem = elem_list[0];
                   2100:                     break;
                   2101:                 }
                   2102:             }
                   2103:             elem.scrollIntoView();
                   2104:         }
                   2105:     }
                   2106: 
                   2107:     function isElementInViewport(el) {
                   2108: 
                   2109:         // change to last element instead of first
                   2110:         var elem = document.getElementsByName(el);
                   2111:         var rect = elem[0].getBoundingClientRect();
                   2112: 
                   2113:         return (
                   2114:             rect.top >= 0 &&
                   2115:             rect.left >= 0 &&
                   2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2118:         );
                   2119:     }
                   2120:     
                   2121:     function autosize(depth){
                   2122:         var cmInst = window['cm'+depth];
                   2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2124: 
                   2125:         // is fixed size, switching to dynamic
                   2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2127:             cmInst.setSize("","auto");
                   2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2129:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2130: 
                   2131:         // is dynamic size, switching to fixed
                   2132:         } else {
                   2133:             cmInst.setSize("","300px");
                   2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2135:             sessionStorage.removeItem("autosized_"+depth);
                   2136:         }
                   2137:     }
                   2138: 
1.1248    raeburn  2139: $browse_or_search
1.1205    golterma 2140: 
                   2141: // ]]>
                   2142: </script>
                   2143: COLORFULEDIT
                   2144: }
                   2145: 
                   2146: sub xmleditor_js {
                   2147:     return <<XMLEDIT
                   2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2149: <script type="text/javascript">
                   2150: // <![CDATA[>
                   2151: 
                   2152:     function saveScrollPosition (resource) {
                   2153: 
                   2154:         var scrollPos = \$(window).scrollTop();
                   2155:         sessionStorage.setItem(resource,scrollPos);
                   2156:     }
                   2157: 
                   2158:     function restoreScrollPosition(resource){
                   2159: 
                   2160:         var scrollPos = sessionStorage.getItem(resource);
                   2161:         \$(window).scrollTop(scrollPos);
                   2162:     }
                   2163: 
                   2164:     // unless internet explorer
                   2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2166: 
                   2167:         \$(document).ready(function() {
                   2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2169:         });
                   2170:     }
                   2171: 
                   2172:     // inserts text at cursor position into codemirror (xml editor only)
                   2173:     function insertText(text){
                   2174:         cm.focus();
                   2175:         var curPos = cm.getCursor();
                   2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2177:     }
                   2178: // ]]>
                   2179: </script>
                   2180: XMLEDIT
                   2181: }
                   2182: 
                   2183: sub insert_folding_button {
                   2184:     my $curDepth = $Apache::lonxml::curdepth;
                   2185:     my $lastresource = $env{'request.ambiguous'};
                   2186: 
                   2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2189: }
                   2190: 
1.1248    raeburn  2191: sub crsauthor_url {
                   2192:     my ($url) = @_;
                   2193:     if ($url eq '') {
                   2194:         $url = $ENV{'REQUEST_URI'};
                   2195:     }
                   2196:     my ($cnum,$cdom);
                   2197:     if ($env{'request.course.id'}) {
                   2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2199:         if ($audom ne '' && $auname ne '') {
                   2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2202:                 $cnum = $auname;
                   2203:                 $cdom = $audom;
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return ($cnum,$cdom);
                   2208: }
                   2209: 
                   2210: sub import_crsauthor_form {
1.1265    raeburn  2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2212:     return (0) unless ($env{'request.course.id'});
                   2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2218:     my @ids=&Apache::lonnet::current_machine_ids();
                   2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2220:     
                   2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2222:         $is_home = 1;
                   2223:     }
                   2224:     $relpath = "/priv/$cdom/$cnum";
                   2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2226:     my %lt = &Apache::lonlocal::texthash (
                   2227:         fnam => 'Filename',
                   2228:         dire => 'Directory',
                   2229:     );
                   2230:     my $numdirs = scalar(keys(%files));
                   2231:     my (%possexts,$singledir,@singledirfiles);
                   2232:     if ($only) {
                   2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2234:     }
                   2235:     my (%nonemptydirs,$possdirs);
                   2236:     if ($numdirs > 1) {
                   2237:         my @order;
                   2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2239:             if (ref($files{$key}) eq 'HASH') {
                   2240:                 my $shown = $key;
                   2241:                 if ($key eq '') {
                   2242:                     $shown = '/';
                   2243:                 }
                   2244:                 my @ordered = ();
                   2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2246:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2247:                     if ($only) {
                   2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2249:                         unless ($possexts{lc($ext)}) {
                   2250:                             next;
                   2251:                         }
                   2252:                     }
                   2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2254:                     push(@ordered,$file);
                   2255:                 }
                   2256:                 if (@ordered) {
                   2257:                     push(@order,$key);
                   2258:                     $nonemptydirs{$key} = 1;
                   2259:                     $selimport_menus{$key}->{'text'} = $shown;
                   2260:                     $selimport_menus{$key}->{'default'} = '';
                   2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2263:                 }
                   2264:             }
                   2265:         }
                   2266:         $possdirs = scalar(keys(%nonemptydirs));
                   2267:         if ($possdirs > 1) {
                   2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2269:             $output = $lt{'dire'}.
                   2270:                       &linked_select_forms($form,'<br />'.
                   2271:                                            $lt{'fnam'},'',
                   2272:                                            $firstselectname,$secondselectname,
                   2273:                                            \%selimport_menus,\@order,
                   2274:                                            $onchangefirst,'',$suffix).'<br />';
                   2275:         } elsif ($possdirs == 1) {
                   2276:             $singledir = (keys(%nonemptydirs))[0];
                   2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2279:             }
                   2280:             delete($selimport_menus{$singledir});
                   2281:         }
                   2282:     } elsif ($numdirs == 1) {
                   2283:         $singledir = (keys(%files))[0];
                   2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2285:             if ($only) {
                   2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2287:                 unless ($possexts{lc($ext)}) {
                   2288:                     next;
                   2289:                 }
1.1315    raeburn  2290:             } else {
                   2291:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2292:             }
                   2293:             push(@singledirfiles,$file);
                   2294:         }
                   2295:         if (@singledirfiles) {
1.1315    raeburn  2296:             $possdirs = 1;
1.1248    raeburn  2297:         }
                   2298:     }
                   2299:     if (($possdirs == 1) && (@singledirfiles)) {
                   2300:         my $showdir = $singledir;
                   2301:         if ($singledir eq '') {
                   2302:             $showdir = '/';
                   2303:         }
                   2304:         $output = $lt{'dire'}.
                   2305:                   '<select name="'.$firstselectname.'">'.
                   2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2307:                   '</select><br />'.
                   2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2310:         foreach my $file (@singledirfiles) {
                   2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2312:         }
                   2313:         $output .= '</select><br />'."\n";
                   2314:     }
                   2315:     return ($possdirs,$output);
                   2316: }
                   2317: 
1.565     albertel 2318: =pod
                   2319: 
1.256     matthew  2320: =head1 Excel and CSV file utility routines
                   2321: 
                   2322: =cut
                   2323: 
                   2324: ###############################################################
                   2325: ###############################################################
                   2326: 
                   2327: =pod
                   2328: 
1.1162    raeburn  2329: =over 4
                   2330: 
1.648     raeburn  2331: =item * &csv_translate($text) 
1.37      matthew  2332: 
1.185     www      2333: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2334: format.
                   2335: 
                   2336: =cut
                   2337: 
1.180     matthew  2338: ###############################################################
                   2339: ###############################################################
1.37      matthew  2340: sub csv_translate {
                   2341:     my $text = shift;
                   2342:     $text =~ s/\"/\"\"/g;
1.209     albertel 2343:     $text =~ s/\n/ /g;
1.37      matthew  2344:     return $text;
                   2345: }
1.180     matthew  2346: 
                   2347: ###############################################################
                   2348: ###############################################################
                   2349: 
                   2350: =pod
                   2351: 
1.648     raeburn  2352: =item * &define_excel_formats()
1.180     matthew  2353: 
                   2354: Define some commonly used Excel cell formats.
                   2355: 
                   2356: Currently supported formats:
                   2357: 
                   2358: =over 4
                   2359: 
                   2360: =item header
                   2361: 
                   2362: =item bold
                   2363: 
                   2364: =item h1
                   2365: 
                   2366: =item h2
                   2367: 
                   2368: =item h3
                   2369: 
1.256     matthew  2370: =item h4
                   2371: 
                   2372: =item i
                   2373: 
1.180     matthew  2374: =item date
                   2375: 
                   2376: =back
                   2377: 
                   2378: Inputs: $workbook
                   2379: 
                   2380: Returns: $format, a hash reference.
                   2381: 
1.1057    foxr     2382: 
1.180     matthew  2383: =cut
                   2384: 
                   2385: ###############################################################
                   2386: ###############################################################
                   2387: sub define_excel_formats {
                   2388:     my ($workbook) = @_;
                   2389:     my $format;
                   2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2391:                                                 bottom    => 1,
                   2392:                                                 align     => 'center');
                   2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2399:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2400:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2401:     return $format;
                   2402: }
                   2403: 
                   2404: ###############################################################
                   2405: ###############################################################
1.113     bowersj2 2406: 
                   2407: =pod
                   2408: 
1.648     raeburn  2409: =item * &create_workbook()
1.255     matthew  2410: 
                   2411: Create an Excel worksheet.  If it fails, output message on the
                   2412: request object and return undefs.
                   2413: 
                   2414: Inputs: Apache request object
                   2415: 
                   2416: Returns (undef) on failure, 
                   2417:     Excel worksheet object, scalar with filename, and formats 
                   2418:     from &Apache::loncommon::define_excel_formats on success
                   2419: 
                   2420: =cut
                   2421: 
                   2422: ###############################################################
                   2423: ###############################################################
                   2424: sub create_workbook {
                   2425:     my ($r) = @_;
                   2426:         #
                   2427:     # Create the excel spreadsheet
                   2428:     my $filename = '/prtspool/'.
1.258     albertel 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2430:         time.'_'.rand(1000000000).'.xls';
                   2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2432:     if (! defined($workbook)) {
                   2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2434:         $r->print(
                   2435:             '<p class="LC_error">'
                   2436:            .&mt('Problems occurred in creating the new Excel file.')
                   2437:            .' '.&mt('This error has been logged.')
                   2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2439:            .'</p>'
                   2440:         );
1.255     matthew  2441:         return (undef);
                   2442:     }
                   2443:     #
1.1014    foxr     2444:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2445:     #
                   2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2447:     return ($workbook,$filename,$format);
                   2448: }
                   2449: 
                   2450: ###############################################################
                   2451: ###############################################################
                   2452: 
                   2453: =pod
                   2454: 
1.648     raeburn  2455: =item * &create_text_file()
1.113     bowersj2 2456: 
1.542     raeburn  2457: Create a file to write to and eventually make available to the user.
1.256     matthew  2458: If file creation fails, outputs an error message on the request object and 
                   2459: return undefs.
1.113     bowersj2 2460: 
1.256     matthew  2461: Inputs: Apache request object, and file suffix
1.113     bowersj2 2462: 
1.256     matthew  2463: Returns (undef) on failure, 
                   2464:     Filehandle and filename on success.
1.113     bowersj2 2465: 
                   2466: =cut
                   2467: 
1.256     matthew  2468: ###############################################################
                   2469: ###############################################################
                   2470: sub create_text_file {
                   2471:     my ($r,$suffix) = @_;
                   2472:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2473:     my $fh;
                   2474:     my $filename = '/prtspool/'.
1.258     albertel 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2476:         time.'_'.rand(1000000000).'.'.$suffix;
                   2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2478:     if (! defined($fh)) {
                   2479:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2480:         $r->print(
                   2481:             '<p class="LC_error">'
                   2482:            .&mt('Problems occurred in creating the output file.')
                   2483:            .' '.&mt('This error has been logged.')
                   2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2485:            .'</p>'
                   2486:         );
1.113     bowersj2 2487:     }
1.256     matthew  2488:     return ($fh,$filename)
1.113     bowersj2 2489: }
                   2490: 
                   2491: 
1.256     matthew  2492: =pod 
1.113     bowersj2 2493: 
                   2494: =back
                   2495: 
                   2496: =cut
1.37      matthew  2497: 
                   2498: ###############################################################
1.33      matthew  2499: ##        Home server <option> list generating code          ##
                   2500: ###############################################################
1.35      matthew  2501: 
1.169     www      2502: # ------------------------------------------
                   2503: 
                   2504: sub domain_select {
1.1289    raeburn  2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2506:     my @possdoms;
                   2507:     if (ref($incdoms) eq 'ARRAY') {
                   2508:         @possdoms = @{$incdoms};
                   2509:     } else {
                   2510:         @possdoms = &Apache::lonnet::all_domains();
                   2511:     }
                   2512: 
1.169     www      2513:     my %domains=map { 
1.514     albertel 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2515:     } @possdoms;
                   2516: 
                   2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2518:         foreach my $dom (@{$excdoms}) {
                   2519:             delete($domains{$dom});
                   2520:         }
                   2521:     }
                   2522: 
1.169     www      2523:     if ($multiple) {
                   2524: 	$domains{''}=&mt('Any domain');
1.550     albertel 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2526: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2527:     } else {
1.550     albertel 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2529: 	return &select_form($name,$value,\%domains);
1.169     www      2530:     }
                   2531: }
                   2532: 
1.282     albertel 2533: #-------------------------------------------
                   2534: 
                   2535: =pod
                   2536: 
1.519     raeburn  2537: =head1 Routines for form select boxes
                   2538: 
                   2539: =over 4
                   2540: 
1.648     raeburn  2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2542: 
                   2543: Returns a string containing a <select> element int multiple mode
                   2544: 
                   2545: 
                   2546: Args:
                   2547:   $name - name of the <select> element
1.506     raeburn  2548:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2549:   $size - number of rows long the select element is
1.283     albertel 2550:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2551:           (shown text should already have been &mt())
1.506     raeburn  2552:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2553: 
1.282     albertel 2554: =cut
                   2555: 
                   2556: #-------------------------------------------
1.169     www      2557: sub multiple_select_form {
1.284     albertel 2558:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2560:     my $output='';
1.191     matthew  2561:     if (! defined($size)) {
                   2562:         $size = 4;
1.283     albertel 2563:         if (scalar(keys(%$hash))<4) {
                   2564:             $size = scalar(keys(%$hash));
1.191     matthew  2565:         }
                   2566:     }
1.734     bisitz   2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2568:     my @order;
1.506     raeburn  2569:     if (ref($order) eq 'ARRAY')  {
                   2570:         @order = @{$order};
                   2571:     } else {
                   2572:         @order = sort(keys(%$hash));
1.501     banghart 2573:     }
                   2574:     if (exists($$hash{'select_form_order'})) {
                   2575:         @order = @{$$hash{'select_form_order'}};
                   2576:     }
                   2577:         
1.284     albertel 2578:     foreach my $key (@order) {
1.356     albertel 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2580:         $output.='selected="selected" ' if ($selected{$key});
                   2581:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2582:     }
                   2583:     $output.="</select>\n";
                   2584:     return $output;
                   2585: }
                   2586: 
1.88      www      2587: #-------------------------------------------
                   2588: 
                   2589: =pod
                   2590: 
1.1254    raeburn  2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2592: 
                   2593: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2594: allow a user to select options from a ref to a hash containing:
                   2595: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2596: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2597: An optional arg -- $readonly -- if true will cause the select form
                   2598: to be disabled, e.g., for the case where an instructor has a section-
                   2599: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2600: 
1.88      www      2601: See lonrights.pm for an example invocation and use.
                   2602: 
                   2603: =cut
                   2604: 
                   2605: #-------------------------------------------
                   2606: sub select_form {
1.1228    raeburn  2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2608:     return unless (ref($hashref) eq 'HASH');
                   2609:     if ($onchange) {
                   2610:         $onchange = ' onchange="'.$onchange.'"';
                   2611:     }
1.1228    raeburn  2612:     my $disabled;
                   2613:     if ($readonly) {
                   2614:         $disabled = ' disabled="disabled"';
                   2615:     }
                   2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2617:     my @keys;
1.970     raeburn  2618:     if (exists($hashref->{'select_form_order'})) {
                   2619: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2620:     } else {
1.970     raeburn  2621: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2622:     }
1.356     albertel 2623:     foreach my $key (@keys) {
                   2624:         $selectform.=
                   2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2626:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2627:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2628:     }
                   2629:     $selectform.="</select>";
                   2630:     return $selectform;
                   2631: }
                   2632: 
1.475     www      2633: # For display filters
                   2634: 
                   2635: sub display_filter {
1.1074    raeburn  2636:     my ($context) = @_;
1.475     www      2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2639:     my $phraseinput = 'hidden';
                   2640:     my $includeinput = 'hidden';
                   2641:     my ($checked,$includetypestext);
                   2642:     if ($env{'form.displayfilter'} eq 'containing') {
                   2643:         $phraseinput = 'text'; 
                   2644:         if ($context eq 'parmslog') {
                   2645:             $includeinput = 'checkbox';
                   2646:             if ($env{'form.includetypes'}) {
                   2647:                 $checked = ' checked="checked"';
                   2648:             }
                   2649:             $includetypestext = &mt('Include parameter types');
                   2650:         }
                   2651:     } else {
                   2652:         $includetypestext = '&nbsp;';
                   2653:     }
                   2654:     my ($additional,$secondid,$thirdid);
                   2655:     if ($context eq 'parmslog') {
                   2656:         $additional = 
                   2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2660:             '</label>';
                   2661:         $secondid = 'includetypes';
                   2662:         $thirdid = 'includetypestext';
                   2663:     }
                   2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2665:                                                     '$secondid','$thirdid')";
                   2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2669: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2670:            &mt('Filter: [_1]',
1.477     www      2671: 	   &select_form($env{'form.displayfilter'},
                   2672: 			'displayfilter',
1.970     raeburn  2673: 			{'currentfolder' => 'Current folder/page',
1.477     www      2674: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2678:                          '" />'.$additional;
                   2679: }
                   2680: 
                   2681: sub display_filter_js {
                   2682:     my $includetext = &mt('Include parameter types');
                   2683:     return <<"ENDJS";
                   2684:   
                   2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2686:     var firstType = 'hidden';
                   2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2688:         firstType = 'text';
                   2689:     }
                   2690:     firstObject = document.getElementById(firstid);
                   2691:     if (typeof(firstObject) == 'object') {
                   2692:         if (firstObject.type != firstType) {
                   2693:             changeInputType(firstObject,firstType);
                   2694:         }
                   2695:     }
                   2696:     if (context == 'parmslog') {
                   2697:         var secondType = 'hidden';
                   2698:         if (firstType == 'text') {
                   2699:             secondType = 'checkbox';
                   2700:         }
                   2701:         secondObject = document.getElementById(secondid);  
                   2702:         if (typeof(secondObject) == 'object') {
                   2703:             if (secondObject.type != secondType) {
                   2704:                 changeInputType(secondObject,secondType);
                   2705:             }
                   2706:         }
                   2707:         var textItem = document.getElementById(thirdid);
                   2708:         var currtext = textItem.innerHTML;
                   2709:         var newtext;
                   2710:         if (firstType == 'text') {
                   2711:             newtext = '$includetext';
                   2712:         } else {
                   2713:             newtext = '&nbsp;';
                   2714:         }
                   2715:         if (currtext != newtext) {
                   2716:             textItem.innerHTML = newtext;
                   2717:         }
                   2718:     }
                   2719:     return;
                   2720: }
                   2721: 
                   2722: function changeInputType(oldObject,newType) {
                   2723:     var newObject = document.createElement('input');
                   2724:     newObject.type = newType;
                   2725:     if (oldObject.size) {
                   2726:         newObject.size = oldObject.size;
                   2727:     }
                   2728:     if (oldObject.value) {
                   2729:         newObject.value = oldObject.value;
                   2730:     }
                   2731:     if (oldObject.name) {
                   2732:         newObject.name = oldObject.name;
                   2733:     }
                   2734:     if (oldObject.id) {
                   2735:         newObject.id = oldObject.id;
                   2736:     }
                   2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2738:     return;
                   2739: }
                   2740: 
                   2741: ENDJS
1.475     www      2742: }
                   2743: 
1.167     www      2744: sub gradeleveldescription {
                   2745:     my $gradelevel=shift;
                   2746:     my %gradelevels=(0 => 'Not specified',
                   2747: 		     1 => 'Grade 1',
                   2748: 		     2 => 'Grade 2',
                   2749: 		     3 => 'Grade 3',
                   2750: 		     4 => 'Grade 4',
                   2751: 		     5 => 'Grade 5',
                   2752: 		     6 => 'Grade 6',
                   2753: 		     7 => 'Grade 7',
                   2754: 		     8 => 'Grade 8',
                   2755: 		     9 => 'Grade 9',
                   2756: 		     10 => 'Grade 10',
                   2757: 		     11 => 'Grade 11',
                   2758: 		     12 => 'Grade 12',
                   2759: 		     13 => 'Grade 13',
                   2760: 		     14 => '100 Level',
                   2761: 		     15 => '200 Level',
                   2762: 		     16 => '300 Level',
                   2763: 		     17 => '400 Level',
                   2764: 		     18 => 'Graduate Level');
                   2765:     return &mt($gradelevels{$gradelevel});
                   2766: }
                   2767: 
1.163     www      2768: sub select_level_form {
                   2769:     my ($deflevel,$name)=@_;
                   2770:     unless ($deflevel) { $deflevel=0; }
1.167     www      2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2772:     for (my $i=0; $i<=18; $i++) {
                   2773:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2775:                 ">".&gradeleveldescription($i)."</option>\n";
                   2776:     }
                   2777:     $selectform.="</select>";
                   2778:     return $selectform;
1.163     www      2779: }
1.167     www      2780: 
1.35      matthew  2781: #-------------------------------------------
                   2782: 
1.45      matthew  2783: =pod
                   2784: 
1.1256    raeburn  2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2786: 
                   2787: Returns a string containing a <select name='$name' size='1'> form to 
                   2788: allow a user to select the domain to preform an operation in.  
                   2789: See loncreateuser.pm for an example invocation and use.
                   2790: 
1.90      www      2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2792: selected");
                   2793: 
1.743     raeburn  2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2795: 
1.910     raeburn  2796: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2797: 
1.1121    raeburn  2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2799: 
                   2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2801: 
1.1256    raeburn  2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2803: 
1.35      matthew  2804: =cut
                   2805: 
                   2806: #-------------------------------------------
1.34      matthew  2807: sub select_dom_form {
1.1256    raeburn  2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2809:     if ($onchange) {
1.874     raeburn  2810:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2811:     }
1.1256    raeburn  2812:     if ($disabled) {
                   2813:         $disabled = ' disabled="disabled"';
                   2814:     }
1.1121    raeburn  2815:     my (@domains,%exclude);
1.910     raeburn  2816:     if (ref($incdoms) eq 'ARRAY') {
                   2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2818:     } else {
                   2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2820:     }
1.90      www      2821:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2822:     if (ref($excdoms) eq 'ARRAY') {
                   2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2824:     }
1.1256    raeburn  2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2826:     foreach my $dom (@domains) {
1.1121    raeburn  2827:         next if ($exclude{$dom});
1.356     albertel 2828:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2830:         if ($showdomdesc) {
                   2831:             if ($dom ne '') {
                   2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2833:                 if ($domdesc ne '') {
                   2834:                     $selectdomain .= ' ('.$domdesc.')';
                   2835:                 }
                   2836:             } 
                   2837:         }
                   2838:         $selectdomain .= "</option>\n";
1.34      matthew  2839:     }
                   2840:     $selectdomain.="</select>";
                   2841:     return $selectdomain;
                   2842: }
                   2843: 
1.35      matthew  2844: #-------------------------------------------
                   2845: 
1.45      matthew  2846: =pod
                   2847: 
1.648     raeburn  2848: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2849: 
1.586     raeburn  2850: input: 4 arguments (two required, two optional) - 
                   2851:     $domain - domain of new user
                   2852:     $name - name of form element
                   2853:     $default - Value of 'default' causes a default item to be first 
                   2854:                             option, and selected by default. 
                   2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2856:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2857: output: returns 2 items: 
1.586     raeburn  2858: (a) form element which contains either:
                   2859:    (i) <select name="$name">
                   2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2862:        </select>
                   2863:        form item if there are multiple library servers in $domain, or
                   2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2865:        if there is only one library server in $domain.
                   2866: 
                   2867: (b) number of library servers found.
                   2868: 
                   2869: See loncreateuser.pm for example of use.
1.35      matthew  2870: 
                   2871: =cut
                   2872: 
                   2873: #-------------------------------------------
1.586     raeburn  2874: sub home_server_form_item {
                   2875:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2877:     my $result;
                   2878:     my $numlib = keys(%servers);
                   2879:     if ($numlib > 1) {
                   2880:         $result .= '<select name="'.$name.'" />'."\n";
                   2881:         if ($default) {
1.804     bisitz   2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2883:                        '</option>'."\n";
                   2884:         }
                   2885:         foreach my $hostid (sort(keys(%servers))) {
                   2886:             $result.= '<option value="'.$hostid.'">'.
                   2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2888:         }
                   2889:         $result .= '</select>'."\n";
                   2890:     } elsif ($numlib == 1) {
                   2891:         my $hostid;
                   2892:         foreach my $item (keys(%servers)) {
                   2893:             $hostid = $item;
                   2894:         }
                   2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2896:                    $hostid.'" />';
                   2897:                    if (!$hide) {
                   2898:                        $result .= $hostid.' '.$servers{$hostid};
                   2899:                    }
                   2900:                    $result .= "\n";
                   2901:     } elsif ($default) {
                   2902:         $result .= '<input type="hidden" name="'.$name.
                   2903:                    '" value="default" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= &mt('default');
                   2906:                    }
                   2907:                    $result .= "\n";
1.33      matthew  2908:     }
1.586     raeburn  2909:     return ($result,$numlib);
1.33      matthew  2910: }
1.112     bowersj2 2911: 
                   2912: =pod
                   2913: 
1.534     albertel 2914: =back 
                   2915: 
1.112     bowersj2 2916: =cut
1.87      matthew  2917: 
                   2918: ###############################################################
1.112     bowersj2 2919: ##                  Decoding User Agent                      ##
1.87      matthew  2920: ###############################################################
                   2921: 
                   2922: =pod
                   2923: 
1.112     bowersj2 2924: =head1 Decoding the User Agent
                   2925: 
                   2926: =over 4
                   2927: 
                   2928: =item * &decode_user_agent()
1.87      matthew  2929: 
                   2930: Inputs: $r
                   2931: 
                   2932: Outputs:
                   2933: 
                   2934: =over 4
                   2935: 
1.112     bowersj2 2936: =item * $httpbrowser
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientbrowser
1.87      matthew  2939: 
1.112     bowersj2 2940: =item * $clientversion
1.87      matthew  2941: 
1.112     bowersj2 2942: =item * $clientmathml
1.87      matthew  2943: 
1.112     bowersj2 2944: =item * $clientunicode
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientos
1.87      matthew  2947: 
1.1137    raeburn  2948: =item * $clientmobile
                   2949: 
1.1141    raeburn  2950: =item * $clientinfo
                   2951: 
1.1194    raeburn  2952: =item * $clientosversion
                   2953: 
1.87      matthew  2954: =back
                   2955: 
1.157     matthew  2956: =back 
                   2957: 
1.87      matthew  2958: =cut
                   2959: 
                   2960: ###############################################################
                   2961: ###############################################################
                   2962: sub decode_user_agent {
1.247     albertel 2963:     my ($r)=@_;
1.87      matthew  2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2968:     my $clientbrowser='unknown';
                   2969:     my $clientversion='0';
                   2970:     my $clientmathml='';
                   2971:     my $clientunicode='0';
1.1137    raeburn  2972:     my $clientmobile=0;
1.1194    raeburn  2973:     my $clientosversion='';
1.87      matthew  2974:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2977: 	    $clientbrowser=$bname;
                   2978:             $httpbrowser=~/$vreg/i;
                   2979: 	    $clientversion=$1;
                   2980:             $clientmathml=($clientversion>=$minv);
                   2981:             $clientunicode=($clientversion>=$univ);
                   2982: 	}
                   2983:     }
                   2984:     my $clientos='unknown';
1.1141    raeburn  2985:     my $clientinfo;
1.87      matthew  2986:     if (($httpbrowser=~/linux/i) ||
                   2987:         ($httpbrowser=~/unix/i) ||
                   2988:         ($httpbrowser=~/ux/i) ||
                   2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2990:     if (($httpbrowser=~/vax/i) ||
                   2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2993:     if (($httpbrowser=~/mac/i) ||
                   2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2995:     if ($httpbrowser=~/win/i) {
                   2996:         $clientos='win';
                   2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2998:             $clientosversion = $1;
                   2999:         }
                   3000:     }
1.87      matthew  3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3003:         $clientmobile=lc($1);
                   3004:     }
1.1141    raeburn  3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3006:         $clientinfo = 'firefox-'.$1;
                   3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3008:         $clientinfo = 'chromeframe-'.$1;
                   3009:     }
1.87      matthew  3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3012:             $clientosversion);
1.87      matthew  3013: }
                   3014: 
1.32      matthew  3015: ###############################################################
                   3016: ##    Authentication changing form generation subroutines    ##
                   3017: ###############################################################
                   3018: ##
                   3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3020: ## hash, and have reasonable default values.
                   3021: ##
                   3022: ##    formname = the name given in the <form> tag.
1.35      matthew  3023: #-------------------------------------------
                   3024: 
1.45      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =head1 Authentication Routines
                   3028: 
                   3029: =over 4
                   3030: 
1.648     raeburn  3031: =item * &authform_xxxxxx()
1.35      matthew  3032: 
                   3033: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3034: handle some of the conveniences required for authentication forms.  
                   3035: This is not an optimal method, but it works.  
                   3036: 
                   3037: =over 4
                   3038: 
1.112     bowersj2 3039: =item * authform_header
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_authorwarning
1.35      matthew  3042: 
1.112     bowersj2 3043: =item * authform_nochange
1.35      matthew  3044: 
1.112     bowersj2 3045: =item * authform_kerberos
1.35      matthew  3046: 
1.112     bowersj2 3047: =item * authform_internal
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_filesystem
1.35      matthew  3050: 
1.1310    raeburn  3051: =item * authform_lti
                   3052: 
1.35      matthew  3053: =back
                   3054: 
1.648     raeburn  3055: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3056: 
1.35      matthew  3057: =cut
                   3058: 
                   3059: #-------------------------------------------
1.32      matthew  3060: sub authform_header{  
                   3061:     my %in = (
                   3062:         formname => 'cu',
1.80      albertel 3063:         kerb_def_dom => '',
1.32      matthew  3064:         @_,
                   3065:     );
                   3066:     $in{'formname'} = 'document.' . $in{'formname'};
                   3067:     my $result='';
1.80      albertel 3068: 
                   3069: #---------------------------------------------- Code for upper case translation
                   3070:     my $Javascript_toUpperCase;
                   3071:     unless ($in{kerb_def_dom}) {
                   3072:         $Javascript_toUpperCase =<<"END";
                   3073:         switch (choice) {
                   3074:            case 'krb': currentform.elements[choicearg].value =
                   3075:                currentform.elements[choicearg].value.toUpperCase();
                   3076:                break;
                   3077:            default:
                   3078:         }
                   3079: END
                   3080:     } else {
                   3081:         $Javascript_toUpperCase = "";
                   3082:     }
                   3083: 
1.165     raeburn  3084:     my $radioval = "'nochange'";
1.591     raeburn  3085:     if (defined($in{'curr_authtype'})) {
                   3086:         if ($in{'curr_authtype'} ne '') {
                   3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3088:         }
1.174     matthew  3089:     }
1.165     raeburn  3090:     my $argfield = 'null';
1.591     raeburn  3091:     if (defined($in{'mode'})) {
1.165     raeburn  3092:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3093:             if (defined($in{'curr_autharg'})) {
                   3094:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3095:                     $argfield = "'$in{'curr_autharg'}'";
                   3096:                 }
                   3097:             }
                   3098:         }
                   3099:     }
                   3100: 
1.32      matthew  3101:     $result.=<<"END";
                   3102: var current = new Object();
1.165     raeburn  3103: current.radiovalue = $radioval;
                   3104: current.argfield = $argfield;
1.32      matthew  3105: 
                   3106: function changed_radio(choice,currentform) {
                   3107:     var choicearg = choice + 'arg';
                   3108:     // If a radio button in changed, we need to change the argfield
                   3109:     if (current.radiovalue != choice) {
                   3110:         current.radiovalue = choice;
                   3111:         if (current.argfield != null) {
                   3112:             currentform.elements[current.argfield].value = '';
                   3113:         }
                   3114:         if (choice == 'nochange') {
                   3115:             current.argfield = null;
                   3116:         } else {
                   3117:             current.argfield = choicearg;
                   3118:             switch(choice) {
                   3119:                 case 'krb': 
                   3120:                     currentform.elements[current.argfield].value = 
                   3121:                         "$in{'kerb_def_dom'}";
                   3122:                 break;
                   3123:               default:
                   3124:                 break;
                   3125:             }
                   3126:         }
                   3127:     }
                   3128:     return;
                   3129: }
1.22      www      3130: 
1.32      matthew  3131: function changed_text(choice,currentform) {
                   3132:     var choicearg = choice + 'arg';
                   3133:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3134:         $Javascript_toUpperCase
1.32      matthew  3135:         // clear old field
                   3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3137:             currentform.elements[current.argfield].value = '';
                   3138:         }
                   3139:         current.argfield = choicearg;
                   3140:     }
                   3141:     set_auth_radio_buttons(choice,currentform);
                   3142:     return;
1.20      www      3143: }
1.32      matthew  3144: 
                   3145: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3146:     var numauthchoices = currentform.login.length;
                   3147:     if (typeof numauthchoices  == "undefined") {
                   3148:         return;
                   3149:     } 
1.32      matthew  3150:     var i=0;
1.986     raeburn  3151:     while (i < numauthchoices) {
1.32      matthew  3152:         if (currentform.login[i].value == newvalue) { break; }
                   3153:         i++;
                   3154:     }
1.986     raeburn  3155:     if (i == numauthchoices) {
1.32      matthew  3156:         return;
                   3157:     }
                   3158:     current.radiovalue = newvalue;
                   3159:     currentform.login[i].checked = true;
                   3160:     return;
                   3161: }
                   3162: END
                   3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_authorwarning {
1.32      matthew  3167:     my $result='';
1.144     matthew  3168:     $result='<i>'.
                   3169:         &mt('As a general rule, only authors or co-authors should be '.
                   3170:             'filesystem authenticated '.
                   3171:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3172:     return $result;
                   3173: }
                   3174: 
1.1106    raeburn  3175: sub authform_nochange {
1.32      matthew  3176:     my %in = (
                   3177:               formname => 'document.cu',
                   3178:               kerb_def_dom => 'MSU.EDU',
                   3179:               @_,
                   3180:           );
1.1106    raeburn  3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3182:     my $result;
1.1104    raeburn  3183:     if (!$authnum) {
1.1105    raeburn  3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3185:     } else {
                   3186:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3187:                   '<input type="radio" name="login" value="nochange" '.
                   3188:                   'checked="checked" onclick="'.
1.281     albertel 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3190: 	    '</label>';
1.586     raeburn  3191:     }
1.32      matthew  3192:     return $result;
                   3193: }
                   3194: 
1.591     raeburn  3195: sub authform_kerberos {
1.32      matthew  3196:     my %in = (
                   3197:               formname => 'document.cu',
                   3198:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3199:               kerb_def_auth => 'krb4',
1.32      matthew  3200:               @_,
                   3201:               );
1.586     raeburn  3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3203:         $autharg,$jscall,$disabled);
1.1106    raeburn  3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3206:        $check5 = ' checked="checked"';
1.80      albertel 3207:     } else {
1.772     bisitz   3208:        $check4 = ' checked="checked"';
1.80      albertel 3209:     }
1.1259    raeburn  3210:     if ($in{'readonly'}) {
                   3211:         $disabled = ' disabled="disabled"';
                   3212:     }
1.165     raeburn  3213:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3214:     if (defined($in{'curr_authtype'})) {
                   3215:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3216:             $krbcheck = ' checked="checked"';
1.623     raeburn  3217:             if (defined($in{'mode'})) {
                   3218:                 if ($in{'mode'} eq 'modifyuser') {
                   3219:                     $krbcheck = '';
                   3220:                 }
                   3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_kerb_ver'})) {
                   3223:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3224:                     $check5 = ' checked="checked"';
1.591     raeburn  3225:                     $check4 = '';
                   3226:                 } else {
1.772     bisitz   3227:                     $check4 = ' checked="checked"';
1.591     raeburn  3228:                     $check5 = '';
                   3229:                 }
1.586     raeburn  3230:             }
1.591     raeburn  3231:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3232:                 $krbarg = $in{'curr_autharg'};
                   3233:             }
1.586     raeburn  3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3235:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3236:                     $result = 
                   3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3238:         $in{'curr_autharg'},$krbver);
                   3239:                 } else {
                   3240:                     $result =
                   3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3242:                 }
                   3243:                 return $result; 
                   3244:             }
                   3245:         }
                   3246:     } else {
                   3247:         if ($authnum == 1) {
1.784     bisitz   3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3249:         }
                   3250:     }
1.586     raeburn  3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3252:         return;
1.587     raeburn  3253:     } elsif ($authtype eq '') {
1.591     raeburn  3254:         if (defined($in{'mode'})) {
1.587     raeburn  3255:             if ($in{'mode'} eq 'modifycourse') {
                   3256:                 if ($authnum == 1) {
1.1259    raeburn  3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3258:                 }
                   3259:             }
                   3260:         }
1.586     raeburn  3261:     }
                   3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3263:     if ($authtype eq '') {
                   3264:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3266:                     $krbcheck.$disabled.' />';
1.586     raeburn  3267:     }
                   3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3270:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3272:          $in{'curr_authtype'} eq 'krb4')) {
                   3273:         $result .= &mt
1.144     matthew  3274:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3276:          '<label>'.$authtype,
1.281     albertel 3277:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3278:              'value="'.$krbarg.'" '.
1.1259    raeburn  3279:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3282: 	 '</label>');
1.586     raeburn  3283:     } elsif ($can_assign{'krb4'}) {
                   3284:         $result .= &mt
                   3285:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3286:          '[_3] Version 4 [_4]',
                   3287:          '<label>'.$authtype,
                   3288:          '</label><input type="text" size="10" name="krbarg" '.
                   3289:              'value="'.$krbarg.'" '.
1.1259    raeburn  3290:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3291:          '<label><input type="hidden" name="krbver" value="4" />',
                   3292:          '</label>');
                   3293:     } elsif ($can_assign{'krb5'}) {
                   3294:         $result .= &mt
                   3295:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3296:          '[_3] Version 5 [_4]',
                   3297:          '<label>'.$authtype,
                   3298:          '</label><input type="text" size="10" name="krbarg" '.
                   3299:              'value="'.$krbarg.'" '.
1.1259    raeburn  3300:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3301:          '<label><input type="hidden" name="krbver" value="5" />',
                   3302:          '</label>');
                   3303:     }
1.32      matthew  3304:     return $result;
                   3305: }
                   3306: 
1.1106    raeburn  3307: sub authform_internal {
1.586     raeburn  3308:     my %in = (
1.32      matthew  3309:                 formname => 'document.cu',
                   3310:                 kerb_def_dom => 'MSU.EDU',
                   3311:                 @_,
                   3312:                 );
1.1259    raeburn  3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3315:     if ($in{'readonly'}) {
                   3316:         $disabled = ' disabled="disabled"';
                   3317:     }
1.591     raeburn  3318:     if (defined($in{'curr_authtype'})) {
                   3319:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3320:             if ($can_assign{'int'}) {
1.772     bisitz   3321:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3322:                 if (defined($in{'mode'})) {
                   3323:                     if ($in{'mode'} eq 'modifyuser') {
                   3324:                         $intcheck = '';
                   3325:                     }
                   3326:                 }
1.591     raeburn  3327:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3328:                     $intarg = $in{'curr_autharg'};
                   3329:                 }
                   3330:             } else {
                   3331:                 $result = &mt('Currently internally authenticated.');
                   3332:                 return $result;
1.165     raeburn  3333:             }
                   3334:         }
1.586     raeburn  3335:     } else {
                   3336:         if ($authnum == 1) {
1.784     bisitz   3337:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3338:         }
                   3339:     }
                   3340:     if (!$can_assign{'int'}) {
                   3341:         return;
1.587     raeburn  3342:     } elsif ($authtype eq '') {
1.591     raeburn  3343:         if (defined($in{'mode'})) {
1.587     raeburn  3344:             if ($in{'mode'} eq 'modifycourse') {
                   3345:                 if ($authnum == 1) {
1.1259    raeburn  3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3347:                 }
                   3348:             }
                   3349:         }
1.165     raeburn  3350:     }
1.586     raeburn  3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3352:     if ($authtype eq '') {
                   3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3355:     }
1.605     bisitz   3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3358:     $result = &mt
1.144     matthew  3359:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3360:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3361:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3362:     return $result;
                   3363: }
                   3364: 
1.1104    raeburn  3365: sub authform_local {
1.32      matthew  3366:     my %in = (
                   3367:               formname => 'document.cu',
                   3368:               kerb_def_dom => 'MSU.EDU',
                   3369:               @_,
                   3370:               );
1.1259    raeburn  3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3373:     if ($in{'readonly'}) {
                   3374:         $disabled = ' disabled="disabled"';
                   3375:     } 
1.591     raeburn  3376:     if (defined($in{'curr_authtype'})) {
                   3377:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3378:             if ($can_assign{'loc'}) {
1.772     bisitz   3379:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3380:                 if (defined($in{'mode'})) {
                   3381:                     if ($in{'mode'} eq 'modifyuser') {
                   3382:                         $loccheck = '';
                   3383:                     }
                   3384:                 }
1.591     raeburn  3385:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3386:                     $locarg = $in{'curr_autharg'};
                   3387:                 }
                   3388:             } else {
                   3389:                 $result = &mt('Currently using local (institutional) authentication.');
                   3390:                 return $result;
1.165     raeburn  3391:             }
                   3392:         }
1.586     raeburn  3393:     } else {
                   3394:         if ($authnum == 1) {
1.784     bisitz   3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3396:         }
                   3397:     }
                   3398:     if (!$can_assign{'loc'}) {
                   3399:         return;
1.587     raeburn  3400:     } elsif ($authtype eq '') {
1.591     raeburn  3401:         if (defined($in{'mode'})) {
1.587     raeburn  3402:             if ($in{'mode'} eq 'modifycourse') {
                   3403:                 if ($authnum == 1) {
1.1259    raeburn  3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3405:                 }
                   3406:             }
                   3407:         }
1.165     raeburn  3408:     }
1.586     raeburn  3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3410:     if ($authtype eq '') {
                   3411:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3413:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3414:     }
                   3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3418:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3419:     return $result;
                   3420: }
                   3421: 
1.1106    raeburn  3422: sub authform_filesystem {
1.32      matthew  3423:     my %in = (
                   3424:               formname => 'document.cu',
                   3425:               kerb_def_dom => 'MSU.EDU',
                   3426:               @_,
                   3427:               );
1.1259    raeburn  3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3430:     if ($in{'readonly'}) {
                   3431:         $disabled = ' disabled="disabled"';
                   3432:     }
1.591     raeburn  3433:     if (defined($in{'curr_authtype'})) {
                   3434:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3435:             if ($can_assign{'fsys'}) {
1.772     bisitz   3436:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3437:                 if (defined($in{'mode'})) {
                   3438:                     if ($in{'mode'} eq 'modifyuser') {
                   3439:                         $fsyscheck = '';
                   3440:                     }
                   3441:                 }
1.586     raeburn  3442:             } else {
                   3443:                 $result = &mt('Currently Filesystem Authenticated.');
                   3444:                 return $result;
1.1259    raeburn  3445:             }
1.586     raeburn  3446:         }
                   3447:     } else {
                   3448:         if ($authnum == 1) {
1.784     bisitz   3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3450:         }
                   3451:     }
                   3452:     if (!$can_assign{'fsys'}) {
                   3453:         return;
1.587     raeburn  3454:     } elsif ($authtype eq '') {
1.591     raeburn  3455:         if (defined($in{'mode'})) {
1.587     raeburn  3456:             if ($in{'mode'} eq 'modifycourse') {
                   3457:                 if ($authnum == 1) {
1.1259    raeburn  3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3459:                 }
                   3460:             }
                   3461:         }
1.586     raeburn  3462:     }
                   3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3464:     if ($authtype eq '') {
                   3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3467:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3468:     }
1.1310    raeburn  3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3471:     $result = &mt
1.144     matthew  3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3473:          '<label>'.$authtype,'</label>'.$autharg);
                   3474:     return $result;
                   3475: }
                   3476: 
                   3477: sub authform_lti {
                   3478:     my %in = (
                   3479:               formname => 'document.cu',
                   3480:               kerb_def_dom => 'MSU.EDU',
                   3481:               @_,
                   3482:               );
                   3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3485:     if ($in{'readonly'}) {
                   3486:         $disabled = ' disabled="disabled"';
                   3487:     }
                   3488:     if (defined($in{'curr_authtype'})) {
                   3489:         if ($in{'curr_authtype'} eq 'lti') {
                   3490:             if ($can_assign{'lti'}) {
                   3491:                 $lticheck = 'checked="checked" ';
                   3492:                 if (defined($in{'mode'})) {
                   3493:                     if ($in{'mode'} eq 'modifyuser') {
                   3494:                         $lticheck = '';
                   3495:                     }
                   3496:                 }
                   3497:             } else {
                   3498:                 $result = &mt('Currently LTI Authenticated.');
                   3499:                 return $result;
                   3500:             }
                   3501:         }
                   3502:     } else {
                   3503:         if ($authnum == 1) {
                   3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3505:         }
                   3506:     }
                   3507:     if (!$can_assign{'lti'}) {
                   3508:         return;
                   3509:     } elsif ($authtype eq '') {
                   3510:         if (defined($in{'mode'})) {
                   3511:             if ($in{'mode'} eq 'modifycourse') {
                   3512:                 if ($authnum == 1) {
                   3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3514:                 }
                   3515:             }
                   3516:         }
                   3517:     }
                   3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3520:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3522:                     $jscall.'"'.$disabled.' />';
                   3523:     }
                   3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3525:     if ($authtype) {
                   3526:         $result = &mt('[_1] LTI Authenticated',
                   3527:                       '<label>'.$authtype.'</label>'.$autharg);
                   3528:     } else {
                   3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3530:                   $autharg;
                   3531:     }
1.32      matthew  3532:     return $result;
                   3533: }
                   3534: 
1.586     raeburn  3535: sub get_assignable_auth {
                   3536:     my ($dom) = @_;
                   3537:     if ($dom eq '') {
                   3538:         $dom = $env{'request.role.domain'};
                   3539:     }
                   3540:     my %can_assign = (
                   3541:                           krb4 => 1,
                   3542:                           krb5 => 1,
                   3543:                           int  => 1,
                   3544:                           loc  => 1,
1.1310    raeburn  3545:                           lti  => 1,
1.586     raeburn  3546:                      );
                   3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3551:             my $context;
                   3552:             if ($env{'request.role'} =~ /^au/) {
                   3553:                 $context = 'author';
1.1259    raeburn  3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3555:                 $context = 'domain';
                   3556:             } elsif ($env{'request.course.id'}) {
                   3557:                 $context = 'course';
                   3558:             }
                   3559:             if ($context) {
                   3560:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3561:                    %can_assign = %{$authhash->{$context}}; 
                   3562:                 }
                   3563:             }
                   3564:         }
                   3565:     }
                   3566:     my $authnum = 0;
                   3567:     foreach my $key (keys(%can_assign)) {
                   3568:         if ($can_assign{$key}) {
                   3569:             $authnum ++;
                   3570:         }
                   3571:     }
                   3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3573:         $authnum --;
                   3574:     }
                   3575:     return ($authnum,%can_assign);
                   3576: }
                   3577: 
1.1331    raeburn  3578: sub check_passwd_rules {
                   3579:     my ($domain,$plainpass) = @_;
                   3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3581:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3582:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3585:             if ($passwdconf{'min'} > $min) {
                   3586:                 $min = $passwdconf{'min'};
                   3587:             }
1.1331    raeburn  3588:         }
                   3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3590:             $max = $passwdconf{'max'};
                   3591:         }
                   3592:         @chars = @{$passwdconf{'chars'}};
                   3593:     }
                   3594:     if (($min) && (length($plainpass) < $min)) {
                   3595:         push(@brokerule,'min');
                   3596:     }
                   3597:     if (($max) && (length($plainpass) > $max)) {
                   3598:         push(@brokerule,'max');
                   3599:     }
                   3600:     if (@chars) {
                   3601:         my %rules;
                   3602:         map { $rules{$_} = 1; } @chars;
                   3603:         if ($rules{'uc'}) {
                   3604:             unless ($plainpass =~ /[A-Z]/) {
                   3605:                 push(@brokerule,'uc');
                   3606:             }
                   3607:         }
                   3608:         if ($rules{'lc'}) {
1.1332    raeburn  3609:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3610:                 push(@brokerule,'lc');
                   3611:             }
                   3612:         }
                   3613:         if ($rules{'num'}) {
                   3614:             unless ($plainpass =~ /\d/) {
                   3615:                 push(@brokerule,'num');
                   3616:             }
                   3617:         }
                   3618:         if ($rules{'spec'}) {
                   3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3620:                 push(@brokerule,'spec');
                   3621:             }
                   3622:         }
                   3623:     }
                   3624:     if (@brokerule) {
                   3625:         my %rulenames = &Apache::lonlocal::texthash(
                   3626:             uc   => 'At least one upper case letter',
                   3627:             lc   => 'At least one lower case letter',
                   3628:             num  => 'At least one number',
                   3629:             spec => 'At least one non-alphanumeric',
                   3630:         );
                   3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3633:         $rulenames{'num'} .= ': 0123456789';
                   3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3639:             if (grep(/^$rule$/,@brokerule)) {
                   3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3641:             }
                   3642:         }
                   3643:         $warning .= '</ul>';
                   3644:     }
1.1332    raeburn  3645:     if (wantarray) {
                   3646:         return @brokerule;
                   3647:     }
1.1331    raeburn  3648:     return $warning;
                   3649: }
                   3650: 
1.80      albertel 3651: ###############################################################
                   3652: ##    Get Kerberos Defaults for Domain                 ##
                   3653: ###############################################################
                   3654: ##
                   3655: ## Returns default kerberos version and an associated argument
                   3656: ## as listed in file domain.tab. If not listed, provides
                   3657: ## appropriate default domain and kerberos version.
                   3658: ##
                   3659: #-------------------------------------------
                   3660: 
                   3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &get_kerberos_defaults()
1.80      albertel 3664: 
                   3665: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3666: version and domain. If not found, it defaults to version 4 and the 
                   3667: domain of the server.
1.80      albertel 3668: 
1.648     raeburn  3669: =over 4
                   3670: 
1.80      albertel 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3672: 
1.648     raeburn  3673: =back
                   3674: 
                   3675: =back
                   3676: 
1.80      albertel 3677: =cut
                   3678: 
                   3679: #-------------------------------------------
                   3680: sub get_kerberos_defaults {
                   3681:     my $domain=shift;
1.641     raeburn  3682:     my ($krbdef,$krbdefdom);
                   3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3685:         $krbdef = $domdefaults{'auth_def'};
                   3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3687:     } else {
1.80      albertel 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3689:         my $krbdefdom=$1;
                   3690:         $krbdefdom=~tr/a-z/A-Z/;
                   3691:         $krbdef = "krb4";
                   3692:     }
                   3693:     return ($krbdef,$krbdefdom);
                   3694: }
1.112     bowersj2 3695: 
1.32      matthew  3696: 
1.46      matthew  3697: ###############################################################
                   3698: ##                Thesaurus Functions                        ##
                   3699: ###############################################################
1.20      www      3700: 
1.46      matthew  3701: =pod
1.20      www      3702: 
1.112     bowersj2 3703: =head1 Thesaurus Functions
                   3704: 
                   3705: =over 4
                   3706: 
1.648     raeburn  3707: =item * &initialize_keywords()
1.46      matthew  3708: 
                   3709: Initializes the package variable %Keywords if it is empty.  Uses the
                   3710: package variable $thesaurus_db_file.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: ###################################################
                   3715: 
                   3716: sub initialize_keywords {
                   3717:     return 1 if (scalar keys(%Keywords));
                   3718:     # If we are here, %Keywords is empty, so fill it up
                   3719:     #   Make sure the file we need exists...
                   3720:     if (! -e $thesaurus_db_file) {
                   3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3722:                                  " failed because it does not exist");
                   3723:         return 0;
                   3724:     }
                   3725:     #   Set up the hash as a database
                   3726:     my %thesaurus_db;
                   3727:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3730:                                  $thesaurus_db_file);
                   3731:         return 0;
                   3732:     } 
                   3733:     #  Get the average number of appearances of a word.
                   3734:     my $avecount = $thesaurus_db{'average.count'};
                   3735:     #  Put keywords (those that appear > average) into %Keywords
                   3736:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3737:         my ($count,undef) = split /:/,$data;
                   3738:         $Keywords{$word}++ if ($count > $avecount);
                   3739:     }
                   3740:     untie %thesaurus_db;
                   3741:     # Remove special values from %Keywords.
1.356     albertel 3742:     foreach my $value ('total.count','average.count') {
                   3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3744:   }
1.46      matthew  3745:     return 1;
                   3746: }
                   3747: 
                   3748: ###################################################
                   3749: 
                   3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &keyword($word)
1.46      matthew  3753: 
                   3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3755: than the average number of times in the thesaurus database.  Calls 
                   3756: &initialize_keywords
                   3757: 
                   3758: =cut
                   3759: 
                   3760: ###################################################
1.20      www      3761: 
                   3762: sub keyword {
1.46      matthew  3763:     return if (!&initialize_keywords());
                   3764:     my $word=lc(shift());
                   3765:     $word=~s/\W//g;
                   3766:     return exists($Keywords{$word});
1.20      www      3767: }
1.46      matthew  3768: 
                   3769: ###############################################################
                   3770: 
                   3771: =pod 
1.20      www      3772: 
1.648     raeburn  3773: =item * &get_related_words()
1.46      matthew  3774: 
1.160     matthew  3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3776: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3777: will be returned.  The order of the words returned is determined by the
                   3778: database which holds them.
                   3779: 
                   3780: Uses global $thesaurus_db_file.
                   3781: 
1.1057    foxr     3782: 
1.46      matthew  3783: =cut
                   3784: 
                   3785: ###############################################################
                   3786: sub get_related_words {
                   3787:     my $keyword = shift;
                   3788:     my %thesaurus_db;
                   3789:     if (! -e $thesaurus_db_file) {
                   3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3791:                                  "failed because the file does not exist");
                   3792:         return ();
                   3793:     }
                   3794:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3796:         return ();
                   3797:     } 
                   3798:     my @Words=();
1.429     www      3799:     my $count=0;
1.46      matthew  3800:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3801: 	# The first element is the number of times
                   3802: 	# the word appears.  We do not need it now.
1.429     www      3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3805: 	my $threshold=$mostfrequentcount/10;
                   3806:         foreach my $possibleword (@RelatedWords) {
                   3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3808:             if ($wordcount>$threshold) {
                   3809: 		push(@Words,$word);
                   3810:                 $count++;
                   3811:                 if ($count>10) { last; }
                   3812: 	    }
1.20      www      3813:         }
                   3814:     }
1.46      matthew  3815:     untie %thesaurus_db;
                   3816:     return @Words;
1.14      harris41 3817: }
1.1090    foxr     3818: ###############################################################
                   3819: #
                   3820: #  Spell checking
                   3821: #
                   3822: 
                   3823: =pod
                   3824: 
1.1142    raeburn  3825: =back
                   3826: 
1.1090    foxr     3827: =head1 Spell checking
                   3828: 
                   3829: =over 4
                   3830: 
                   3831: =item * &check_spelling($wordlist $language)
                   3832: 
                   3833: Takes a string containing words and feeds it to an external
                   3834: spellcheck program via a pipeline. Returns a string containing
                   3835: them mis-spelled words.
                   3836: 
                   3837: Parameters:
                   3838: 
                   3839: =over 4
                   3840: 
                   3841: =item - $wordlist
                   3842: 
                   3843: String that will be fed into the spellcheck program.
                   3844: 
                   3845: =item - $language
                   3846: 
                   3847: Language string that specifies the language for which the spell
                   3848: check will be performed.
                   3849: 
                   3850: =back
                   3851: 
                   3852: =back
                   3853: 
                   3854: Note: This sub assumes that aspell is installed.
                   3855: 
                   3856: 
                   3857: =cut
                   3858: 
1.46      matthew  3859: 
1.1090    foxr     3860: sub check_spelling {
                   3861:     my ($wordlist, $language) = @_;
1.1091    foxr     3862:     my @misspellings;
                   3863:     
                   3864:     # Generate the speller and set the langauge.
                   3865:     # if explicitly selected:
1.1090    foxr     3866: 
1.1091    foxr     3867:     my $speller = Text::Aspell->new;
1.1090    foxr     3868:     if ($language) {
1.1091    foxr     3869: 	$speller->set_option('lang', $language);
1.1090    foxr     3870:     }
                   3871: 
1.1091    foxr     3872:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3873: 
1.1091    foxr     3874:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3875: 
1.1091    foxr     3876:     foreach my $word (@words) {
                   3877: 	if(! $speller->check($word)) {
                   3878: 	    push(@misspellings, $word);
1.1090    foxr     3879: 	}
                   3880:     }
1.1091    foxr     3881:     return join(' ', @misspellings);
                   3882:     
1.1090    foxr     3883: }
                   3884: 
1.61      www      3885: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3886: =pod
                   3887: 
1.112     bowersj2 3888: =head1 User Name Functions
                   3889: 
                   3890: =over 4
                   3891: 
1.648     raeburn  3892: =item * &plainname($uname,$udom,$first)
1.81      albertel 3893: 
1.112     bowersj2 3894: Takes a users logon name and returns it as a string in
1.226     albertel 3895: "first middle last generation" form 
                   3896: if $first is set to 'lastname' then it returns it as
                   3897: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3898: 
                   3899: =cut
1.61      www      3900: 
1.295     www      3901: 
1.81      albertel 3902: ###############################################################
1.61      www      3903: sub plainname {
1.226     albertel 3904:     my ($uname,$udom,$first)=@_;
1.537     albertel 3905:     return if (!defined($uname) || !defined($udom));
1.295     www      3906:     my %names=&getnames($uname,$udom);
1.226     albertel 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3908: 					  $names{'middlename'},
                   3909: 					  $names{'lastname'},
                   3910: 					  $names{'generation'},$first);
                   3911:     $name=~s/^\s+//;
1.62      www      3912:     $name=~s/\s+$//;
                   3913:     $name=~s/\s+/ /g;
1.353     albertel 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3915:     return $name;
1.61      www      3916: }
1.66      www      3917: 
                   3918: # -------------------------------------------------------------------- Nickname
1.81      albertel 3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &nickname($uname,$udom)
1.81      albertel 3922: 
                   3923: Gets a users name and returns it as a string as
                   3924: 
                   3925: "&quot;nickname&quot;"
1.66      www      3926: 
1.81      albertel 3927: if the user has a nickname or
                   3928: 
                   3929: "first middle last generation"
                   3930: 
                   3931: if the user does not
                   3932: 
                   3933: =cut
1.66      www      3934: 
                   3935: sub nickname {
                   3936:     my ($uname,$udom)=@_;
1.537     albertel 3937:     return if (!defined($uname) || !defined($udom));
1.295     www      3938:     my %names=&getnames($uname,$udom);
1.68      albertel 3939:     my $name=$names{'nickname'};
1.66      www      3940:     if ($name) {
                   3941:        $name='&quot;'.$name.'&quot;'; 
                   3942:     } else {
                   3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3944: 	     $names{'lastname'}.' '.$names{'generation'};
                   3945:        $name=~s/\s+$//;
                   3946:        $name=~s/\s+/ /g;
                   3947:     }
                   3948:     return $name;
                   3949: }
                   3950: 
1.295     www      3951: sub getnames {
                   3952:     my ($uname,$udom)=@_;
1.537     albertel 3953:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3954:     if ($udom eq 'public' && $uname eq 'public') {
                   3955: 	return ('lastname' => &mt('Public'));
                   3956:     }
1.295     www      3957:     my $id=$uname.':'.$udom;
                   3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3959:     if ($cached) {
                   3960: 	return %{$names};
                   3961:     } else {
                   3962: 	my %loadnames=&Apache::lonnet::get('environment',
                   3963:                     ['firstname','middlename','lastname','generation','nickname'],
                   3964: 					 $udom,$uname);
                   3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3966: 	return %loadnames;
                   3967:     }
                   3968: }
1.61      www      3969: 
1.542     raeburn  3970: # -------------------------------------------------------------------- getemails
1.648     raeburn  3971: 
1.542     raeburn  3972: =pod
                   3973: 
1.648     raeburn  3974: =item * &getemails($uname,$udom)
1.542     raeburn  3975: 
                   3976: Gets a user's email information and returns it as a hash with keys:
                   3977: notification, critnotification, permanentemail
                   3978: 
                   3979: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3981:  
1.648     raeburn  3982: 
1.542     raeburn  3983: =cut
                   3984: 
1.648     raeburn  3985: 
1.466     albertel 3986: sub getemails {
                   3987:     my ($uname,$udom)=@_;
                   3988:     if ($udom eq 'public' && $uname eq 'public') {
                   3989: 	return;
                   3990:     }
1.467     www      3991:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3992:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3993:     my $id=$uname.':'.$udom;
                   3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3995:     if ($cached) {
                   3996: 	return %{$names};
                   3997:     } else {
                   3998: 	my %loadnames=&Apache::lonnet::get('environment',
                   3999:                     			   ['notification','critnotification',
                   4000: 					    'permanentemail'],
                   4001: 					   $udom,$uname);
                   4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4003: 	return %loadnames;
                   4004:     }
                   4005: }
                   4006: 
1.551     albertel 4007: sub flush_email_cache {
                   4008:     my ($uname,$udom)=@_;
                   4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4010:     if (!$uname) { $uname=$env{'user.name'};   }
                   4011:     return if ($udom eq 'public' && $uname eq 'public');
                   4012:     my $id=$uname.':'.$udom;
                   4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4014: }
                   4015: 
1.728     raeburn  4016: # -------------------------------------------------------------------- getlangs
                   4017: 
                   4018: =pod
                   4019: 
                   4020: =item * &getlangs($uname,$udom)
                   4021: 
                   4022: Gets a user's language preference and returns it as a hash with key:
                   4023: language.
                   4024: 
                   4025: =cut
                   4026: 
                   4027: 
                   4028: sub getlangs {
                   4029:     my ($uname,$udom) = @_;
                   4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4031:     if (!$uname) { $uname=$env{'user.name'};   }
                   4032:     my $id=$uname.':'.$udom;
                   4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4034:     if ($cached) {
                   4035:         return %{$langs};
                   4036:     } else {
                   4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4038:                                            $udom,$uname);
                   4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4040:         return %loadlangs;
                   4041:     }
                   4042: }
                   4043: 
                   4044: sub flush_langs_cache {
                   4045:     my ($uname,$udom)=@_;
                   4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4047:     if (!$uname) { $uname=$env{'user.name'};   }
                   4048:     return if ($udom eq 'public' && $uname eq 'public');
                   4049:     my $id=$uname.':'.$udom;
                   4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4051: }
                   4052: 
1.61      www      4053: # ------------------------------------------------------------------ Screenname
1.81      albertel 4054: 
                   4055: =pod
                   4056: 
1.648     raeburn  4057: =item * &screenname($uname,$udom)
1.81      albertel 4058: 
                   4059: Gets a users screenname and returns it as a string
                   4060: 
                   4061: =cut
1.61      www      4062: 
                   4063: sub screenname {
                   4064:     my ($uname,$udom)=@_;
1.258     albertel 4065:     if ($uname eq $env{'user.name'} &&
                   4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4068:     return $names{'screenname'};
1.62      www      4069: }
                   4070: 
1.212     albertel 4071: 
1.802     bisitz   4072: # ------------------------------------------------------------- Confirm Wrapper
                   4073: =pod
                   4074: 
1.1142    raeburn  4075: =item * &confirmwrapper($message)
1.802     bisitz   4076: 
                   4077: Wrap messages about completion of operation in box
                   4078: 
                   4079: =cut
                   4080: 
                   4081: sub confirmwrapper {
                   4082:     my ($message)=@_;
                   4083:     if ($message) {
                   4084:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4085:                .$message."\n"
                   4086:                .'</div>'."\n";
                   4087:     } else {
                   4088:         return $message;
                   4089:     }
                   4090: }
                   4091: 
1.62      www      4092: # ------------------------------------------------------------- Message Wrapper
                   4093: 
                   4094: sub messagewrapper {
1.369     www      4095:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4096:     return 
1.441     albertel 4097:         '<a href="/adm/email?compose=individual&amp;'.
                   4098:         'recname='.$username.'&amp;recdom='.$domain.
                   4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4101: }
1.802     bisitz   4102: 
1.74      www      4103: # --------------------------------------------------------------- Notes Wrapper
                   4104: 
                   4105: sub noteswrapper {
                   4106:     my ($link,$un,$do)=@_;
                   4107:     return 
1.896     amueller 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4109: }
1.802     bisitz   4110: 
1.62      www      4111: # ------------------------------------------------------------- Aboutme Wrapper
                   4112: 
                   4113: sub aboutmewrapper {
1.1070    raeburn  4114:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4115:     if (!defined($username)  && !defined($domain)) {
                   4116:         return;
                   4117:     }
1.1096    raeburn  4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4120: }
                   4121: 
                   4122: # ------------------------------------------------------------ Syllabus Wrapper
                   4123: 
                   4124: sub syllabuswrapper {
1.707     bisitz   4125:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4127: }
1.14      harris41 4128: 
1.802     bisitz   4129: # -----------------------------------------------------------------------------
                   4130: 
1.208     matthew  4131: sub track_student_link {
1.887     raeburn  4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4133:     my $link ="/adm/trackstudent?";
1.208     matthew  4134:     my $title = 'View recent activity';
                   4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4137:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4138:         $title .= ' of this student';
1.268     albertel 4139:     } 
1.208     matthew  4140:     if (defined($target) && $target !~ /^\s*$/) {
                   4141:         $target = qq{target="$target"};
                   4142:     } else {
                   4143:         $target = '';
                   4144:     }
1.268     albertel 4145:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4147:     $title = &mt($title);
                   4148:     $linktext = &mt($linktext);
1.448     albertel 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4150: 	&help_open_topic('View_recent_activity');
1.208     matthew  4151: }
                   4152: 
1.781     raeburn  4153: sub slot_reservations_link {
                   4154:     my ($linktext,$sname,$sdom,$target) = @_;
                   4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4156:     my $title = 'View slot reservation history';
                   4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4160:         $title .= ' of this student';
                   4161:     }
                   4162:     if (defined($target) && $target !~ /^\s*$/) {
                   4163:         $target = qq{target="$target"};
                   4164:     } else {
                   4165:         $target = '';
                   4166:     }
                   4167:     $title = &mt($title);
                   4168:     $linktext = &mt($linktext);
                   4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4171: 
                   4172: }
                   4173: 
1.508     www      4174: # ===================================================== Display a student photo
                   4175: 
                   4176: 
1.509     albertel 4177: sub student_image_tag {
1.508     www      4178:     my ($domain,$user)=@_;
                   4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4181: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4182:     } else {
                   4183: 	return '';
                   4184:     }
                   4185: }
                   4186: 
1.112     bowersj2 4187: =pod
                   4188: 
                   4189: =back
                   4190: 
                   4191: =head1 Access .tab File Data
                   4192: 
                   4193: =over 4
                   4194: 
1.648     raeburn  4195: =item * &languageids() 
1.112     bowersj2 4196: 
                   4197: returns list of all language ids
                   4198: 
                   4199: =cut
                   4200: 
1.14      harris41 4201: sub languageids {
1.16      harris41 4202:     return sort(keys(%language));
1.14      harris41 4203: }
                   4204: 
1.112     bowersj2 4205: =pod
                   4206: 
1.648     raeburn  4207: =item * &languagedescription() 
1.112     bowersj2 4208: 
                   4209: returns description of a specified language id
                   4210: 
                   4211: =cut
                   4212: 
1.14      harris41 4213: sub languagedescription {
1.125     www      4214:     my $code=shift;
                   4215:     return  ($supported_language{$code}?'* ':'').
                   4216:             $language{$code}.
1.126     www      4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4218: }
                   4219: 
1.1048    foxr     4220: =pod
                   4221: 
                   4222: =item * &plainlanguagedescription
                   4223: 
                   4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4226: 
                   4227: =cut
                   4228: 
1.145     www      4229: sub plainlanguagedescription {
                   4230:     my $code=shift;
                   4231:     return $language{$code};
                   4232: }
                   4233: 
1.1048    foxr     4234: =pod
                   4235: 
                   4236: =item * &supportedlanguagecode
                   4237: 
                   4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4239: code.
                   4240: 
                   4241: =cut
                   4242: 
1.145     www      4243: sub supportedlanguagecode {
                   4244:     my $code=shift;
                   4245:     return $supported_language{$code};
1.97      www      4246: }
                   4247: 
1.112     bowersj2 4248: =pod
                   4249: 
1.1048    foxr     4250: =item * &latexlanguage()
                   4251: 
                   4252: Given a language key code returns the correspondnig language to use
                   4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4254: is no supported hyphenation for the language code.
                   4255: 
                   4256: =cut
                   4257: 
                   4258: sub latexlanguage {
                   4259:     my $code = shift;
                   4260:     return $latex_language{$code};
                   4261: }
                   4262: 
                   4263: =pod
                   4264: 
                   4265: =item * &latexhyphenation()
                   4266: 
                   4267: Same as above but what's supplied is the language as it might be stored
                   4268: in the metadata.
                   4269: 
                   4270: =cut
                   4271: 
                   4272: sub latexhyphenation {
                   4273:     my $key = shift;
                   4274:     return $latex_language_bykey{$key};
                   4275: }
                   4276: 
                   4277: =pod
                   4278: 
1.648     raeburn  4279: =item * &copyrightids() 
1.112     bowersj2 4280: 
                   4281: returns list of all copyrights
                   4282: 
                   4283: =cut
                   4284: 
                   4285: sub copyrightids {
                   4286:     return sort(keys(%cprtag));
                   4287: }
                   4288: 
                   4289: =pod
                   4290: 
1.648     raeburn  4291: =item * &copyrightdescription() 
1.112     bowersj2 4292: 
                   4293: returns description of a specified copyright id
                   4294: 
                   4295: =cut
                   4296: 
                   4297: sub copyrightdescription {
1.166     www      4298:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4299: }
1.197     matthew  4300: 
                   4301: =pod
                   4302: 
1.648     raeburn  4303: =item * &source_copyrightids() 
1.192     taceyjo1 4304: 
                   4305: returns list of all source copyrights
                   4306: 
                   4307: =cut
                   4308: 
                   4309: sub source_copyrightids {
                   4310:     return sort(keys(%scprtag));
                   4311: }
                   4312: 
                   4313: =pod
                   4314: 
1.648     raeburn  4315: =item * &source_copyrightdescription() 
1.192     taceyjo1 4316: 
                   4317: returns description of a specified source copyright id
                   4318: 
                   4319: =cut
                   4320: 
                   4321: sub source_copyrightdescription {
                   4322:     return &mt($scprtag{shift(@_)});
                   4323: }
1.112     bowersj2 4324: 
                   4325: =pod
                   4326: 
1.648     raeburn  4327: =item * &filecategories() 
1.112     bowersj2 4328: 
                   4329: returns list of all file categories
                   4330: 
                   4331: =cut
                   4332: 
                   4333: sub filecategories {
                   4334:     return sort(keys(%category_extensions));
                   4335: }
                   4336: 
                   4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &filecategorytypes() 
1.112     bowersj2 4340: 
                   4341: returns list of file types belonging to a given file
                   4342: category
                   4343: 
                   4344: =cut
                   4345: 
                   4346: sub filecategorytypes {
1.356     albertel 4347:     my ($cat) = @_;
1.1248    raeburn  4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4349:         return @{$category_extensions{lc($cat)}};
                   4350:     } else {
                   4351:         return ();
                   4352:     }
1.112     bowersj2 4353: }
                   4354: 
                   4355: =pod
                   4356: 
1.648     raeburn  4357: =item * &fileembstyle() 
1.112     bowersj2 4358: 
                   4359: returns embedding style for a specified file type
                   4360: 
                   4361: =cut
                   4362: 
                   4363: sub fileembstyle {
                   4364:     return $fe{lc(shift(@_))};
1.169     www      4365: }
                   4366: 
1.351     www      4367: sub filemimetype {
                   4368:     return $fm{lc(shift(@_))};
                   4369: }
                   4370: 
1.169     www      4371: 
                   4372: sub filecategoryselect {
                   4373:     my ($name,$value)=@_;
1.189     matthew  4374:     return &select_form($value,$name,
1.970     raeburn  4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4376: }
                   4377: 
                   4378: =pod
                   4379: 
1.648     raeburn  4380: =item * &filedescription() 
1.112     bowersj2 4381: 
                   4382: returns description for a specified file type
                   4383: 
                   4384: =cut
                   4385: 
                   4386: sub filedescription {
1.188     matthew  4387:     my $file_description = $fd{lc(shift())};
                   4388:     $file_description =~ s:([\[\]]):~$1:g;
                   4389:     return &mt($file_description);
1.112     bowersj2 4390: }
                   4391: 
                   4392: =pod
                   4393: 
1.648     raeburn  4394: =item * &filedescriptionex() 
1.112     bowersj2 4395: 
                   4396: returns description for a specified file type with
                   4397: extra formatting
                   4398: 
                   4399: =cut
                   4400: 
                   4401: sub filedescriptionex {
                   4402:     my $ex=shift;
1.188     matthew  4403:     my $file_description = $fd{lc($ex)};
                   4404:     $file_description =~ s:([\[\]]):~$1:g;
                   4405:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4406: }
                   4407: 
                   4408: # End of .tab access
                   4409: =pod
                   4410: 
                   4411: =back
                   4412: 
                   4413: =cut
                   4414: 
                   4415: # ------------------------------------------------------------------ File Types
                   4416: sub fileextensions {
                   4417:     return sort(keys(%fe));
                   4418: }
                   4419: 
1.97      www      4420: # ----------------------------------------------------------- Display Languages
                   4421: # returns a hash with all desired display languages
                   4422: #
                   4423: 
                   4424: sub display_languages {
                   4425:     my %languages=();
1.695     raeburn  4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4427: 	$languages{$lang}=1;
1.97      www      4428:     }
                   4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4430:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4432: 	    $languages{$lang}=1;
1.97      www      4433:         }
                   4434:     }
                   4435:     return %languages;
1.14      harris41 4436: }
                   4437: 
1.582     albertel 4438: sub languages {
                   4439:     my ($possible_langs) = @_;
1.695     raeburn  4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4441:     if (!ref($possible_langs)) {
                   4442: 	if( wantarray ) {
                   4443: 	    return @preferred_langs;
                   4444: 	} else {
                   4445: 	    return $preferred_langs[0];
                   4446: 	}
                   4447:     }
                   4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4449:     my @preferred_possibilities;
                   4450:     foreach my $preferred_lang (@preferred_langs) {
                   4451: 	if (exists($possibilities{$preferred_lang})) {
                   4452: 	    push(@preferred_possibilities, $preferred_lang);
                   4453: 	}
                   4454:     }
                   4455:     if( wantarray ) {
                   4456: 	return @preferred_possibilities;
                   4457:     }
                   4458:     return $preferred_possibilities[0];
                   4459: }
                   4460: 
1.742     raeburn  4461: sub user_lang {
                   4462:     my ($touname,$toudom,$fromcid) = @_;
                   4463:     my @userlangs;
                   4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4466:                     $env{'course.'.$fromcid.'.languages'}));
                   4467:     } else {
                   4468:         my %langhash = &getlangs($touname,$toudom);
                   4469:         if ($langhash{'languages'} ne '') {
                   4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4471:         } else {
                   4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4473:             if ($domdefs{'lang_def'} ne '') {
                   4474:                 @userlangs = ($domdefs{'lang_def'});
                   4475:             }
                   4476:         }
                   4477:     }
                   4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4479:     my $user_lh = Apache::localize->get_handle(@languages);
                   4480:     return $user_lh;
                   4481: }
                   4482: 
                   4483: 
1.112     bowersj2 4484: ###############################################################
                   4485: ##               Student Answer Attempts                     ##
                   4486: ###############################################################
                   4487: 
                   4488: =pod
                   4489: 
                   4490: =head1 Alternate Problem Views
                   4491: 
                   4492: =over 4
                   4493: 
1.648     raeburn  4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4496: 
                   4497: Return string with previous attempt on problem. Arguments:
                   4498: 
                   4499: =over 4
                   4500: 
                   4501: =item * $symb: Problem, including path
                   4502: 
                   4503: =item * $username: username of the desired student
                   4504: 
                   4505: =item * $domain: domain of the desired student
1.14      harris41 4506: 
1.112     bowersj2 4507: =item * $course: Course ID
1.14      harris41 4508: 
1.112     bowersj2 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4510:     something
1.14      harris41 4511: 
1.112     bowersj2 4512: =item * $regexp: if string matches this regexp, the string will be
                   4513:     sent to $gradesub
1.14      harris41 4514: 
1.112     bowersj2 4515: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4516: 
1.1199    raeburn  4517: =item * $usec: section of the desired student
                   4518: 
                   4519: =item * $identifier: counter for student (multiple students one problem) or 
                   4520:     problem (one student; whole sequence).
                   4521: 
1.112     bowersj2 4522: =back
1.14      harris41 4523: 
1.112     bowersj2 4524: The output string is a table containing all desired attempts, if any.
1.16      harris41 4525: 
1.112     bowersj2 4526: =cut
1.1       albertel 4527: 
                   4528: sub get_previous_attempt {
1.1199    raeburn  4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4530:   my $prevattempts='';
1.43      ng       4531:   no strict 'refs';
1.1       albertel 4532:   if ($symb) {
1.3       albertel 4533:     my (%returnhash)=
                   4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4535:     if ($returnhash{'version'}) {
                   4536:       my %lasthash=();
                   4537:       my $version;
                   4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4540:             if ($key =~ /\.rawrndseed$/) {
                   4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4543:             } else {
                   4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4545:             }
1.19      harris41 4546:         }
1.1       albertel 4547:       }
1.596     albertel 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4549:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4552:       foreach my $key (sort(keys(%lasthash))) {
                   4553: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4554: 	if ($#parts > 0) {
1.31      albertel 4555: 	  my $data=$parts[-1];
1.989     raeburn  4556:           next if ($data eq 'foilorder');
1.31      albertel 4557: 	  pop(@parts);
1.1010    www      4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4559:           if ($data eq 'type') {
                   4560:               unless ($showsurv) {
                   4561:                   my $id = join(',',@parts);
                   4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4564:                       $lasthidden{$ign.'.'.$id} = 1;
                   4565:                   }
1.945     raeburn  4566:               }
1.1199    raeburn  4567:               if ($identifier ne '') {
                   4568:                   my $id = join(',',@parts);
                   4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4571:                       $hidestatus{$ign.'.'.$id} = 1;
                   4572:                   }
                   4573:               }
                   4574:           } elsif ($data eq 'regrader') {
                   4575:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4576:                   my $id = join(',',@parts);
                   4577:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4578:               }
1.1010    www      4579:           } 
1.31      albertel 4580: 	} else {
1.41      ng       4581: 	  if ($#parts == 0) {
                   4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4583: 	  } else {
                   4584: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4585: 	  }
1.31      albertel 4586: 	}
1.16      harris41 4587:       }
1.596     albertel 4588:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4589:       if ($getattempt eq '') {
1.1199    raeburn  4590:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4593:                 foreach my $id (keys(%regraded)) {
                   4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4597:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4598:                     }
                   4599:                 }
                   4600:             }
1.1200    raeburn  4601:         }
                   4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4603:             my (@hidden,@unsolved);
1.945     raeburn  4604:             if (%typeparts) {
                   4605:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4608:                         push(@hidden,$id);
1.1199    raeburn  4609:                     } elsif ($identifier ne '') {
                   4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4612:                                 ($hidestatus{$id})) {
1.1200    raeburn  4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4615:                                 push(@{$solved{$id}},$version);
                   4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4618:                                 my $skip;
                   4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4620:                                     foreach my $reset (@{$resets{$id}}) {
                   4621:                                         if ($reset > $solved{$id}[-1]) {
                   4622:                                             $skip=1;
                   4623:                                             last;
                   4624:                                         }
                   4625:                                     }
                   4626:                                 }
                   4627:                                 unless ($skip) {
                   4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4629:                                     push(@unsolved,$partslist);
                   4630:                                 }
                   4631:                             }
                   4632:                         }
1.945     raeburn  4633:                     }
                   4634:                 }
                   4635:             }
                   4636:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4637:                            '<td>'.&mt('Transaction [_1]',$version);
                   4638:             if (@unsolved) {
                   4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4641:                                  &mt('Hide').'</label></span>';
                   4642:             }
                   4643:             $prevattempts .= '</td>';
1.945     raeburn  4644:             if (@hidden) {
                   4645:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4646:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4647:                     my $hide;
                   4648:                     foreach my $id (@hidden) {
                   4649:                         if ($key =~ /^\Q$id\E/) {
                   4650:                             $hide = 1;
                   4651:                             last;
                   4652:                         }
                   4653:                     }
                   4654:                     if ($hide) {
                   4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4657:                             my $value = &format_previous_attempt_value($key,
                   4658:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4660:                         } else {
                   4661:                             $prevattempts.='<td>&nbsp;</td>';
                   4662:                         }
                   4663:                     } else {
                   4664:                         if ($key =~ /\./) {
1.1212    raeburn  4665:                             my $value = $returnhash{$version.':'.$key};
                   4666:                             if ($key =~ /\.rndseed$/) {
                   4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4670:                                 }
                   4671:                             }
                   4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4673:                                            '&nbsp;</td>';
1.945     raeburn  4674:                         } else {
                   4675:                             $prevattempts.='<td>&nbsp;</td>';
                   4676:                         }
                   4677:                     }
                   4678:                 }
                   4679:             } else {
                   4680: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4681:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4682:                     my $value = $returnhash{$version.':'.$key};
                   4683:                     if ($key =~ /\.rndseed$/) {
                   4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4687:                         }
                   4688:                     }
                   4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4690:                                    '&nbsp;</td>';
1.945     raeburn  4691: 	        }
                   4692:             }
                   4693: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4694: 	 }
1.1       albertel 4695:       }
1.945     raeburn  4696:       my @currhidden = keys(%lasthidden);
1.596     albertel 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4698:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4699:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4700:           if (%typeparts) {
                   4701:               my $hidden;
                   4702:               foreach my $id (@currhidden) {
                   4703:                   if ($key =~ /^\Q$id\E/) {
                   4704:                       $hidden = 1;
                   4705:                       last;
                   4706:                   }
                   4707:               }
                   4708:               if ($hidden) {
                   4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4713:                           $value = &$gradesub($value);
                   4714:                       }
1.1173    kruse    4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4716:                   } else {
                   4717:                       $prevattempts.='<td>&nbsp;</td>';
                   4718:                   }
                   4719:               } else {
                   4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4722:                       $value = &$gradesub($value);
                   4723:                   }
1.1173    kruse    4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4725:               }
                   4726:           } else {
                   4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4729:                   $value = &$gradesub($value);
                   4730:               }
1.1173    kruse    4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4732:           }
1.16      harris41 4733:       }
1.596     albertel 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4735:     } else {
1.1305    raeburn  4736:       my $msg;
                   4737:       if ($symb =~ /ext\.tool$/) {
                   4738:           $msg = &mt('No grade passed back.');
                   4739:       } else {
                   4740:           $msg = &mt('Nothing submitted - no attempts.');
                   4741:       }
1.596     albertel 4742:       $prevattempts=
                   4743: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4744: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4745: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4746:     }
                   4747:   } else {
1.596     albertel 4748:     $prevattempts=
                   4749: 	  &start_data_table().&start_data_table_row().
                   4750: 	  '<td>'.&mt('No data.').'</td>'.
                   4751: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4752:   }
1.10      albertel 4753: }
                   4754: 
1.581     albertel 4755: sub format_previous_attempt_value {
                   4756:     my ($key,$value) = @_;
1.1011    www      4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4758:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4759:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4761:     } elsif ($key =~ /answerstring$/) {
                   4762:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4763:         my @answer = %answers;
                   4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4765:         my @anskeys = sort(keys(%answers));
                   4766:         if (@anskeys == 1) {
                   4767:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4768:             if ($answer =~ m{\0}) {
                   4769:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4770:             }
                   4771:             my $tag_internal_answer_name = 'INTERNAL';
                   4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4773:                 $value = $answer; 
                   4774:             } else {
                   4775:                 $value = $anskeys[0].'='.$answer;
                   4776:             }
                   4777:         } else {
                   4778:             foreach my $ans (@anskeys) {
                   4779:                 my $answer = $answers{$ans};
1.1001    raeburn  4780:                 if ($answer =~ m{\0}) {
                   4781:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4782:                 }
                   4783:                 $value .=  $ans.'='.$answer.'<br />';;
                   4784:             } 
                   4785:         }
1.581     albertel 4786:     } else {
1.1173    kruse    4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4788:     }
                   4789:     return $value;
                   4790: }
                   4791: 
                   4792: 
1.107     albertel 4793: sub relative_to_absolute {
                   4794:     my ($url,$output)=@_;
                   4795:     my $parser=HTML::TokeParser->new(\$output);
                   4796:     my $token;
                   4797:     my $thisdir=$url;
                   4798:     my @rlinks=();
                   4799:     while ($token=$parser->get_token) {
                   4800: 	if ($token->[0] eq 'S') {
                   4801: 	    if ($token->[1] eq 'a') {
                   4802: 		if ($token->[2]->{'href'}) {
                   4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4804: 		}
                   4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4807: 	    } elsif ($token->[1] eq 'base') {
                   4808: 		$thisdir=$token->[2]->{'href'};
                   4809: 	    }
                   4810: 	}
                   4811:     }
                   4812:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4813:     foreach my $link (@rlinks) {
1.726     raeburn  4814: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4815: 		($link=~/^\//) ||
                   4816: 		($link=~/^javascript:/i) ||
                   4817: 		($link=~/^mailto:/i) ||
                   4818: 		($link=~/^\#/)) {
                   4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4821: 	}
                   4822:     }
                   4823: # -------------------------------------------------- Deal with Applet codebases
                   4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4825:     return $output;
                   4826: }
                   4827: 
1.112     bowersj2 4828: =pod
                   4829: 
1.648     raeburn  4830: =item * &get_student_view()
1.112     bowersj2 4831: 
                   4832: show a snapshot of what student was looking at
                   4833: 
                   4834: =cut
                   4835: 
1.10      albertel 4836: sub get_student_view {
1.186     albertel 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4839:   my (%form);
1.10      albertel 4840:   my @elements=('symb','courseid','domain','username');
                   4841:   foreach my $element (@elements) {
1.186     albertel 4842:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4843:   }
1.186     albertel 4844:   if (defined($moreenv)) {
                   4845:       %form=(%form,%{$moreenv});
                   4846:   }
1.236     albertel 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4850:       $feedurl =~ s{^/adm/wrapper}{};
                   4851:   }
1.650     www      4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4853:   $userview=~s/\<body[^\>]*\>//gi;
                   4854:   $userview=~s/\<\/body\>//gi;
                   4855:   $userview=~s/\<html\>//gi;
                   4856:   $userview=~s/\<\/html\>//gi;
                   4857:   $userview=~s/\<head\>//gi;
                   4858:   $userview=~s/\<\/head\>//gi;
                   4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4860:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4861:   if (wantarray) {
                   4862:      return ($userview,$response);
                   4863:   } else {
                   4864:      return $userview;
                   4865:   }
                   4866: }
                   4867: 
                   4868: sub get_student_view_with_retries {
                   4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4870: 
                   4871:     my $ok = 0;                 # True if we got a good response.
                   4872:     my $content;
                   4873:     my $response;
                   4874: 
                   4875:     # Try to get the student_view done. within the retries count:
                   4876:     
                   4877:     do {
                   4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4879:          $ok      = $response->is_success;
                   4880:          if (!$ok) {
                   4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4882:          }
                   4883:          $retries--;
                   4884:     } while (!$ok && ($retries > 0));
                   4885:     
                   4886:     if (!$ok) {
                   4887:        $content = '';          # On error return an empty content.
                   4888:     }
1.651     www      4889:     if (wantarray) {
                   4890:        return ($content, $response);
                   4891:     } else {
                   4892:        return $content;
                   4893:     }
1.11      albertel 4894: }
                   4895: 
1.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.1359    raeburn  6269:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref);
1.359     albertel 6270: 
1.1318    raeburn  6271:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6272:                 if ($dc_info) {
                   6273:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6274:                 }
                   6275:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6276:                                <em>$realm</em> $dc_info</div>|;
                   6277:                 return $bodytag;
                   6278:             }
1.894     droeschl 6279: 
1.1318    raeburn  6280:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6281:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6282:             }
1.916     droeschl 6283: 
1.1318    raeburn  6284:             $bodytag .= $right;
1.852     droeschl 6285: 
1.1318    raeburn  6286:             if ($dc_info) {
                   6287:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6288:             }
                   6289:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6290:         }
1.916     droeschl 6291: 
1.1169    raeburn  6292:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6293:         if ($args->{'no_secondary_menu'}) {
                   6294:             return $bodytag;
                   6295:         }
1.1169    raeburn  6296:         #don't show menus for public users
1.954     raeburn  6297:         if (!$public){
1.1318    raeburn  6298:             unless ($args->{'no_inline_menu'}) {
                   6299:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6300:                                                             $args->{'no_primary_menu'},
                   6301:                                                             $menucoll,$menuref);
1.1318    raeburn  6302:             }
1.903     droeschl 6303:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6304:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6305:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6306:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6307:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6308:             } elsif ($forcereg) {
                   6309:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6310:                                                             $args->{'group'},
1.1274    raeburn  6311:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6312:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6313:             } else {
                   6314:                 $bodytag .= 
                   6315:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6316:                                                         $forcereg,$args->{'group'},
                   6317:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6318:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6319:             }
1.903     droeschl 6320:         }else{
                   6321:             # this is to seperate menu from content when there's no secondary
                   6322:             # menu. Especially needed for public accessible ressources.
                   6323:             $bodytag .= '<hr style="clear:both" />';
                   6324:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6325:         }
1.903     droeschl 6326: 
1.235     raeburn  6327:         return $bodytag;
1.182     matthew  6328: }
                   6329: 
1.917     raeburn  6330: sub dc_courseid_toggle {
                   6331:     my ($dc_info) = @_;
1.980     raeburn  6332:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6333:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6334:            &mt('(More ...)').'</a></span>'.
                   6335:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6336: }
                   6337: 
1.330     albertel 6338: sub make_attr_string {
                   6339:     my ($register,$attr_ref) = @_;
                   6340: 
                   6341:     if ($attr_ref && !ref($attr_ref)) {
                   6342: 	die("addentries Must be a hash ref ".
                   6343: 	    join(':',caller(1))." ".
                   6344: 	    join(':',caller(0))." ");
                   6345:     }
                   6346: 
                   6347:     if ($register) {
1.339     albertel 6348: 	my ($on_load,$on_unload);
                   6349: 	foreach my $key (keys(%{$attr_ref})) {
                   6350: 	    if      (lc($key) eq 'onload') {
                   6351: 		$on_load.=$attr_ref->{$key}.';';
                   6352: 		delete($attr_ref->{$key});
                   6353: 
                   6354: 	    } elsif (lc($key) eq 'onunload') {
                   6355: 		$on_unload.=$attr_ref->{$key}.';';
                   6356: 		delete($attr_ref->{$key});
                   6357: 	    }
                   6358: 	}
1.953     droeschl 6359: 	$attr_ref->{'onload'}  = $on_load;
                   6360: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6361:     }
1.339     albertel 6362: 
1.330     albertel 6363:     my $attr_string;
1.1159    raeburn  6364:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6365: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6366:     }
                   6367:     return $attr_string;
                   6368: }
                   6369: 
                   6370: 
1.182     matthew  6371: ###############################################
1.251     albertel 6372: ###############################################
                   6373: 
                   6374: =pod
                   6375: 
                   6376: =item * &endbodytag()
                   6377: 
                   6378: Returns a uniform footer for LON-CAPA web pages.
                   6379: 
1.635     raeburn  6380: Inputs: 1 - optional reference to an args hash
                   6381: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6382: a 'Continue' link is not displayed if the page contains an
                   6383: internal redirect in the <head></head> section,
                   6384: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6385: 
                   6386: =cut
                   6387: 
                   6388: sub endbodytag {
1.635     raeburn  6389:     my ($args) = @_;
1.1080    raeburn  6390:     my $endbodytag;
                   6391:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6392:         $endbodytag='</body>';
                   6393:     }
1.315     albertel 6394:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6395:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6396: 	    $endbodytag=
                   6397: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6398: 	        &mt('Continue').'</a>'.
                   6399: 	        $endbodytag;
                   6400:         }
1.315     albertel 6401:     }
1.251     albertel 6402:     return $endbodytag;
                   6403: }
                   6404: 
1.352     albertel 6405: =pod
                   6406: 
                   6407: =item * &standard_css()
                   6408: 
                   6409: Returns a style sheet
                   6410: 
                   6411: Inputs: (all optional)
                   6412:             domain         -> force to color decorate a page for a specific
                   6413:                                domain
                   6414:             function       -> force usage of a specific rolish color scheme
                   6415:             bgcolor        -> override the default page bgcolor
                   6416: 
                   6417: =cut
                   6418: 
1.343     albertel 6419: sub standard_css {
1.345     albertel 6420:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6421:     $function  = &get_users_function() if (!$function);
                   6422:     my $img    = &designparm($function.'.img',   $domain);
                   6423:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6424:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6425:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6426: #second colour for later usage
1.345     albertel 6427:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6428:     my $pgbg_or_bgcolor =
                   6429: 	         $bgcolor ||
1.352     albertel 6430: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6431:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6432:     my $alink  = &designparm($function.'.alink', $domain);
                   6433:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6434:     my $link   = &designparm($function.'.link',  $domain);
                   6435: 
1.602     albertel 6436:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6437:     my $mono                 = 'monospace';
1.850     bisitz   6438:     my $data_table_head      = $sidebg;
                   6439:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6440:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6441:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6442:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6443:     my $mail_new             = '#FFBB77';
                   6444:     my $mail_new_hover       = '#DD9955';
                   6445:     my $mail_read            = '#BBBB77';
                   6446:     my $mail_read_hover      = '#999944';
                   6447:     my $mail_replied         = '#AAAA88';
                   6448:     my $mail_replied_hover   = '#888855';
                   6449:     my $mail_other           = '#99BBBB';
                   6450:     my $mail_other_hover     = '#669999';
1.391     albertel 6451:     my $table_header         = '#DDDDDD';
1.489     raeburn  6452:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6453:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6454:     my $button_hover         = '#BF2317';
1.392     albertel 6455: 
1.608     albertel 6456:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6457:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6458:                                              : '0 3px 0 4px';
1.448     albertel 6459: 
1.523     albertel 6460: 
1.343     albertel 6461:     return <<END;
1.947     droeschl 6462: 
                   6463: /* needed for iframe to allow 100% height in FF */
                   6464: body, html { 
                   6465:     margin: 0;
                   6466:     padding: 0 0.5%;
                   6467:     height: 99%; /* to avoid scrollbars */
                   6468: }
                   6469: 
1.795     www      6470: body {
1.911     bisitz   6471:   font-family: $sans;
                   6472:   line-height:130%;
                   6473:   font-size:0.83em;
                   6474:   color:$font;
1.795     www      6475: }
                   6476: 
1.959     onken    6477: a:focus,
                   6478: a:focus img {
1.795     www      6479:   color: red;
                   6480: }
1.698     harmsja  6481: 
1.911     bisitz   6482: form, .inline {
                   6483:   display: inline;
1.795     www      6484: }
1.721     harmsja  6485: 
1.795     www      6486: .LC_right {
1.911     bisitz   6487:   text-align:right;
1.795     www      6488: }
                   6489: 
                   6490: .LC_middle {
1.911     bisitz   6491:   vertical-align:middle;
1.795     www      6492: }
1.721     harmsja  6493: 
1.1130    raeburn  6494: .LC_floatleft {
                   6495:   float: left;
                   6496: }
                   6497: 
                   6498: .LC_floatright {
                   6499:   float: right;
                   6500: }
                   6501: 
1.911     bisitz   6502: .LC_400Box {
                   6503:   width:400px;
                   6504: }
1.721     harmsja  6505: 
1.947     droeschl 6506: .LC_iframecontainer {
                   6507:     width: 98%;
                   6508:     margin: 0;
                   6509:     position: fixed;
                   6510:     top: 8.5em;
                   6511:     bottom: 0;
                   6512: }
                   6513: 
                   6514: .LC_iframecontainer iframe{
                   6515:     border: none;
                   6516:     width: 100%;
                   6517:     height: 100%;
                   6518: }
                   6519: 
1.778     bisitz   6520: .LC_filename {
                   6521:   font-family: $mono;
                   6522:   white-space:pre;
1.921     bisitz   6523:   font-size: 120%;
1.778     bisitz   6524: }
                   6525: 
                   6526: .LC_fileicon {
                   6527:   border: none;
                   6528:   height: 1.3em;
                   6529:   vertical-align: text-bottom;
                   6530:   margin-right: 0.3em;
                   6531:   text-decoration:none;
                   6532: }
                   6533: 
1.1008    www      6534: .LC_setting {
                   6535:   text-decoration:underline;
                   6536: }
                   6537: 
1.350     albertel 6538: .LC_error {
                   6539:   color: red;
                   6540: }
1.795     www      6541: 
1.1097    bisitz   6542: .LC_warning {
                   6543:   color: darkorange;
                   6544: }
                   6545: 
1.457     albertel 6546: .LC_diff_removed {
1.733     bisitz   6547:   color: red;
1.394     albertel 6548: }
1.532     albertel 6549: 
                   6550: .LC_info,
1.457     albertel 6551: .LC_success,
                   6552: .LC_diff_added {
1.350     albertel 6553:   color: green;
                   6554: }
1.795     www      6555: 
1.802     bisitz   6556: div.LC_confirm_box {
                   6557:   background-color: #FAFAFA;
                   6558:   border: 1px solid $lg_border_color;
                   6559:   margin-right: 0;
                   6560:   padding: 5px;
                   6561: }
                   6562: 
                   6563: div.LC_confirm_box .LC_error img,
                   6564: div.LC_confirm_box .LC_success img {
                   6565:   vertical-align: middle;
                   6566: }
                   6567: 
1.1242    raeburn  6568: .LC_maxwidth {
                   6569:   max-width: 100%;
                   6570:   height: auto;
                   6571: }
                   6572: 
1.1243    raeburn  6573: .LC_textsize_mobile {
                   6574:   \@media only screen and (max-device-width: 480px) {
                   6575:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6576:   }
                   6577: }
                   6578: 
1.440     albertel 6579: .LC_icon {
1.771     droeschl 6580:   border: none;
1.790     droeschl 6581:   vertical-align: middle;
1.771     droeschl 6582: }
                   6583: 
1.543     albertel 6584: .LC_docs_spacer {
                   6585:   width: 25px;
                   6586:   height: 1px;
1.771     droeschl 6587:   border: none;
1.543     albertel 6588: }
1.346     albertel 6589: 
1.532     albertel 6590: .LC_internal_info {
1.735     bisitz   6591:   color: #999999;
1.532     albertel 6592: }
                   6593: 
1.794     www      6594: .LC_discussion {
1.1050    www      6595:   background: $data_table_dark;
1.911     bisitz   6596:   border: 1px solid black;
                   6597:   margin: 2px;
1.794     www      6598: }
                   6599: 
                   6600: .LC_disc_action_left {
1.1050    www      6601:   background: $sidebg;
1.911     bisitz   6602:   text-align: left;
1.1050    www      6603:   padding: 4px;
                   6604:   margin: 2px;
1.794     www      6605: }
                   6606: 
                   6607: .LC_disc_action_right {
1.1050    www      6608:   background: $sidebg;
1.911     bisitz   6609:   text-align: right;
1.1050    www      6610:   padding: 4px;
                   6611:   margin: 2px;
1.794     www      6612: }
                   6613: 
                   6614: .LC_disc_new_item {
1.911     bisitz   6615:   background: white;
                   6616:   border: 2px solid red;
1.1050    www      6617:   margin: 4px;
                   6618:   padding: 4px;
1.794     www      6619: }
                   6620: 
                   6621: .LC_disc_old_item {
1.911     bisitz   6622:   background: white;
1.1050    www      6623:   margin: 4px;
                   6624:   padding: 4px;
1.794     www      6625: }
                   6626: 
1.458     albertel 6627: table.LC_pastsubmission {
                   6628:   border: 1px solid black;
                   6629:   margin: 2px;
                   6630: }
                   6631: 
1.924     bisitz   6632: table#LC_menubuttons {
1.345     albertel 6633:   width: 100%;
                   6634:   background: $pgbg;
1.392     albertel 6635:   border: 2px;
1.402     albertel 6636:   border-collapse: separate;
1.803     bisitz   6637:   padding: 0;
1.345     albertel 6638: }
1.392     albertel 6639: 
1.801     tempelho 6640: table#LC_title_bar a {
                   6641:   color: $fontmenu;
                   6642: }
1.836     bisitz   6643: 
1.807     droeschl 6644: table#LC_title_bar {
1.819     tempelho 6645:   clear: both;
1.836     bisitz   6646:   display: none;
1.807     droeschl 6647: }
                   6648: 
1.795     www      6649: table#LC_title_bar,
1.933     droeschl 6650: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6651: table#LC_title_bar.LC_with_remote {
1.359     albertel 6652:   width: 100%;
1.392     albertel 6653:   border-color: $pgbg;
                   6654:   border-style: solid;
                   6655:   border-width: $border;
1.379     albertel 6656:   background: $pgbg;
1.801     tempelho 6657:   color: $fontmenu;
1.392     albertel 6658:   border-collapse: collapse;
1.803     bisitz   6659:   padding: 0;
1.819     tempelho 6660:   margin: 0;
1.359     albertel 6661: }
1.795     www      6662: 
1.933     droeschl 6663: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6664:     margin: 0;
                   6665:     padding: 0;
1.933     droeschl 6666:     position: relative;
                   6667:     list-style: none;
1.913     droeschl 6668: }
1.933     droeschl 6669: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6670:     display: inline;
                   6671: }
1.933     droeschl 6672: 
                   6673: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6674:     padding: 0;
1.933     droeschl 6675:     margin: 0;
                   6676:     float: left;
1.913     droeschl 6677: }
1.933     droeschl 6678: .LC_breadcrumb_tools_tools {
                   6679:     padding: 0;
                   6680:     margin: 0;
1.913     droeschl 6681:     float: right;
                   6682: }
                   6683: 
1.1240    raeburn  6684: .LC_placement_prog {
                   6685:     padding-right: 20px;
                   6686:     font-weight: bold;
                   6687:     font-size: 90%;
                   6688: }
                   6689: 
1.359     albertel 6690: table#LC_title_bar td {
                   6691:   background: $tabbg;
                   6692: }
1.795     www      6693: 
1.911     bisitz   6694: table#LC_menubuttons img {
1.803     bisitz   6695:   border: none;
1.346     albertel 6696: }
1.795     www      6697: 
1.842     droeschl 6698: .LC_breadcrumbs_component {
1.911     bisitz   6699:   float: right;
                   6700:   margin: 0 1em;
1.357     albertel 6701: }
1.842     droeschl 6702: .LC_breadcrumbs_component img {
1.911     bisitz   6703:   vertical-align: middle;
1.777     tempelho 6704: }
1.795     www      6705: 
1.1243    raeburn  6706: .LC_breadcrumbs_hoverable {
                   6707:   background: $sidebg;
                   6708: }
                   6709: 
1.383     albertel 6710: td.LC_table_cell_checkbox {
                   6711:   text-align: center;
                   6712: }
1.795     www      6713: 
                   6714: .LC_fontsize_small {
1.911     bisitz   6715:   font-size: 70%;
1.705     tempelho 6716: }
                   6717: 
1.844     bisitz   6718: #LC_breadcrumbs {
1.911     bisitz   6719:   clear:both;
                   6720:   background: $sidebg;
                   6721:   border-bottom: 1px solid $lg_border_color;
                   6722:   line-height: 2.5em;
1.933     droeschl 6723:   overflow: hidden;
1.911     bisitz   6724:   margin: 0;
                   6725:   padding: 0;
1.995     raeburn  6726:   text-align: left;
1.819     tempelho 6727: }
1.862     bisitz   6728: 
1.1098    bisitz   6729: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6730:   clear:both;
                   6731:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6732:   border: 1px solid $sidebg;
1.1098    bisitz   6733:   margin: 0 0 10px 0;
1.966     bisitz   6734:   padding: 3px;
1.995     raeburn  6735:   text-align: left;
1.822     bisitz   6736: }
                   6737: 
1.795     www      6738: .LC_fontsize_medium {
1.911     bisitz   6739:   font-size: 85%;
1.705     tempelho 6740: }
                   6741: 
1.795     www      6742: .LC_fontsize_large {
1.911     bisitz   6743:   font-size: 120%;
1.705     tempelho 6744: }
                   6745: 
1.346     albertel 6746: .LC_menubuttons_inline_text {
                   6747:   color: $font;
1.698     harmsja  6748:   font-size: 90%;
1.701     harmsja  6749:   padding-left:3px;
1.346     albertel 6750: }
                   6751: 
1.934     droeschl 6752: .LC_menubuttons_inline_text img{
                   6753:   vertical-align: middle;
                   6754: }
                   6755: 
1.1051    www      6756: li.LC_menubuttons_inline_text img {
1.951     onken    6757:   cursor:pointer;
1.1002    droeschl 6758:   text-decoration: none;
1.951     onken    6759: }
                   6760: 
1.526     www      6761: .LC_menubuttons_link {
                   6762:   text-decoration: none;
                   6763: }
1.795     www      6764: 
1.522     albertel 6765: .LC_menubuttons_category {
1.521     www      6766:   color: $font;
1.526     www      6767:   background: $pgbg;
1.521     www      6768:   font-size: larger;
                   6769:   font-weight: bold;
                   6770: }
                   6771: 
1.346     albertel 6772: td.LC_menubuttons_text {
1.911     bisitz   6773:   color: $font;
1.346     albertel 6774: }
1.706     harmsja  6775: 
1.346     albertel 6776: .LC_current_location {
                   6777:   background: $tabbg;
                   6778: }
1.795     www      6779: 
1.1286    raeburn  6780: td.LC_zero_height {
                   6781:   line-height: 0; 
                   6782:   cellpadding: 0;
                   6783: }
                   6784: 
1.938     bisitz   6785: table.LC_data_table {
1.347     albertel 6786:   border: 1px solid #000000;
1.402     albertel 6787:   border-collapse: separate;
1.426     albertel 6788:   border-spacing: 1px;
1.610     albertel 6789:   background: $pgbg;
1.347     albertel 6790: }
1.795     www      6791: 
1.422     albertel 6792: .LC_data_table_dense {
                   6793:   font-size: small;
                   6794: }
1.795     www      6795: 
1.507     raeburn  6796: table.LC_nested_outer {
                   6797:   border: 1px solid #000000;
1.589     raeburn  6798:   border-collapse: collapse;
1.803     bisitz   6799:   border-spacing: 0;
1.507     raeburn  6800:   width: 100%;
                   6801: }
1.795     www      6802: 
1.879     raeburn  6803: table.LC_innerpickbox,
1.507     raeburn  6804: table.LC_nested {
1.803     bisitz   6805:   border: none;
1.589     raeburn  6806:   border-collapse: collapse;
1.803     bisitz   6807:   border-spacing: 0;
1.507     raeburn  6808:   width: 100%;
                   6809: }
1.795     www      6810: 
1.911     bisitz   6811: table.LC_data_table tr th,
                   6812: table.LC_calendar tr th,
1.879     raeburn  6813: table.LC_prior_tries tr th,
                   6814: table.LC_innerpickbox tr th {
1.349     albertel 6815:   font-weight: bold;
                   6816:   background-color: $data_table_head;
1.801     tempelho 6817:   color:$fontmenu;
1.701     harmsja  6818:   font-size:90%;
1.347     albertel 6819: }
1.795     www      6820: 
1.879     raeburn  6821: table.LC_innerpickbox tr th,
                   6822: table.LC_innerpickbox tr td {
                   6823:   vertical-align: top;
                   6824: }
                   6825: 
1.711     raeburn  6826: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6827:   background-color: #CCCCCC;
1.711     raeburn  6828:   font-weight: bold;
                   6829:   text-align: left;
                   6830: }
1.795     www      6831: 
1.912     bisitz   6832: table.LC_data_table tr.LC_odd_row > td {
                   6833:   background-color: $data_table_light;
                   6834:   padding: 2px;
                   6835:   vertical-align: top;
                   6836: }
                   6837: 
1.809     bisitz   6838: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6839:   background-color: $data_table_light;
1.912     bisitz   6840:   vertical-align: top;
                   6841: }
                   6842: 
                   6843: table.LC_data_table tr.LC_even_row > td {
                   6844:   background-color: $data_table_dark;
1.425     albertel 6845:   padding: 2px;
1.900     bisitz   6846:   vertical-align: top;
1.347     albertel 6847: }
1.795     www      6848: 
1.809     bisitz   6849: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6850:   background-color: $data_table_dark;
1.900     bisitz   6851:   vertical-align: top;
1.347     albertel 6852: }
1.795     www      6853: 
1.425     albertel 6854: table.LC_data_table tr.LC_data_table_highlight td {
                   6855:   background-color: $data_table_darker;
                   6856: }
1.795     www      6857: 
1.639     raeburn  6858: table.LC_data_table tr td.LC_leftcol_header {
                   6859:   background-color: $data_table_head;
                   6860:   font-weight: bold;
                   6861: }
1.795     www      6862: 
1.451     albertel 6863: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6864: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6865:   font-weight: bold;
                   6866:   font-style: italic;
                   6867:   text-align: center;
                   6868:   padding: 8px;
1.347     albertel 6869: }
1.795     www      6870: 
1.1114    raeburn  6871: table.LC_data_table tr.LC_empty_row td,
                   6872: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6873:   background-color: $sidebg;
                   6874: }
                   6875: 
                   6876: table.LC_nested tr.LC_empty_row td {
                   6877:   background-color: #FFFFFF;
                   6878: }
                   6879: 
1.890     droeschl 6880: table.LC_caption {
                   6881: }
                   6882: 
1.507     raeburn  6883: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6884:   padding: 4ex
                   6885: }
1.795     www      6886: 
1.507     raeburn  6887: table.LC_nested_outer tr th {
                   6888:   font-weight: bold;
1.801     tempelho 6889:   color:$fontmenu;
1.507     raeburn  6890:   background-color: $data_table_head;
1.701     harmsja  6891:   font-size: small;
1.507     raeburn  6892:   border-bottom: 1px solid #000000;
                   6893: }
1.795     www      6894: 
1.507     raeburn  6895: table.LC_nested_outer tr td.LC_subheader {
                   6896:   background-color: $data_table_head;
                   6897:   font-weight: bold;
                   6898:   font-size: small;
                   6899:   border-bottom: 1px solid #000000;
                   6900:   text-align: right;
1.451     albertel 6901: }
1.795     www      6902: 
1.507     raeburn  6903: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6904:   background-color: #CCCCCC;
1.451     albertel 6905:   font-weight: bold;
                   6906:   font-size: small;
1.507     raeburn  6907:   text-align: center;
                   6908: }
1.795     www      6909: 
1.589     raeburn  6910: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6911: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6912:   text-align: left;
1.451     albertel 6913: }
1.795     www      6914: 
1.507     raeburn  6915: table.LC_nested td {
1.735     bisitz   6916:   background-color: #FFFFFF;
1.451     albertel 6917:   font-size: small;
1.507     raeburn  6918: }
1.795     www      6919: 
1.507     raeburn  6920: table.LC_nested_outer tr th.LC_right_item,
                   6921: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6922: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6923: table.LC_nested tr td.LC_right_item {
1.451     albertel 6924:   text-align: right;
                   6925: }
                   6926: 
1.507     raeburn  6927: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6928:   background-color: #EEEEEE;
1.451     albertel 6929: }
                   6930: 
1.473     raeburn  6931: table.LC_createuser {
                   6932: }
                   6933: 
                   6934: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6935:   font-size: small;
1.473     raeburn  6936: }
                   6937: 
                   6938: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6939:   background-color: #CCCCCC;
1.473     raeburn  6940:   font-weight: bold;
                   6941:   text-align: center;
                   6942: }
                   6943: 
1.349     albertel 6944: table.LC_calendar {
                   6945:   border: 1px solid #000000;
                   6946:   border-collapse: collapse;
1.917     raeburn  6947:   width: 98%;
1.349     albertel 6948: }
1.795     www      6949: 
1.349     albertel 6950: table.LC_calendar_pickdate {
                   6951:   font-size: xx-small;
                   6952: }
1.795     www      6953: 
1.349     albertel 6954: table.LC_calendar tr td {
                   6955:   border: 1px solid #000000;
                   6956:   vertical-align: top;
1.917     raeburn  6957:   width: 14%;
1.349     albertel 6958: }
1.795     www      6959: 
1.349     albertel 6960: table.LC_calendar tr td.LC_calendar_day_empty {
                   6961:   background-color: $data_table_dark;
                   6962: }
1.795     www      6963: 
1.779     bisitz   6964: table.LC_calendar tr td.LC_calendar_day_current {
                   6965:   background-color: $data_table_highlight;
1.777     tempelho 6966: }
1.795     www      6967: 
1.938     bisitz   6968: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6969:   background-color: $mail_new;
                   6970: }
1.795     www      6971: 
1.938     bisitz   6972: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6973:   background-color: $mail_new_hover;
                   6974: }
1.795     www      6975: 
1.938     bisitz   6976: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6977:   background-color: $mail_read;
                   6978: }
1.795     www      6979: 
1.938     bisitz   6980: /*
                   6981: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6982:   background-color: $mail_read_hover;
                   6983: }
1.938     bisitz   6984: */
1.795     www      6985: 
1.938     bisitz   6986: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6987:   background-color: $mail_replied;
                   6988: }
1.795     www      6989: 
1.938     bisitz   6990: /*
                   6991: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6992:   background-color: $mail_replied_hover;
                   6993: }
1.938     bisitz   6994: */
1.795     www      6995: 
1.938     bisitz   6996: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6997:   background-color: $mail_other;
                   6998: }
1.795     www      6999: 
1.938     bisitz   7000: /*
                   7001: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7002:   background-color: $mail_other_hover;
                   7003: }
1.938     bisitz   7004: */
1.494     raeburn  7005: 
1.777     tempelho 7006: table.LC_data_table tr > td.LC_browser_file,
                   7007: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7008:   background: #AAEE77;
1.389     albertel 7009: }
1.795     www      7010: 
1.777     tempelho 7011: table.LC_data_table tr > td.LC_browser_file_locked,
                   7012: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7013:   background: #FFAA99;
1.387     albertel 7014: }
1.795     www      7015: 
1.777     tempelho 7016: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7017:   background: #888888;
1.779     bisitz   7018: }
1.795     www      7019: 
1.777     tempelho 7020: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7021: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7022:   background: #F8F866;
1.777     tempelho 7023: }
1.795     www      7024: 
1.696     bisitz   7025: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7026:   background: #E0E8FF;
1.387     albertel 7027: }
1.696     bisitz   7028: 
1.707     bisitz   7029: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7030:   /* background: #77FF77; */
1.707     bisitz   7031: }
1.795     www      7032: 
1.707     bisitz   7033: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7034:   border-right: 8px solid #FFFF77;
1.707     bisitz   7035: }
1.795     www      7036: 
1.707     bisitz   7037: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7038:   border-right: 8px solid #FFAA77;
1.707     bisitz   7039: }
1.795     www      7040: 
1.707     bisitz   7041: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7042:   border-right: 8px solid #FF7777;
1.707     bisitz   7043: }
1.795     www      7044: 
1.707     bisitz   7045: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7046:   border-right: 8px solid #AAFF77;
1.707     bisitz   7047: }
1.795     www      7048: 
1.707     bisitz   7049: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7050:   border-right: 8px solid #11CC55;
1.707     bisitz   7051: }
                   7052: 
1.388     albertel 7053: span.LC_current_location {
1.701     harmsja  7054:   font-size:larger;
1.388     albertel 7055:   background: $pgbg;
                   7056: }
1.387     albertel 7057: 
1.1029    www      7058: span.LC_current_nav_location {
                   7059:   font-weight:bold;
                   7060:   background: $sidebg;
                   7061: }
                   7062: 
1.395     albertel 7063: span.LC_parm_menu_item {
                   7064:   font-size: larger;
                   7065: }
1.795     www      7066: 
1.395     albertel 7067: span.LC_parm_scope_all {
                   7068:   color: red;
                   7069: }
1.795     www      7070: 
1.395     albertel 7071: span.LC_parm_scope_folder {
                   7072:   color: green;
                   7073: }
1.795     www      7074: 
1.395     albertel 7075: span.LC_parm_scope_resource {
                   7076:   color: orange;
                   7077: }
1.795     www      7078: 
1.395     albertel 7079: span.LC_parm_part {
                   7080:   color: blue;
                   7081: }
1.795     www      7082: 
1.911     bisitz   7083: span.LC_parm_folder,
                   7084: span.LC_parm_symb {
1.395     albertel 7085:   font-size: x-small;
                   7086:   font-family: $mono;
                   7087:   color: #AAAAAA;
                   7088: }
                   7089: 
1.977     bisitz   7090: ul.LC_parm_parmlist li {
                   7091:   display: inline-block;
                   7092:   padding: 0.3em 0.8em;
                   7093:   vertical-align: top;
                   7094:   width: 150px;
                   7095:   border-top:1px solid $lg_border_color;
                   7096: }
                   7097: 
1.795     www      7098: td.LC_parm_overview_level_menu,
                   7099: td.LC_parm_overview_map_menu,
                   7100: td.LC_parm_overview_parm_selectors,
                   7101: td.LC_parm_overview_restrictions  {
1.396     albertel 7102:   border: 1px solid black;
                   7103:   border-collapse: collapse;
                   7104: }
1.795     www      7105: 
1.1285    raeburn  7106: span.LC_parm_recursive,
                   7107: td.LC_parm_recursive {
                   7108:   font-weight: bold;
                   7109:   font-size: smaller;
                   7110: }
                   7111: 
1.396     albertel 7112: table.LC_parm_overview_restrictions td {
                   7113:   border-width: 1px 4px 1px 4px;
                   7114:   border-style: solid;
                   7115:   border-color: $pgbg;
                   7116:   text-align: center;
                   7117: }
1.795     www      7118: 
1.396     albertel 7119: table.LC_parm_overview_restrictions th {
                   7120:   background: $tabbg;
                   7121:   border-width: 1px 4px 1px 4px;
                   7122:   border-style: solid;
                   7123:   border-color: $pgbg;
                   7124: }
1.795     www      7125: 
1.398     albertel 7126: table#LC_helpmenu {
1.803     bisitz   7127:   border: none;
1.398     albertel 7128:   height: 55px;
1.803     bisitz   7129:   border-spacing: 0;
1.398     albertel 7130: }
                   7131: 
                   7132: table#LC_helpmenu fieldset legend {
                   7133:   font-size: larger;
                   7134: }
1.795     www      7135: 
1.397     albertel 7136: table#LC_helpmenu_links {
                   7137:   width: 100%;
                   7138:   border: 1px solid black;
                   7139:   background: $pgbg;
1.803     bisitz   7140:   padding: 0;
1.397     albertel 7141:   border-spacing: 1px;
                   7142: }
1.795     www      7143: 
1.397     albertel 7144: table#LC_helpmenu_links tr td {
                   7145:   padding: 1px;
                   7146:   background: $tabbg;
1.399     albertel 7147:   text-align: center;
                   7148:   font-weight: bold;
1.397     albertel 7149: }
1.396     albertel 7150: 
1.795     www      7151: table#LC_helpmenu_links a:link,
                   7152: table#LC_helpmenu_links a:visited,
1.397     albertel 7153: table#LC_helpmenu_links a:active {
                   7154:   text-decoration: none;
                   7155:   color: $font;
                   7156: }
1.795     www      7157: 
1.397     albertel 7158: table#LC_helpmenu_links a:hover {
                   7159:   text-decoration: underline;
                   7160:   color: $vlink;
                   7161: }
1.396     albertel 7162: 
1.417     albertel 7163: .LC_chrt_popup_exists {
                   7164:   border: 1px solid #339933;
                   7165:   margin: -1px;
                   7166: }
1.795     www      7167: 
1.417     albertel 7168: .LC_chrt_popup_up {
                   7169:   border: 1px solid yellow;
                   7170:   margin: -1px;
                   7171: }
1.795     www      7172: 
1.417     albertel 7173: .LC_chrt_popup {
                   7174:   border: 1px solid #8888FF;
                   7175:   background: #CCCCFF;
                   7176: }
1.795     www      7177: 
1.421     albertel 7178: table.LC_pick_box {
                   7179:   border-collapse: separate;
                   7180:   background: white;
                   7181:   border: 1px solid black;
                   7182:   border-spacing: 1px;
                   7183: }
1.795     www      7184: 
1.421     albertel 7185: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7186:   background: $sidebg;
1.421     albertel 7187:   font-weight: bold;
1.900     bisitz   7188:   text-align: left;
1.740     bisitz   7189:   vertical-align: top;
1.421     albertel 7190:   width: 184px;
                   7191:   padding: 8px;
                   7192: }
1.795     www      7193: 
1.579     raeburn  7194: table.LC_pick_box td.LC_pick_box_value {
                   7195:   text-align: left;
                   7196:   padding: 8px;
                   7197: }
1.795     www      7198: 
1.579     raeburn  7199: table.LC_pick_box td.LC_pick_box_select {
                   7200:   text-align: left;
                   7201:   padding: 8px;
                   7202: }
1.795     www      7203: 
1.424     albertel 7204: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7205:   padding: 0;
1.421     albertel 7206:   height: 1px;
                   7207:   background: black;
                   7208: }
1.795     www      7209: 
1.421     albertel 7210: table.LC_pick_box td.LC_pick_box_submit {
                   7211:   text-align: right;
                   7212: }
1.795     www      7213: 
1.579     raeburn  7214: table.LC_pick_box td.LC_evenrow_value {
                   7215:   text-align: left;
                   7216:   padding: 8px;
                   7217:   background-color: $data_table_light;
                   7218: }
1.795     www      7219: 
1.579     raeburn  7220: table.LC_pick_box td.LC_oddrow_value {
                   7221:   text-align: left;
                   7222:   padding: 8px;
                   7223:   background-color: $data_table_light;
                   7224: }
1.795     www      7225: 
1.579     raeburn  7226: span.LC_helpform_receipt_cat {
                   7227:   font-weight: bold;
                   7228: }
1.795     www      7229: 
1.424     albertel 7230: table.LC_group_priv_box {
                   7231:   background: white;
                   7232:   border: 1px solid black;
                   7233:   border-spacing: 1px;
                   7234: }
1.795     www      7235: 
1.424     albertel 7236: table.LC_group_priv_box td.LC_pick_box_title {
                   7237:   background: $tabbg;
                   7238:   font-weight: bold;
                   7239:   text-align: right;
                   7240:   width: 184px;
                   7241: }
1.795     www      7242: 
1.424     albertel 7243: table.LC_group_priv_box td.LC_groups_fixed {
                   7244:   background: $data_table_light;
                   7245:   text-align: center;
                   7246: }
1.795     www      7247: 
1.424     albertel 7248: table.LC_group_priv_box td.LC_groups_optional {
                   7249:   background: $data_table_dark;
                   7250:   text-align: center;
                   7251: }
1.795     www      7252: 
1.424     albertel 7253: table.LC_group_priv_box td.LC_groups_functionality {
                   7254:   background: $data_table_darker;
                   7255:   text-align: center;
                   7256:   font-weight: bold;
                   7257: }
1.795     www      7258: 
1.424     albertel 7259: table.LC_group_priv td {
                   7260:   text-align: left;
1.803     bisitz   7261:   padding: 0;
1.424     albertel 7262: }
                   7263: 
                   7264: .LC_navbuttons {
                   7265:   margin: 2ex 0ex 2ex 0ex;
                   7266: }
1.795     www      7267: 
1.423     albertel 7268: .LC_topic_bar {
                   7269:   font-weight: bold;
                   7270:   background: $tabbg;
1.918     wenzelju 7271:   margin: 1em 0em 1em 2em;
1.805     bisitz   7272:   padding: 3px;
1.918     wenzelju 7273:   font-size: 1.2em;
1.423     albertel 7274: }
1.795     www      7275: 
1.423     albertel 7276: .LC_topic_bar span {
1.918     wenzelju 7277:   left: 0.5em;
                   7278:   position: absolute;
1.423     albertel 7279:   vertical-align: middle;
1.918     wenzelju 7280:   font-size: 1.2em;
1.423     albertel 7281: }
1.795     www      7282: 
1.423     albertel 7283: table.LC_course_group_status {
                   7284:   margin: 20px;
                   7285: }
1.795     www      7286: 
1.423     albertel 7287: table.LC_status_selector td {
                   7288:   vertical-align: top;
                   7289:   text-align: center;
1.424     albertel 7290:   padding: 4px;
                   7291: }
1.795     www      7292: 
1.599     albertel 7293: div.LC_feedback_link {
1.616     albertel 7294:   clear: both;
1.829     kalberla 7295:   background: $sidebg;
1.779     bisitz   7296:   width: 100%;
1.829     kalberla 7297:   padding-bottom: 10px;
                   7298:   border: 1px $tabbg solid;
1.833     kalberla 7299:   height: 22px;
                   7300:   line-height: 22px;
                   7301:   padding-top: 5px;
                   7302: }
                   7303: 
                   7304: div.LC_feedback_link img {
                   7305:   height: 22px;
1.867     kalberla 7306:   vertical-align:middle;
1.829     kalberla 7307: }
                   7308: 
1.911     bisitz   7309: div.LC_feedback_link a {
1.829     kalberla 7310:   text-decoration: none;
1.489     raeburn  7311: }
1.795     www      7312: 
1.867     kalberla 7313: div.LC_comblock {
1.911     bisitz   7314:   display:inline;
1.867     kalberla 7315:   color:$font;
                   7316:   font-size:90%;
                   7317: }
                   7318: 
                   7319: div.LC_feedback_link div.LC_comblock {
                   7320:   padding-left:5px;
                   7321: }
                   7322: 
                   7323: div.LC_feedback_link div.LC_comblock a {
                   7324:   color:$font;
                   7325: }
                   7326: 
1.489     raeburn  7327: span.LC_feedback_link {
1.858     bisitz   7328:   /* background: $feedback_link_bg; */
1.599     albertel 7329:   font-size: larger;
                   7330: }
1.795     www      7331: 
1.599     albertel 7332: span.LC_message_link {
1.858     bisitz   7333:   /* background: $feedback_link_bg; */
1.599     albertel 7334:   font-size: larger;
                   7335:   position: absolute;
                   7336:   right: 1em;
1.489     raeburn  7337: }
1.421     albertel 7338: 
1.515     albertel 7339: table.LC_prior_tries {
1.524     albertel 7340:   border: 1px solid #000000;
                   7341:   border-collapse: separate;
                   7342:   border-spacing: 1px;
1.515     albertel 7343: }
1.523     albertel 7344: 
1.515     albertel 7345: table.LC_prior_tries td {
1.524     albertel 7346:   padding: 2px;
1.515     albertel 7347: }
1.523     albertel 7348: 
                   7349: .LC_answer_correct {
1.795     www      7350:   background: lightgreen;
                   7351:   color: darkgreen;
                   7352:   padding: 6px;
1.523     albertel 7353: }
1.795     www      7354: 
1.523     albertel 7355: .LC_answer_charged_try {
1.797     www      7356:   background: #FFAAAA;
1.795     www      7357:   color: darkred;
                   7358:   padding: 6px;
1.523     albertel 7359: }
1.795     www      7360: 
1.779     bisitz   7361: .LC_answer_not_charged_try,
1.523     albertel 7362: .LC_answer_no_grade,
                   7363: .LC_answer_late {
1.795     www      7364:   background: lightyellow;
1.523     albertel 7365:   color: black;
1.795     www      7366:   padding: 6px;
1.523     albertel 7367: }
1.795     www      7368: 
1.523     albertel 7369: .LC_answer_previous {
1.795     www      7370:   background: lightblue;
                   7371:   color: darkblue;
                   7372:   padding: 6px;
1.523     albertel 7373: }
1.795     www      7374: 
1.779     bisitz   7375: .LC_answer_no_message {
1.777     tempelho 7376:   background: #FFFFFF;
                   7377:   color: black;
1.795     www      7378:   padding: 6px;
1.779     bisitz   7379: }
1.795     www      7380: 
1.1334    raeburn  7381: .LC_answer_unknown,
                   7382: .LC_answer_warning {
1.779     bisitz   7383:   background: orange;
                   7384:   color: black;
1.795     www      7385:   padding: 6px;
1.777     tempelho 7386: }
1.795     www      7387: 
1.529     albertel 7388: span.LC_prior_numerical,
                   7389: span.LC_prior_string,
                   7390: span.LC_prior_custom,
                   7391: span.LC_prior_reaction,
                   7392: span.LC_prior_math {
1.925     bisitz   7393:   font-family: $mono;
1.523     albertel 7394:   white-space: pre;
                   7395: }
                   7396: 
1.525     albertel 7397: span.LC_prior_string {
1.925     bisitz   7398:   font-family: $mono;
1.525     albertel 7399:   white-space: pre;
                   7400: }
                   7401: 
1.523     albertel 7402: table.LC_prior_option {
                   7403:   width: 100%;
                   7404:   border-collapse: collapse;
                   7405: }
1.795     www      7406: 
1.911     bisitz   7407: table.LC_prior_rank,
1.795     www      7408: table.LC_prior_match {
1.528     albertel 7409:   border-collapse: collapse;
                   7410: }
1.795     www      7411: 
1.528     albertel 7412: table.LC_prior_option tr td,
                   7413: table.LC_prior_rank tr td,
                   7414: table.LC_prior_match tr td {
1.524     albertel 7415:   border: 1px solid #000000;
1.515     albertel 7416: }
                   7417: 
1.855     bisitz   7418: .LC_nobreak {
1.544     albertel 7419:   white-space: nowrap;
1.519     raeburn  7420: }
                   7421: 
1.576     raeburn  7422: span.LC_cusr_emph {
                   7423:   font-style: italic;
                   7424: }
                   7425: 
1.633     raeburn  7426: span.LC_cusr_subheading {
                   7427:   font-weight: normal;
                   7428:   font-size: 85%;
                   7429: }
                   7430: 
1.861     bisitz   7431: div.LC_docs_entry_move {
1.859     bisitz   7432:   border: 1px solid #BBBBBB;
1.545     albertel 7433:   background: #DDDDDD;
1.861     bisitz   7434:   width: 22px;
1.859     bisitz   7435:   padding: 1px;
                   7436:   margin: 0;
1.545     albertel 7437: }
                   7438: 
1.861     bisitz   7439: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7440: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7441:   font-size: x-small;
                   7442: }
1.795     www      7443: 
1.861     bisitz   7444: .LC_docs_entry_parameter {
                   7445:   white-space: nowrap;
                   7446: }
                   7447: 
1.544     albertel 7448: .LC_docs_copy {
1.545     albertel 7449:   color: #000099;
1.544     albertel 7450: }
1.795     www      7451: 
1.544     albertel 7452: .LC_docs_cut {
1.545     albertel 7453:   color: #550044;
1.544     albertel 7454: }
1.795     www      7455: 
1.544     albertel 7456: .LC_docs_rename {
1.545     albertel 7457:   color: #009900;
1.544     albertel 7458: }
1.795     www      7459: 
1.544     albertel 7460: .LC_docs_remove {
1.545     albertel 7461:   color: #990000;
                   7462: }
                   7463: 
1.1284    raeburn  7464: .LC_docs_alias {
                   7465:   color: #440055;  
                   7466: }
                   7467: 
1.1286    raeburn  7468: .LC_domprefs_email,
1.1284    raeburn  7469: .LC_docs_alias_name,
1.547     albertel 7470: .LC_docs_reinit_warn,
                   7471: .LC_docs_ext_edit {
                   7472:   font-size: x-small;
                   7473: }
                   7474: 
1.545     albertel 7475: table.LC_docs_adddocs td,
                   7476: table.LC_docs_adddocs th {
                   7477:   border: 1px solid #BBBBBB;
                   7478:   padding: 4px;
                   7479:   background: #DDDDDD;
1.543     albertel 7480: }
                   7481: 
1.584     albertel 7482: table.LC_sty_begin {
                   7483:   background: #BBFFBB;
                   7484: }
1.795     www      7485: 
1.584     albertel 7486: table.LC_sty_end {
                   7487:   background: #FFBBBB;
                   7488: }
                   7489: 
1.589     raeburn  7490: table.LC_double_column {
1.803     bisitz   7491:   border-width: 0;
1.589     raeburn  7492:   border-collapse: collapse;
                   7493:   width: 100%;
                   7494:   padding: 2px;
                   7495: }
                   7496: 
                   7497: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7498:   top: 2px;
1.589     raeburn  7499:   left: 2px;
                   7500:   width: 47%;
                   7501:   vertical-align: top;
                   7502: }
                   7503: 
                   7504: table.LC_double_column tr td.LC_right_col {
                   7505:   top: 2px;
1.779     bisitz   7506:   right: 2px;
1.589     raeburn  7507:   width: 47%;
                   7508:   vertical-align: top;
                   7509: }
                   7510: 
1.591     raeburn  7511: div.LC_left_float {
                   7512:   float: left;
                   7513:   padding-right: 5%;
1.597     albertel 7514:   padding-bottom: 4px;
1.591     raeburn  7515: }
                   7516: 
                   7517: div.LC_clear_float_header {
1.597     albertel 7518:   padding-bottom: 2px;
1.591     raeburn  7519: }
                   7520: 
                   7521: div.LC_clear_float_footer {
1.597     albertel 7522:   padding-top: 10px;
1.591     raeburn  7523:   clear: both;
                   7524: }
                   7525: 
1.597     albertel 7526: div.LC_grade_show_user {
1.941     bisitz   7527: /*  border-left: 5px solid $sidebg; */
                   7528:   border-top: 5px solid #000000;
                   7529:   margin: 50px 0 0 0;
1.936     bisitz   7530:   padding: 15px 0 5px 10px;
1.597     albertel 7531: }
1.795     www      7532: 
1.936     bisitz   7533: div.LC_grade_show_user_odd_row {
1.941     bisitz   7534: /*  border-left: 5px solid #000000; */
                   7535: }
                   7536: 
                   7537: div.LC_grade_show_user div.LC_Box {
                   7538:   margin-right: 50px;
1.597     albertel 7539: }
                   7540: 
                   7541: div.LC_grade_submissions,
                   7542: div.LC_grade_message_center,
1.936     bisitz   7543: div.LC_grade_info_links {
1.597     albertel 7544:   margin: 5px;
                   7545:   width: 99%;
                   7546:   background: #FFFFFF;
                   7547: }
1.795     www      7548: 
1.597     albertel 7549: div.LC_grade_submissions_header,
1.936     bisitz   7550: div.LC_grade_message_center_header {
1.705     tempelho 7551:   font-weight: bold;
                   7552:   font-size: large;
1.597     albertel 7553: }
1.795     www      7554: 
1.597     albertel 7555: div.LC_grade_submissions_body,
1.936     bisitz   7556: div.LC_grade_message_center_body {
1.597     albertel 7557:   border: 1px solid black;
                   7558:   width: 99%;
                   7559:   background: #FFFFFF;
                   7560: }
1.795     www      7561: 
1.613     albertel 7562: table.LC_scantron_action {
                   7563:   width: 100%;
                   7564: }
1.795     www      7565: 
1.613     albertel 7566: table.LC_scantron_action tr th {
1.698     harmsja  7567:   font-weight:bold;
                   7568:   font-style:normal;
1.613     albertel 7569: }
1.795     www      7570: 
1.779     bisitz   7571: .LC_edit_problem_header,
1.614     albertel 7572: div.LC_edit_problem_footer {
1.705     tempelho 7573:   font-weight: normal;
                   7574:   font-size:  medium;
1.602     albertel 7575:   margin: 2px;
1.1060    bisitz   7576:   background-color: $sidebg;
1.600     albertel 7577: }
1.795     www      7578: 
1.600     albertel 7579: div.LC_edit_problem_header,
1.602     albertel 7580: div.LC_edit_problem_header div,
1.614     albertel 7581: div.LC_edit_problem_footer,
                   7582: div.LC_edit_problem_footer div,
1.602     albertel 7583: div.LC_edit_problem_editxml_header,
                   7584: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7585:   z-index: 100;
1.600     albertel 7586: }
1.795     www      7587: 
1.600     albertel 7588: div.LC_edit_problem_header_title {
1.705     tempelho 7589:   font-weight: bold;
                   7590:   font-size: larger;
1.602     albertel 7591:   background: $tabbg;
                   7592:   padding: 3px;
1.1060    bisitz   7593:   margin: 0 0 5px 0;
1.602     albertel 7594: }
1.795     www      7595: 
1.602     albertel 7596: table.LC_edit_problem_header_title {
                   7597:   width: 100%;
1.600     albertel 7598:   background: $tabbg;
1.602     albertel 7599: }
                   7600: 
1.1205    golterma 7601: div.LC_edit_actionbar {
                   7602:     background-color: $sidebg;
1.1218    droeschl 7603:     margin: 0;
                   7604:     padding: 0;
                   7605:     line-height: 200%;
1.602     albertel 7606: }
1.795     www      7607: 
1.1218    droeschl 7608: div.LC_edit_actionbar div{
                   7609:     padding: 0;
                   7610:     margin: 0;
                   7611:     display: inline-block;
1.600     albertel 7612: }
1.795     www      7613: 
1.1124    bisitz   7614: .LC_edit_opt {
                   7615:   padding-left: 1em;
                   7616:   white-space: nowrap;
                   7617: }
                   7618: 
1.1152    golterma 7619: .LC_edit_problem_latexhelper{
                   7620:     text-align: right;
                   7621: }
                   7622: 
                   7623: #LC_edit_problem_colorful div{
                   7624:     margin-left: 40px;
                   7625: }
                   7626: 
1.1205    golterma 7627: #LC_edit_problem_codemirror div{
                   7628:     margin-left: 0px;
                   7629: }
                   7630: 
1.911     bisitz   7631: img.stift {
1.803     bisitz   7632:   border-width: 0;
                   7633:   vertical-align: middle;
1.677     riegler  7634: }
1.680     riegler  7635: 
1.923     bisitz   7636: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7637:   vertical-align: top;
1.777     tempelho 7638: }
1.795     www      7639: 
1.716     raeburn  7640: div.LC_createcourse {
1.911     bisitz   7641:   margin: 10px 10px 10px 10px;
1.716     raeburn  7642: }
                   7643: 
1.917     raeburn  7644: .LC_dccid {
1.1130    raeburn  7645:   float: right;
1.917     raeburn  7646:   margin: 0.2em 0 0 0;
                   7647:   padding: 0;
                   7648:   font-size: 90%;
                   7649:   display:none;
                   7650: }
                   7651: 
1.897     wenzelju 7652: ol.LC_primary_menu a:hover,
1.721     harmsja  7653: ol#LC_MenuBreadcrumbs a:hover,
                   7654: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7655: ul#LC_secondary_menu a:hover,
1.721     harmsja  7656: .LC_FormSectionClearButton input:hover
1.795     www      7657: ul.LC_TabContent   li:hover a {
1.952     onken    7658:   color:$button_hover;
1.911     bisitz   7659:   text-decoration:none;
1.693     droeschl 7660: }
                   7661: 
1.779     bisitz   7662: h1 {
1.911     bisitz   7663:   padding: 0;
                   7664:   line-height:130%;
1.693     droeschl 7665: }
1.698     harmsja  7666: 
1.911     bisitz   7667: h2,
                   7668: h3,
                   7669: h4,
                   7670: h5,
                   7671: h6 {
                   7672:   margin: 5px 0 5px 0;
                   7673:   padding: 0;
                   7674:   line-height:130%;
1.693     droeschl 7675: }
1.795     www      7676: 
                   7677: .LC_hcell {
1.911     bisitz   7678:   padding:3px 15px 3px 15px;
                   7679:   margin: 0;
                   7680:   background-color:$tabbg;
                   7681:   color:$fontmenu;
                   7682:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7683: }
1.795     www      7684: 
1.840     bisitz   7685: .LC_Box > .LC_hcell {
1.911     bisitz   7686:   margin: 0 -10px 10px -10px;
1.835     bisitz   7687: }
                   7688: 
1.721     harmsja  7689: .LC_noBorder {
1.911     bisitz   7690:   border: 0;
1.698     harmsja  7691: }
1.693     droeschl 7692: 
1.721     harmsja  7693: .LC_FormSectionClearButton input {
1.911     bisitz   7694:   background-color:transparent;
                   7695:   border: none;
                   7696:   cursor:pointer;
                   7697:   text-decoration:underline;
1.693     droeschl 7698: }
1.763     bisitz   7699: 
                   7700: .LC_help_open_topic {
1.911     bisitz   7701:   color: #FFFFFF;
                   7702:   background-color: #EEEEFF;
                   7703:   margin: 1px;
                   7704:   padding: 4px;
                   7705:   border: 1px solid #000033;
                   7706:   white-space: nowrap;
                   7707:   /* vertical-align: middle; */
1.759     neumanie 7708: }
1.693     droeschl 7709: 
1.911     bisitz   7710: dl,
                   7711: ul,
                   7712: div,
                   7713: fieldset {
                   7714:   margin: 10px 10px 10px 0;
                   7715:   /* overflow: hidden; */
1.693     droeschl 7716: }
1.795     www      7717: 
1.1211    raeburn  7718: article.geogebraweb div {
                   7719:     margin: 0;
                   7720: }
                   7721: 
1.838     bisitz   7722: fieldset > legend {
1.911     bisitz   7723:   font-weight: bold;
                   7724:   padding: 0 5px 0 5px;
1.838     bisitz   7725: }
                   7726: 
1.813     bisitz   7727: #LC_nav_bar {
1.911     bisitz   7728:   float: left;
1.995     raeburn  7729:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7730:   margin: 0 0 2px 0;
1.807     droeschl 7731: }
                   7732: 
1.916     droeschl 7733: #LC_realm {
                   7734:   margin: 0.2em 0 0 0;
                   7735:   padding: 0;
                   7736:   font-weight: bold;
                   7737:   text-align: center;
1.995     raeburn  7738:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7739: }
                   7740: 
1.911     bisitz   7741: #LC_nav_bar em {
                   7742:   font-weight: bold;
                   7743:   font-style: normal;
1.807     droeschl 7744: }
                   7745: 
1.897     wenzelju 7746: ol.LC_primary_menu {
1.934     droeschl 7747:   margin: 0;
1.1076    raeburn  7748:   padding: 0;
1.807     droeschl 7749: }
                   7750: 
1.852     droeschl 7751: ol#LC_PathBreadcrumbs {
1.911     bisitz   7752:   margin: 0;
1.693     droeschl 7753: }
                   7754: 
1.897     wenzelju 7755: ol.LC_primary_menu li {
1.1076    raeburn  7756:   color: RGB(80, 80, 80);
                   7757:   vertical-align: middle;
                   7758:   text-align: left;
                   7759:   list-style: none;
1.1205    golterma 7760:   position: relative;
1.1076    raeburn  7761:   float: left;
1.1205    golterma 7762:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7763:   line-height: 1.5em;
1.1076    raeburn  7764: }
                   7765: 
1.1205    golterma 7766: ol.LC_primary_menu li a,
                   7767: ol.LC_primary_menu li p {
1.1076    raeburn  7768:   display: block;
                   7769:   margin: 0;
                   7770:   padding: 0 5px 0 10px;
                   7771:   text-decoration: none;
                   7772: }
                   7773: 
1.1205    golterma 7774: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7775:   display: inline-block;
                   7776:   width: 95%;
                   7777:   text-align: left;
                   7778: }
                   7779: 
                   7780: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7781:   display: inline-block;	
                   7782:   width: 5%;
                   7783:   float: right;
                   7784:   text-align: right;
                   7785:   font-size: 70%;
                   7786: }
                   7787: 
                   7788: ol.LC_primary_menu ul {
1.1076    raeburn  7789:   display: none;
1.1205    golterma 7790:   width: 15em;
1.1076    raeburn  7791:   background-color: $data_table_light;
1.1205    golterma 7792:   position: absolute;
                   7793:   top: 100%;
1.1076    raeburn  7794: }
                   7795: 
1.1205    golterma 7796: ol.LC_primary_menu ul ul {
                   7797:   left: 100%;
                   7798:   top: 0;
                   7799: }
                   7800: 
                   7801: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7802:   display: block;
                   7803:   position: absolute;
                   7804:   margin: 0;
                   7805:   padding: 0;
1.1078    raeburn  7806:   z-index: 2;
1.1076    raeburn  7807: }
                   7808: 
                   7809: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7810: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7811:   font-size: 90%;
1.911     bisitz   7812:   vertical-align: top;
1.1076    raeburn  7813:   float: none;
1.1079    raeburn  7814:   border-left: 1px solid black;
                   7815:   border-right: 1px solid black;
1.1205    golterma 7816: /* A dark bottom border to visualize different menu options; 
                   7817: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7818:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7819: }
                   7820: 
1.1205    golterma 7821: ol.LC_primary_menu li li p:hover {
                   7822:   color:$button_hover;
                   7823:   text-decoration:none;
                   7824:   background-color:$data_table_dark;
1.1076    raeburn  7825: }
                   7826: 
                   7827: ol.LC_primary_menu li li a:hover {
                   7828:    color:$button_hover;
                   7829:    background-color:$data_table_dark;
1.693     droeschl 7830: }
                   7831: 
1.1205    golterma 7832: /* Font-size equal to the size of the predecessors*/
                   7833: ol.LC_primary_menu li:hover li li {
                   7834:   font-size: 100%;
                   7835: }
                   7836: 
1.897     wenzelju 7837: ol.LC_primary_menu li img {
1.911     bisitz   7838:   vertical-align: bottom;
1.934     droeschl 7839:   height: 1.1em;
1.1077    raeburn  7840:   margin: 0.2em 0 0 0;
1.693     droeschl 7841: }
                   7842: 
1.897     wenzelju 7843: ol.LC_primary_menu a {
1.911     bisitz   7844:   color: RGB(80, 80, 80);
                   7845:   text-decoration: none;
1.693     droeschl 7846: }
1.795     www      7847: 
1.949     droeschl 7848: ol.LC_primary_menu a.LC_new_message {
                   7849:   font-weight:bold;
                   7850:   color: darkred;
                   7851: }
                   7852: 
1.975     raeburn  7853: ol.LC_docs_parameters {
                   7854:   margin-left: 0;
                   7855:   padding: 0;
                   7856:   list-style: none;
                   7857: }
                   7858: 
                   7859: ol.LC_docs_parameters li {
                   7860:   margin: 0;
                   7861:   padding-right: 20px;
                   7862:   display: inline;
                   7863: }
                   7864: 
1.976     raeburn  7865: ol.LC_docs_parameters li:before {
                   7866:   content: "\\002022 \\0020";
                   7867: }
                   7868: 
                   7869: li.LC_docs_parameters_title {
                   7870:   font-weight: bold;
                   7871: }
                   7872: 
                   7873: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7874:   content: "";
                   7875: }
                   7876: 
1.897     wenzelju 7877: ul#LC_secondary_menu {
1.1107    raeburn  7878:   clear: right;
1.911     bisitz   7879:   color: $fontmenu;
                   7880:   background: $tabbg;
                   7881:   list-style: none;
                   7882:   padding: 0;
                   7883:   margin: 0;
                   7884:   width: 100%;
1.995     raeburn  7885:   text-align: left;
1.1107    raeburn  7886:   float: left;
1.808     droeschl 7887: }
                   7888: 
1.897     wenzelju 7889: ul#LC_secondary_menu li {
1.911     bisitz   7890:   font-weight: bold;
                   7891:   line-height: 1.8em;
1.1107    raeburn  7892:   border-right: 1px solid black;
                   7893:   float: left;
                   7894: }
                   7895: 
                   7896: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7897:   background-color: $data_table_light;
                   7898: }
                   7899: 
                   7900: ul#LC_secondary_menu li a {
1.911     bisitz   7901:   padding: 0 0.8em;
1.1107    raeburn  7902: }
                   7903: 
                   7904: ul#LC_secondary_menu li ul {
                   7905:   display: none;
                   7906: }
                   7907: 
                   7908: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7909:   display: block;
                   7910:   position: absolute;
                   7911:   margin: 0;
                   7912:   padding: 0;
                   7913:   list-style:none;
                   7914:   float: none;
                   7915:   background-color: $data_table_light;
                   7916:   z-index: 2;
                   7917:   margin-left: -1px;
                   7918: }
                   7919: 
                   7920: ul#LC_secondary_menu li ul li {
                   7921:   font-size: 90%;
                   7922:   vertical-align: top;
                   7923:   border-left: 1px solid black;
1.911     bisitz   7924:   border-right: 1px solid black;
1.1119    raeburn  7925:   background-color: $data_table_light;
1.1107    raeburn  7926:   list-style:none;
                   7927:   float: none;
                   7928: }
                   7929: 
                   7930: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7931:   background-color: $data_table_dark;
1.807     droeschl 7932: }
                   7933: 
1.847     tempelho 7934: ul.LC_TabContent {
1.911     bisitz   7935:   display:block;
                   7936:   background: $sidebg;
                   7937:   border-bottom: solid 1px $lg_border_color;
                   7938:   list-style:none;
1.1020    raeburn  7939:   margin: -1px -10px 0 -10px;
1.911     bisitz   7940:   padding: 0;
1.693     droeschl 7941: }
                   7942: 
1.795     www      7943: ul.LC_TabContent li,
                   7944: ul.LC_TabContentBigger li {
1.911     bisitz   7945:   float:left;
1.741     harmsja  7946: }
1.795     www      7947: 
1.897     wenzelju 7948: ul#LC_secondary_menu li a {
1.911     bisitz   7949:   color: $fontmenu;
                   7950:   text-decoration: none;
1.693     droeschl 7951: }
1.795     www      7952: 
1.721     harmsja  7953: ul.LC_TabContent {
1.952     onken    7954:   min-height:20px;
1.721     harmsja  7955: }
1.795     www      7956: 
                   7957: ul.LC_TabContent li {
1.911     bisitz   7958:   vertical-align:middle;
1.959     onken    7959:   padding: 0 16px 0 10px;
1.911     bisitz   7960:   background-color:$tabbg;
                   7961:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7962:   border-left: solid 1px $font;
1.721     harmsja  7963: }
1.795     www      7964: 
1.847     tempelho 7965: ul.LC_TabContent .right {
1.911     bisitz   7966:   float:right;
1.847     tempelho 7967: }
                   7968: 
1.911     bisitz   7969: ul.LC_TabContent li a,
                   7970: ul.LC_TabContent li {
                   7971:   color:rgb(47,47,47);
                   7972:   text-decoration:none;
                   7973:   font-size:95%;
                   7974:   font-weight:bold;
1.952     onken    7975:   min-height:20px;
                   7976: }
                   7977: 
1.959     onken    7978: ul.LC_TabContent li a:hover,
                   7979: ul.LC_TabContent li a:focus {
1.952     onken    7980:   color: $button_hover;
1.959     onken    7981:   background:none;
                   7982:   outline:none;
1.952     onken    7983: }
                   7984: 
                   7985: ul.LC_TabContent li:hover {
                   7986:   color: $button_hover;
                   7987:   cursor:pointer;
1.721     harmsja  7988: }
1.795     www      7989: 
1.911     bisitz   7990: ul.LC_TabContent li.active {
1.952     onken    7991:   color: $font;
1.911     bisitz   7992:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7993:   border-bottom:solid 1px #FFFFFF;
                   7994:   cursor: default;
1.744     ehlerst  7995: }
1.795     www      7996: 
1.959     onken    7997: ul.LC_TabContent li.active a {
                   7998:   color:$font;
                   7999:   background:#FFFFFF;
                   8000:   outline: none;
                   8001: }
1.1047    raeburn  8002: 
                   8003: ul.LC_TabContent li.goback {
                   8004:   float: left;
                   8005:   border-left: none;
                   8006: }
                   8007: 
1.870     tempelho 8008: #maincoursedoc {
1.911     bisitz   8009:   clear:both;
1.870     tempelho 8010: }
                   8011: 
                   8012: ul.LC_TabContentBigger {
1.911     bisitz   8013:   display:block;
                   8014:   list-style:none;
                   8015:   padding: 0;
1.870     tempelho 8016: }
                   8017: 
1.795     www      8018: ul.LC_TabContentBigger li {
1.911     bisitz   8019:   vertical-align:bottom;
                   8020:   height: 30px;
                   8021:   font-size:110%;
                   8022:   font-weight:bold;
                   8023:   color: #737373;
1.841     tempelho 8024: }
                   8025: 
1.957     onken    8026: ul.LC_TabContentBigger li.active {
                   8027:   position: relative;
                   8028:   top: 1px;
                   8029: }
                   8030: 
1.870     tempelho 8031: ul.LC_TabContentBigger li a {
1.911     bisitz   8032:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8033:   height: 30px;
                   8034:   line-height: 30px;
                   8035:   text-align: center;
                   8036:   display: block;
                   8037:   text-decoration: none;
1.958     onken    8038:   outline: none;  
1.741     harmsja  8039: }
1.795     www      8040: 
1.870     tempelho 8041: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8042:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8043:   color:$font;
1.744     ehlerst  8044: }
1.795     www      8045: 
1.870     tempelho 8046: ul.LC_TabContentBigger li b {
1.911     bisitz   8047:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8048:   display: block;
                   8049:   float: left;
                   8050:   padding: 0 30px;
1.957     onken    8051:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8052: }
                   8053: 
1.956     onken    8054: ul.LC_TabContentBigger li:hover b {
                   8055:   color:$button_hover;
                   8056: }
                   8057: 
1.870     tempelho 8058: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8059:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8060:   color:$font;
1.957     onken    8061:   border: 0;
1.741     harmsja  8062: }
1.693     droeschl 8063: 
1.870     tempelho 8064: 
1.862     bisitz   8065: ul.LC_CourseBreadcrumbs {
                   8066:   background: $sidebg;
1.1020    raeburn  8067:   height: 2em;
1.862     bisitz   8068:   padding-left: 10px;
1.1020    raeburn  8069:   margin: 0;
1.862     bisitz   8070:   list-style-position: inside;
                   8071: }
                   8072: 
1.911     bisitz   8073: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8074: ol#LC_PathBreadcrumbs {
1.911     bisitz   8075:   padding-left: 10px;
                   8076:   margin: 0;
1.933     droeschl 8077:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8078: }
                   8079: 
1.911     bisitz   8080: ol#LC_MenuBreadcrumbs li,
                   8081: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8082: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8083:   display: inline;
1.933     droeschl 8084:   white-space: normal;  
1.693     droeschl 8085: }
                   8086: 
1.823     bisitz   8087: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8088: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8089:   text-decoration: none;
                   8090:   font-size:90%;
1.693     droeschl 8091: }
1.795     www      8092: 
1.969     droeschl 8093: ol#LC_MenuBreadcrumbs h1 {
                   8094:   display: inline;
                   8095:   font-size: 90%;
                   8096:   line-height: 2.5em;
                   8097:   margin: 0;
                   8098:   padding: 0;
                   8099: }
                   8100: 
1.795     www      8101: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8102:   text-decoration:none;
                   8103:   font-size:100%;
                   8104:   font-weight:bold;
1.693     droeschl 8105: }
1.795     www      8106: 
1.840     bisitz   8107: .LC_Box {
1.911     bisitz   8108:   border: solid 1px $lg_border_color;
                   8109:   padding: 0 10px 10px 10px;
1.746     neumanie 8110: }
1.795     www      8111: 
1.1020    raeburn  8112: .LC_DocsBox {
                   8113:   border: solid 1px $lg_border_color;
                   8114:   padding: 0 0 10px 10px;
                   8115: }
                   8116: 
1.795     www      8117: .LC_AboutMe_Image {
1.911     bisitz   8118:   float:left;
                   8119:   margin-right:10px;
1.747     neumanie 8120: }
1.795     www      8121: 
                   8122: .LC_Clear_AboutMe_Image {
1.911     bisitz   8123:   clear:left;
1.747     neumanie 8124: }
1.795     www      8125: 
1.721     harmsja  8126: dl.LC_ListStyleClean dt {
1.911     bisitz   8127:   padding-right: 5px;
                   8128:   display: table-header-group;
1.693     droeschl 8129: }
                   8130: 
1.721     harmsja  8131: dl.LC_ListStyleClean dd {
1.911     bisitz   8132:   display: table-row;
1.693     droeschl 8133: }
                   8134: 
1.721     harmsja  8135: .LC_ListStyleClean,
                   8136: .LC_ListStyleSimple,
                   8137: .LC_ListStyleNormal,
1.795     www      8138: .LC_ListStyleSpecial {
1.911     bisitz   8139:   /* display:block; */
                   8140:   list-style-position: inside;
                   8141:   list-style-type: none;
                   8142:   overflow: hidden;
                   8143:   padding: 0;
1.693     droeschl 8144: }
                   8145: 
1.721     harmsja  8146: .LC_ListStyleSimple li,
                   8147: .LC_ListStyleSimple dd,
                   8148: .LC_ListStyleNormal li,
                   8149: .LC_ListStyleNormal dd,
                   8150: .LC_ListStyleSpecial li,
1.795     www      8151: .LC_ListStyleSpecial dd {
1.911     bisitz   8152:   margin: 0;
                   8153:   padding: 5px 5px 5px 10px;
                   8154:   clear: both;
1.693     droeschl 8155: }
                   8156: 
1.721     harmsja  8157: .LC_ListStyleClean li,
                   8158: .LC_ListStyleClean dd {
1.911     bisitz   8159:   padding-top: 0;
                   8160:   padding-bottom: 0;
1.693     droeschl 8161: }
                   8162: 
1.721     harmsja  8163: .LC_ListStyleSimple dd,
1.795     www      8164: .LC_ListStyleSimple li {
1.911     bisitz   8165:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8166: }
                   8167: 
1.721     harmsja  8168: .LC_ListStyleSpecial li,
                   8169: .LC_ListStyleSpecial dd {
1.911     bisitz   8170:   list-style-type: none;
                   8171:   background-color: RGB(220, 220, 220);
                   8172:   margin-bottom: 4px;
1.693     droeschl 8173: }
                   8174: 
1.721     harmsja  8175: table.LC_SimpleTable {
1.911     bisitz   8176:   margin:5px;
                   8177:   border:solid 1px $lg_border_color;
1.795     www      8178: }
1.693     droeschl 8179: 
1.721     harmsja  8180: table.LC_SimpleTable tr {
1.911     bisitz   8181:   padding: 0;
                   8182:   border:solid 1px $lg_border_color;
1.693     droeschl 8183: }
1.795     www      8184: 
                   8185: table.LC_SimpleTable thead {
1.911     bisitz   8186:   background:rgb(220,220,220);
1.693     droeschl 8187: }
                   8188: 
1.721     harmsja  8189: div.LC_columnSection {
1.911     bisitz   8190:   display: block;
                   8191:   clear: both;
                   8192:   overflow: hidden;
                   8193:   margin: 0;
1.693     droeschl 8194: }
                   8195: 
1.721     harmsja  8196: div.LC_columnSection>* {
1.911     bisitz   8197:   float: left;
                   8198:   margin: 10px 20px 10px 0;
                   8199:   overflow:hidden;
1.693     droeschl 8200: }
1.721     harmsja  8201: 
1.795     www      8202: table em {
1.911     bisitz   8203:   font-weight: bold;
                   8204:   font-style: normal;
1.748     schulted 8205: }
1.795     www      8206: 
1.779     bisitz   8207: table.LC_tableBrowseRes,
1.795     www      8208: table.LC_tableOfContent {
1.911     bisitz   8209:   border:none;
                   8210:   border-spacing: 1px;
                   8211:   padding: 3px;
                   8212:   background-color: #FFFFFF;
                   8213:   font-size: 90%;
1.753     droeschl 8214: }
1.789     droeschl 8215: 
1.911     bisitz   8216: table.LC_tableOfContent {
                   8217:   border-collapse: collapse;
1.789     droeschl 8218: }
                   8219: 
1.771     droeschl 8220: table.LC_tableBrowseRes a,
1.768     schulted 8221: table.LC_tableOfContent a {
1.911     bisitz   8222:   background-color: transparent;
                   8223:   text-decoration: none;
1.753     droeschl 8224: }
                   8225: 
1.795     www      8226: table.LC_tableOfContent img {
1.911     bisitz   8227:   border: none;
                   8228:   height: 1.3em;
                   8229:   vertical-align: text-bottom;
                   8230:   margin-right: 0.3em;
1.753     droeschl 8231: }
1.757     schulted 8232: 
1.795     www      8233: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8234:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8235: }
                   8236: 
1.795     www      8237: a#LC_content_toolbar_everything {
1.911     bisitz   8238:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8239: }
                   8240: 
1.795     www      8241: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8242:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8243: }
                   8244: 
1.795     www      8245: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8246:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8247: }
                   8248: 
1.795     www      8249: a#LC_content_toolbar_changefolder {
1.911     bisitz   8250:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8251: }
                   8252: 
1.795     www      8253: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8254:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8255: }
                   8256: 
1.1043    raeburn  8257: a#LC_content_toolbar_edittoplevel {
                   8258:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8259: }
                   8260: 
1.795     www      8261: ul#LC_toolbar li a:hover {
1.911     bisitz   8262:   background-position: bottom center;
1.757     schulted 8263: }
                   8264: 
1.795     www      8265: ul#LC_toolbar {
1.911     bisitz   8266:   padding: 0;
                   8267:   margin: 2px;
                   8268:   list-style:none;
                   8269:   position:relative;
                   8270:   background-color:white;
1.1082    raeburn  8271:   overflow: auto;
1.757     schulted 8272: }
                   8273: 
1.795     www      8274: ul#LC_toolbar li {
1.911     bisitz   8275:   border:1px solid white;
                   8276:   padding: 0;
                   8277:   margin: 0;
                   8278:   float: left;
                   8279:   display:inline;
                   8280:   vertical-align:middle;
1.1082    raeburn  8281:   white-space: nowrap;
1.911     bisitz   8282: }
1.757     schulted 8283: 
1.783     amueller 8284: 
1.795     www      8285: a.LC_toolbarItem {
1.911     bisitz   8286:   display:block;
                   8287:   padding: 0;
                   8288:   margin: 0;
                   8289:   height: 32px;
                   8290:   width: 32px;
                   8291:   color:white;
                   8292:   border: none;
                   8293:   background-repeat:no-repeat;
                   8294:   background-color:transparent;
1.757     schulted 8295: }
                   8296: 
1.915     droeschl 8297: ul.LC_funclist {
                   8298:     margin: 0;
                   8299:     padding: 0.5em 1em 0.5em 0;
                   8300: }
                   8301: 
1.933     droeschl 8302: ul.LC_funclist > li:first-child {
                   8303:     font-weight:bold; 
                   8304:     margin-left:0.8em;
                   8305: }
                   8306: 
1.915     droeschl 8307: ul.LC_funclist + ul.LC_funclist {
                   8308:     /* 
                   8309:        left border as a seperator if we have more than
                   8310:        one list 
                   8311:     */
                   8312:     border-left: 1px solid $sidebg;
                   8313:     /* 
                   8314:        this hides the left border behind the border of the 
                   8315:        outer box if element is wrapped to the next 'line' 
                   8316:     */
                   8317:     margin-left: -1px;
                   8318: }
                   8319: 
1.843     bisitz   8320: ul.LC_funclist li {
1.915     droeschl 8321:   display: inline;
1.782     bisitz   8322:   white-space: nowrap;
1.915     droeschl 8323:   margin: 0 0 0 25px;
                   8324:   line-height: 150%;
1.782     bisitz   8325: }
                   8326: 
1.974     wenzelju 8327: .LC_hidden {
                   8328:   display: none;
                   8329: }
                   8330: 
1.1030    www      8331: .LCmodal-overlay {
                   8332: 		position:fixed;
                   8333: 		top:0;
                   8334: 		right:0;
                   8335: 		bottom:0;
                   8336: 		left:0;
                   8337: 		height:100%;
                   8338: 		width:100%;
                   8339: 		margin:0;
                   8340: 		padding:0;
                   8341: 		background:#999;
                   8342: 		opacity:.75;
                   8343: 		filter: alpha(opacity=75);
                   8344: 		-moz-opacity: 0.75;
                   8345: 		z-index:101;
                   8346: }
                   8347: 
                   8348: * html .LCmodal-overlay {   
                   8349: 		position: absolute;
                   8350: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8351: }
                   8352: 
                   8353: .LCmodal-window {
                   8354: 		position:fixed;
                   8355: 		top:50%;
                   8356: 		left:50%;
                   8357: 		margin:0;
                   8358: 		padding:0;
                   8359: 		z-index:102;
                   8360: 	}
                   8361: 
                   8362: * html .LCmodal-window {
                   8363: 		position:absolute;
                   8364: }
                   8365: 
                   8366: .LCclose-window {
                   8367: 		position:absolute;
                   8368: 		width:32px;
                   8369: 		height:32px;
                   8370: 		right:8px;
                   8371: 		top:8px;
                   8372: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8373: 		text-indent:-99999px;
                   8374: 		overflow:hidden;
                   8375: 		cursor:pointer;
                   8376: }
                   8377: 
1.1335    raeburn  8378: pre.LC_wordwrap {
                   8379:   white-space: pre-wrap;
                   8380:   white-space: -moz-pre-wrap;
                   8381:   white-space: -pre-wrap;
                   8382:   white-space: -o-pre-wrap;
                   8383:   word-wrap: break-word;
                   8384: }
                   8385: 
1.1100    raeburn  8386: /*
1.1231    damieng  8387:   styles used for response display
                   8388: */
                   8389: div.LC_radiofoil, div.LC_rankfoil {
                   8390:   margin: .5em 0em .5em 0em;
                   8391: }
                   8392: table.LC_itemgroup {
                   8393:   margin-top: 1em;
                   8394: }
                   8395: 
                   8396: /*
1.1100    raeburn  8397:   styles used by TTH when "Default set of options to pass to tth/m
                   8398:   when converting TeX" in course settings has been set
                   8399: 
                   8400:   option passed: -t
                   8401: 
                   8402: */
                   8403: 
                   8404: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8405: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8406: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8407: td div.norm {line-height:normal;}
                   8408: 
                   8409: /*
                   8410:   option passed -y3
                   8411: */
                   8412: 
                   8413: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8414: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8415: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8416: 
1.1230    damieng  8417: /*
                   8418:   sections with roles, for content only
                   8419: */
                   8420: section[class^="role-"] {
                   8421:   padding-left: 10px;
                   8422:   padding-right: 5px;
                   8423:   margin-top: 8px;
                   8424:   margin-bottom: 8px;
                   8425:   border: 1px solid #2A4;
                   8426:   border-radius: 5px;
                   8427:   box-shadow: 0px 1px 1px #BBB;
                   8428: }
                   8429: section[class^="role-"]>h1 {
                   8430:   position: relative;
                   8431:   margin: 0px;
                   8432:   padding-top: 10px;
                   8433:   padding-left: 40px;
                   8434: }
                   8435: section[class^="role-"]>h1:before {
                   8436:   position: absolute;
                   8437:   left: -5px;
                   8438:   top: 5px;
                   8439: }
                   8440: section.role-activity>h1:before {
                   8441:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8442: }
                   8443: section.role-advice>h1:before {
                   8444:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8445: }
                   8446: section.role-bibliography>h1:before {
                   8447:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8448: }
                   8449: section.role-citation>h1:before {
                   8450:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8451: }
                   8452: section.role-conclusion>h1:before {
                   8453:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8454: }
                   8455: section.role-definition>h1:before {
                   8456:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8457: }
                   8458: section.role-demonstration>h1:before {
                   8459:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8460: }
                   8461: section.role-example>h1:before {
                   8462:   content:url('/adm/daxe/images/section_icons/example.png');
                   8463: }
                   8464: section.role-explanation>h1:before {
                   8465:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8466: }
                   8467: section.role-introduction>h1:before {
                   8468:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8469: }
                   8470: section.role-method>h1:before {
                   8471:   content:url('/adm/daxe/images/section_icons/method.png');
                   8472: }
                   8473: section.role-more_information>h1:before {
                   8474:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8475: }
                   8476: section.role-objectives>h1:before {
                   8477:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8478: }
                   8479: section.role-prerequisites>h1:before {
                   8480:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8481: }
                   8482: section.role-remark>h1:before {
                   8483:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8484: }
                   8485: section.role-reminder>h1:before {
                   8486:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8487: }
                   8488: section.role-summary>h1:before {
                   8489:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8490: }
                   8491: section.role-syntax>h1:before {
                   8492:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8493: }
                   8494: section.role-warning>h1:before {
                   8495:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8496: }
                   8497: 
1.1269    raeburn  8498: #LC_minitab_header {
                   8499:   float:left;
                   8500:   width:100%;
                   8501:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8502:   font-size:93%;
                   8503:   line-height:normal;
                   8504:   margin: 0.5em 0 0.5em 0;
                   8505: }
                   8506: #LC_minitab_header ul {
                   8507:   margin:0;
                   8508:   padding:10px 10px 0;
                   8509:   list-style:none;
                   8510: }
                   8511: #LC_minitab_header li {
                   8512:   float:left;
                   8513:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8514:   margin:0;
                   8515:   padding:0 0 0 9px;
                   8516: }
                   8517: #LC_minitab_header a {
                   8518:   display:block;
                   8519:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8520:   padding:5px 15px 4px 6px;
                   8521: }
                   8522: #LC_minitab_header #LC_current_minitab {
                   8523:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8524: }
                   8525: #LC_minitab_header #LC_current_minitab a {
                   8526:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8527:   padding-bottom:5px;
                   8528: }
                   8529: 
                   8530: 
1.343     albertel 8531: END
                   8532: }
                   8533: 
1.306     albertel 8534: =pod
                   8535: 
                   8536: =item * &headtag()
                   8537: 
                   8538: Returns a uniform footer for LON-CAPA web pages.
                   8539: 
1.307     albertel 8540: Inputs: $title - optional title for the head
                   8541:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8542:         $args - optional arguments
1.319     albertel 8543:             force_register - if is true call registerurl so the remote is 
                   8544:                              informed
1.415     albertel 8545:             redirect       -> array ref of
                   8546:                                    1- seconds before redirect occurs
                   8547:                                    2- url to redirect to
                   8548:                                    3- whether the side effect should occur
1.315     albertel 8549:                            (side effect of setting 
                   8550:                                $env{'internal.head.redirect'} to the url 
                   8551:                                redirected too)
1.352     albertel 8552:             domain         -> force to color decorate a page for a specific
                   8553:                                domain
                   8554:             function       -> force usage of a specific rolish color scheme
                   8555:             bgcolor        -> override the default page bgcolor
1.460     albertel 8556:             no_auto_mt_title
                   8557:                            -> prevent &mt()ing the title arg
1.464     albertel 8558: 
1.306     albertel 8559: =cut
                   8560: 
                   8561: sub headtag {
1.313     albertel 8562:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8563:     
1.363     albertel 8564:     my $function = $args->{'function'} || &get_users_function();
                   8565:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8566:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8567:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8568:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8569: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8570: 		   #time(),
1.418     albertel 8571: 		   $env{'environment.color.timestamp'},
1.363     albertel 8572: 		   $function,$domain,$bgcolor);
                   8573: 
1.369     www      8574:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8575: 
1.308     albertel 8576:     my $result =
                   8577: 	'<head>'.
1.1160    raeburn  8578: 	&font_settings($args);
1.319     albertel 8579: 
1.1188    raeburn  8580:     my $inhibitprint;
                   8581:     if ($args->{'print_suppress'}) {
                   8582:         $inhibitprint = &print_suppression();
                   8583:     }
1.1064    raeburn  8584: 
1.461     albertel 8585:     if (!$args->{'frameset'}) {
                   8586: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8587:     }
1.962     droeschl 8588:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8589:         $result .= Apache::lonxml::display_title();
1.319     albertel 8590:     }
1.436     albertel 8591:     if (!$args->{'no_nav_bar'} 
                   8592: 	&& !$args->{'only_body'}
                   8593: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8594: 	$result .= &help_menu_js($httphost);
1.1032    www      8595:         $result.=&modal_window();
1.1038    www      8596:         $result.=&togglebox_script();
1.1034    www      8597:         $result.=&wishlist_window();
1.1041    www      8598:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8599:     } else {
                   8600:         if ($args->{'add_modal'}) {
                   8601:            $result.=&modal_window();
                   8602:         }
                   8603:         if ($args->{'add_wishlist'}) {
                   8604:            $result.=&wishlist_window();
                   8605:         }
1.1038    www      8606:         if ($args->{'add_togglebox'}) {
                   8607:            $result.=&togglebox_script();
                   8608:         }
1.1041    www      8609:         if ($args->{'add_progressbar'}) {
                   8610:            $result.=&LCprogressbarUpdate_script();
                   8611:         }
1.436     albertel 8612:     }
1.314     albertel 8613:     if (ref($args->{'redirect'})) {
1.414     albertel 8614: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8615: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8616: 	if (!$inhibit_continue) {
                   8617: 	    $env{'internal.head.redirect'} = $url;
                   8618: 	}
1.313     albertel 8619: 	$result.=<<ADDMETA
                   8620: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8621: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8622: ADDMETA
1.1210    raeburn  8623:     } else {
                   8624:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8625:             my $requrl = $env{'request.uri'};
                   8626:             if ($requrl eq '') {
                   8627:                 $requrl = $ENV{'REQUEST_URI'};
                   8628:                 $requrl =~ s/\?.+$//;
                   8629:             }
                   8630:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8631:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8632:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8633:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8634:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8635:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8636:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8637:                     my ($offload,$offloadoth);
1.1210    raeburn  8638:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8639:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8640:                             $offload = 1;
1.1353    raeburn  8641:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8642:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8643:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8644:                                     $offloadoth = 1;
                   8645:                                     $dom_in_use = $env{'user.domain'};
                   8646:                                 }
                   8647:                             }
1.1340    raeburn  8648:                         }
                   8649:                     }
                   8650:                     unless ($offload) {
                   8651:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8652:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8653:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8654:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8655:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8656:                                         $offload = 1;
1.1352    raeburn  8657:                                         $offloadoth = 1;
1.1340    raeburn  8658:                                         $dom_in_use = $env{'user.domain'};
                   8659:                                     }
1.1210    raeburn  8660:                                 }
1.1340    raeburn  8661:                             }
                   8662:                         }
                   8663:                     }
                   8664:                     if ($offload) {
1.1358    raeburn  8665:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8666:                         if (($newserver eq '') && ($offloadoth)) {
                   8667:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8668:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8669:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8670:                             }
                   8671:                         }
1.1340    raeburn  8672:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8673:                             my $numsec = 5;
                   8674:                             my $timeout = $numsec * 1000;
                   8675:                             my ($newurl,$locknum,%locks,$msg);
                   8676:                             if ($env{'request.role.adv'}) {
                   8677:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8678:                             }
                   8679:                             my $disable_submit = 0;
                   8680:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8681:                                 $disable_submit = 1;
                   8682:                             }
                   8683:                             if ($locknum) {
                   8684:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8685:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8686:                                        join(", ",sort(values(%locks)))."\n";
                   8687:                                 if (&show_course()) {
                   8688:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8689:                                 } else {
                   8690:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8691:                                 }
1.1340    raeburn  8692:                             } else {
                   8693:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8694:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8695:                                 }
                   8696:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8697:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8698:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8699:                                     $newurl .= '&role='.$env{'request.role'};
                   8700:                                 }
                   8701:                                 if ($env{'request.symb'}) {
                   8702:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8703:                                     if ($shownsymb =~ m{^/enc/}) {
                   8704:                                         my $reqdmajor = 2;
                   8705:                                         my $reqdminor = 11;
                   8706:                                         my $reqdsubminor = 3;
                   8707:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8708:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8709:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8710:                                         if (($major eq '' && $minor eq '') ||
                   8711:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8712:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8713:                                              ($reqdsubminor > $subminor))))) {
                   8714:                                             undef($shownsymb);
                   8715:                                         }
1.1210    raeburn  8716:                                     }
1.1340    raeburn  8717:                                     if ($shownsymb) {
                   8718:                                         &js_escape(\$shownsymb);
                   8719:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8720:                                     }
1.1340    raeburn  8721:                                 } else {
                   8722:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8723:                                     &js_escape(\$shownurl);
                   8724:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  8725:                                 }
1.1340    raeburn  8726:                             }
                   8727:                             &js_escape(\$msg);
                   8728:                             $result.=<<OFFLOAD
1.1210    raeburn  8729: <meta http-equiv="pragma" content="no-cache" />
                   8730: <script type="text/javascript">
1.1215    raeburn  8731: // <![CDATA[
1.1210    raeburn  8732: function LC_Offload_Now() {
                   8733:     var dest = "$newurl";
                   8734:     if (dest != '') {
                   8735:         window.location.href="$newurl";
                   8736:     }
                   8737: }
1.1214    raeburn  8738: \$(document).ready(function () {
                   8739:     window.alert('$msg');
                   8740:     if ($disable_submit) {
1.1210    raeburn  8741:         \$(".LC_hwk_submit").prop("disabled", true);
                   8742:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8743:     }
                   8744:     setTimeout('LC_Offload_Now()', $timeout);
                   8745: });
1.1215    raeburn  8746: // ]]>
1.1210    raeburn  8747: </script>
                   8748: OFFLOAD
                   8749:                         }
                   8750:                     }
                   8751:                 }
                   8752:             }
                   8753:         }
1.313     albertel 8754:     }
1.306     albertel 8755:     if (!defined($title)) {
                   8756: 	$title = 'The LearningOnline Network with CAPA';
                   8757:     }
1.460     albertel 8758:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8759:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8760: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8761:     if (!$args->{'frameset'}) {
                   8762:         $result .= ' /';
                   8763:     }
                   8764:     $result .= '>' 
1.1064    raeburn  8765:         .$inhibitprint
1.414     albertel 8766: 	.$head_extra;
1.1242    raeburn  8767:     my $clientmobile;
                   8768:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8769:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8770:     } else {
                   8771:         $clientmobile = $env{'browser.mobile'};
                   8772:     }
                   8773:     if ($clientmobile) {
1.1137    raeburn  8774:         $result .= '
                   8775: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8776: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8777:     }
1.1278    raeburn  8778:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8779:     return $result.'</head>';
1.306     albertel 8780: }
                   8781: 
                   8782: =pod
                   8783: 
1.340     albertel 8784: =item * &font_settings()
                   8785: 
                   8786: Returns neccessary <meta> to set the proper encoding
                   8787: 
1.1160    raeburn  8788: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8789: 
                   8790: =cut
                   8791: 
                   8792: sub font_settings {
1.1160    raeburn  8793:     my ($args) = @_;
1.340     albertel 8794:     my $headerstring='';
1.1160    raeburn  8795:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8796:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8797:         $headerstring.=
                   8798:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8799:         if (!$args->{'frameset'}) {
                   8800: 	    $headerstring.= ' /';
                   8801:         }
                   8802: 	$headerstring .= '>'."\n";
1.340     albertel 8803:     }
                   8804:     return $headerstring;
                   8805: }
                   8806: 
1.341     albertel 8807: =pod
                   8808: 
1.1064    raeburn  8809: =item * &print_suppression()
                   8810: 
                   8811: In course context returns css which causes the body to be blank when media="print",
                   8812: if printout generation is unavailable for the current resource.
                   8813: 
                   8814: This could be because:
                   8815: 
                   8816: (a) printstartdate is in the future
                   8817: 
                   8818: (b) printenddate is in the past
                   8819: 
                   8820: (c) there is an active exam block with "printout"
                   8821: functionality blocked
                   8822: 
                   8823: Users with pav, pfo or evb privileges are exempt.
                   8824: 
                   8825: Inputs: none
                   8826: 
                   8827: =cut
                   8828: 
                   8829: 
                   8830: sub print_suppression {
                   8831:     my $noprint;
                   8832:     if ($env{'request.course.id'}) {
                   8833:         my $scope = $env{'request.course.id'};
                   8834:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8835:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8836:             return;
                   8837:         }
                   8838:         if ($env{'request.course.sec'} ne '') {
                   8839:             $scope .= "/$env{'request.course.sec'}";
                   8840:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8841:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8842:                 return;
1.1064    raeburn  8843:             }
                   8844:         }
                   8845:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8846:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8847:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8848:         if ($blocked) {
                   8849:             my $checkrole = "cm./$cdom/$cnum";
                   8850:             if ($env{'request.course.sec'} ne '') {
                   8851:                 $checkrole .= "/$env{'request.course.sec'}";
                   8852:             }
                   8853:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8854:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8855:                 $noprint = 1;
                   8856:             }
                   8857:         }
                   8858:         unless ($noprint) {
                   8859:             my $symb = &Apache::lonnet::symbread();
                   8860:             if ($symb ne '') {
                   8861:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8862:                 if (ref($navmap)) {
                   8863:                     my $res = $navmap->getBySymb($symb);
                   8864:                     if (ref($res)) {
                   8865:                         if (!$res->resprintable()) {
                   8866:                             $noprint = 1;
                   8867:                         }
                   8868:                     }
                   8869:                 }
                   8870:             }
                   8871:         }
                   8872:         if ($noprint) {
                   8873:             return <<"ENDSTYLE";
                   8874: <style type="text/css" media="print">
                   8875:     body { display:none }
                   8876: </style>
                   8877: ENDSTYLE
                   8878:         }
                   8879:     }
                   8880:     return;
                   8881: }
                   8882: 
                   8883: =pod
                   8884: 
1.341     albertel 8885: =item * &xml_begin()
                   8886: 
                   8887: Returns the needed doctype and <html>
                   8888: 
                   8889: Inputs: none
                   8890: 
                   8891: =cut
                   8892: 
                   8893: sub xml_begin {
1.1168    raeburn  8894:     my ($is_frameset) = @_;
1.341     albertel 8895:     my $output='';
                   8896: 
                   8897:     if ($env{'browser.mathml'}) {
                   8898: 	$output='<?xml version="1.0"?>'
                   8899:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8900: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8901:             
                   8902: #	    .'<!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">] >'
                   8903: 	    .'<!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">'
                   8904:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8905: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8906:     } elsif ($is_frameset) {
                   8907:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8908:                 '<html>'."\n";
1.341     albertel 8909:     } else {
1.1168    raeburn  8910: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8911:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8912:     }
                   8913:     return $output;
                   8914: }
1.340     albertel 8915: 
                   8916: =pod
                   8917: 
1.306     albertel 8918: =item * &start_page()
                   8919: 
                   8920: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8921: 
1.648     raeburn  8922: Inputs:
                   8923: 
                   8924: =over 4
                   8925: 
                   8926: $title - optional title for the page
                   8927: 
                   8928: $head_extra - optional extra HTML to incude inside the <head>
                   8929: 
                   8930: $args - additional optional args supported are:
                   8931: 
                   8932: =over 8
                   8933: 
                   8934:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8935:                                     arg on
1.814     bisitz   8936:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8937:              add_entries    -> additional attributes to add to the  <body>
                   8938:              domain         -> force to color decorate a page for a 
1.317     albertel 8939:                                     specific domain
1.648     raeburn  8940:              function       -> force usage of a specific rolish color
1.317     albertel 8941:                                     scheme
1.648     raeburn  8942:              redirect       -> see &headtag()
                   8943:              bgcolor        -> override the default page bg color
                   8944:              js_ready       -> return a string ready for being used in 
1.317     albertel 8945:                                     a javascript writeln
1.648     raeburn  8946:              html_encode    -> return a string ready for being used in 
1.320     albertel 8947:                                     a html attribute
1.648     raeburn  8948:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8949:                                     $forcereg arg
1.648     raeburn  8950:              frameset       -> if true will start with a <frameset>
1.330     albertel 8951:                                     rather than <body>
1.648     raeburn  8952:              skip_phases    -> hash ref of 
1.338     albertel 8953:                                     head -> skip the <html><head> generation
                   8954:                                     body -> skip all <body> generation
1.648     raeburn  8955:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8956:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8957:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8958:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8959:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8960:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8961:                                specific group
                   8962:              use_absolute   -> for request for external resource or syllabus, this
                   8963:                                will contain https://<hostname> if server uses
                   8964:                                https (as per hosts.tab), but request is for http
                   8965:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8966: 
1.648     raeburn  8967: =back
1.460     albertel 8968: 
1.648     raeburn  8969: =back
1.562     albertel 8970: 
1.306     albertel 8971: =cut
                   8972: 
                   8973: sub start_page {
1.309     albertel 8974:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8975:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8976: 
1.315     albertel 8977:     $env{'internal.start_page'}++;
1.1359    raeburn  8978:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8979: 
1.338     albertel 8980:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8981:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8982:     }
1.1316    raeburn  8983: 
                   8984:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  8985:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8986:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8987:                 $args->{'no_primary_menu'} = 1;
                   8988:             }
                   8989:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8990:                 $args->{'no_inline_menu'} = 1;
                   8991:             }
                   8992:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8993:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8994:             }
                   8995:         } else {
                   8996:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8997:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8998:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8999:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9000:                     $args->{'no_primary_menu'} = 1;
                   9001:                 }
                   9002:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9003:                     $args->{'no_inline_menu'} = 1;
                   9004:                 }
                   9005:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9006:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9007:                 }
                   9008:             }
                   9009:         }
1.1316    raeburn  9010:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9011:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9012:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9013:     } elsif ($env{'request.course.id'}) {
                   9014:         my $expiretime=600;
                   9015:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9016:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9017:         }
                   9018:         my ($deeplinkmenu,$menuref);
                   9019:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9020:         if ($menucoll) {
                   9021:             if (ref($menuref) eq 'HASH') {
                   9022:                 %menu = %{$menuref};
                   9023:             }
                   9024:             if ($menu{'top'} eq 'n') {
                   9025:                 $args->{'no_primary_menu'} = 1;
                   9026:             }
                   9027:             if ($menu{'inline'} eq 'n') {
                   9028:                 unless (&Apache::lonnet::allowed('opa')) {
                   9029:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9030:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9031:                     my $crstype = &course_type();
                   9032:                     my $now = time;
                   9033:                     my $ccrole;
                   9034:                     if ($crstype eq 'Community') {
                   9035:                         $ccrole = 'co';
                   9036:                     } else {
                   9037:                         $ccrole = 'cc';
                   9038:                     }
                   9039:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9040:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9041:                         if ((($start) && ($start<0)) ||
                   9042:                             (($end) && ($end<$now))  ||
                   9043:                             (($start) && ($now<$start))) {
                   9044:                             $args->{'no_inline_menu'} = 1;
                   9045:                         }
                   9046:                     } else {
                   9047:                         $args->{'no_inline_menu'} = 1;
                   9048:                     }
                   9049:                 }
                   9050:             }
                   9051:         }
1.1316    raeburn  9052:     }
1.1359    raeburn  9053: 
1.338     albertel 9054:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9055: 	if ($args->{'frameset'}) {
                   9056: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9057: 						$args->{'add_entries'});
                   9058: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9059:         } else {
                   9060:             $result .=
                   9061:                 &bodytag($title, 
                   9062:                          $args->{'function'},       $args->{'add_entries'},
                   9063:                          $args->{'only_body'},      $args->{'domain'},
                   9064:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9065:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9066:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9067:         }
1.330     albertel 9068:     }
1.338     albertel 9069: 
1.315     albertel 9070:     if ($args->{'js_ready'}) {
1.713     kaisler  9071: 		$result = &js_ready($result);
1.315     albertel 9072:     }
1.320     albertel 9073:     if ($args->{'html_encode'}) {
1.713     kaisler  9074: 		$result = &html_encode($result);
                   9075:     }
                   9076: 
1.813     bisitz   9077:     # Preparation for new and consistent functionlist at top of screen
                   9078:     # if ($args->{'functionlist'}) {
                   9079:     #            $result .= &build_functionlist();
                   9080:     #}
                   9081: 
1.964     droeschl 9082:     # Don't add anything more if only_body wanted or in const space
                   9083:     return $result if    $args->{'only_body'} 
                   9084:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9085: 
                   9086:     #Breadcrumbs
1.758     kaisler  9087:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9088: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9089: 		#if any br links exists, add them to the breadcrumbs
                   9090: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9091: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9092: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9093: 			}
                   9094: 		}
1.1096    raeburn  9095:                 # if @advtools array contains items add then to the breadcrumbs
                   9096:                 if (@advtools > 0) {
                   9097:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9098:                 }
1.1272    raeburn  9099:                 my $menulink;
                   9100:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9101:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9102:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9103:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9104:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9105:                      (!$env{'request.role.adv'}))) {
                   9106:                     $menulink = 0;
                   9107:                 } else {
                   9108:                     undef($menulink);
                   9109:                 }
1.758     kaisler  9110: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9111: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9112: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9113:                 } else {
1.1272    raeburn  9114: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9115: 		}
1.320     albertel 9116:     }
1.315     albertel 9117:     return $result;
1.306     albertel 9118: }
                   9119: 
                   9120: sub end_page {
1.315     albertel 9121:     my ($args) = @_;
                   9122:     $env{'internal.end_page'}++;
1.330     albertel 9123:     my $result;
1.335     albertel 9124:     if ($args->{'discussion'}) {
                   9125: 	my ($target,$parser);
                   9126: 	if (ref($args->{'discussion'})) {
                   9127: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9128: 				$args->{'discussion'}{'parser'});
                   9129: 	}
                   9130: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9131:     }
1.330     albertel 9132:     if ($args->{'frameset'}) {
                   9133: 	$result .= '</frameset>';
                   9134:     } else {
1.635     raeburn  9135: 	$result .= &endbodytag($args);
1.330     albertel 9136:     }
1.1080    raeburn  9137:     unless ($args->{'notbody'}) {
                   9138:         $result .= "\n</html>";
                   9139:     }
1.330     albertel 9140: 
1.315     albertel 9141:     if ($args->{'js_ready'}) {
1.317     albertel 9142: 	$result = &js_ready($result);
1.315     albertel 9143:     }
1.335     albertel 9144: 
1.320     albertel 9145:     if ($args->{'html_encode'}) {
                   9146: 	$result = &html_encode($result);
                   9147:     }
1.335     albertel 9148: 
1.315     albertel 9149:     return $result;
                   9150: }
                   9151: 
1.1359    raeburn  9152: sub menucoll_in_effect {
                   9153:     my ($menucoll,$deeplinkmenu,%menu);
                   9154:     if ($env{'request.course.id'}) {
                   9155:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9156:         if ($env{'request.deeplink.login'}) {
                   9157:             my ($deeplink_symb,$deeplink);
                   9158:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9159:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9160:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9161:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9162:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9163:                     if (ref($navmap)) {
                   9164:                         $deeplink = $navmap->get_mapparam(undef,
                   9165:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9166:                                                           '0.deeplink');
                   9167:                     }
                   9168:                 } else {
                   9169:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink');
                   9170:                 }
                   9171:             } else {
                   9172:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9173:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9174:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9175:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9176:                     if (ref($navmap)) {
                   9177:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9178:                     }
                   9179:                 } else {
                   9180:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9181:                 }
                   9182:             }
1.1359    raeburn  9183:             if ($deeplink ne '') {
1.1363    raeburn  9184:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
1.1359    raeburn  9185:                 if ($display =~ /^\d+$/) {
                   9186:                     $deeplinkmenu = 1;
                   9187:                     $menucoll = $display;
                   9188:                 }
                   9189:             }
                   9190:         }
                   9191:         if ($menucoll) {
                   9192:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9193:         }
                   9194:     }
                   9195:     return ($menucoll,$deeplinkmenu,\%menu);
                   9196: }
                   9197: 
1.1362    raeburn  9198: sub deeplink_login_symb {
                   9199:     my ($cnum,$cdom) = @_;
                   9200:     my $login_symb;
                   9201:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9202:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9203:     }
                   9204:     return $login_symb;
                   9205: }
                   9206: 
                   9207: sub symb_from_tinyurl {
                   9208:     my ($url,$cnum,$cdom) = @_;
                   9209:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9210:         my $key = $1;
                   9211:         my ($tinyurl,$login);
                   9212:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9213:         if (defined($cached)) {
                   9214:             $tinyurl = $result;
                   9215:         } else {
                   9216:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9217:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9218:             if ($currtiny{$key} ne '') {
                   9219:                 $tinyurl = $currtiny{$key};
                   9220:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9221:             }
1.1364    raeburn  9222:         }
                   9223:         if ($tinyurl ne '') {
                   9224:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9225:             if (wantarray) {
                   9226:                 return ($cnumreq,$symb);
                   9227:             } elsif ($cnumreq eq $cnum) {
                   9228:                 return $symb;
1.1362    raeburn  9229:             }
                   9230:         }
                   9231:     }
1.1364    raeburn  9232:     if (wantarray) {
                   9233:         return ();
                   9234:     } else {
                   9235:         return;
                   9236:     }
1.1362    raeburn  9237: }
                   9238: 
1.1034    www      9239: sub wishlist_window {
                   9240:     return(<<'ENDWISHLIST');
1.1046    raeburn  9241: <script type="text/javascript">
1.1034    www      9242: // <![CDATA[
                   9243: // <!-- BEGIN LON-CAPA Internal
                   9244: function set_wishlistlink(title, path) {
                   9245:     if (!title) {
                   9246:         title = document.title;
                   9247:         title = title.replace(/^LON-CAPA /,'');
                   9248:     }
1.1175    raeburn  9249:     title = encodeURIComponent(title);
1.1203    raeburn  9250:     title = title.replace("'","\\\'");
1.1034    www      9251:     if (!path) {
                   9252:         path = location.pathname;
                   9253:     }
1.1175    raeburn  9254:     path = encodeURIComponent(path);
1.1203    raeburn  9255:     path = path.replace("'","\\\'");
1.1034    www      9256:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9257:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9258: }
                   9259: // END LON-CAPA Internal -->
                   9260: // ]]>
                   9261: </script>
                   9262: ENDWISHLIST
                   9263: }
                   9264: 
1.1030    www      9265: sub modal_window {
                   9266:     return(<<'ENDMODAL');
1.1046    raeburn  9267: <script type="text/javascript">
1.1030    www      9268: // <![CDATA[
                   9269: // <!-- BEGIN LON-CAPA Internal
                   9270: var modalWindow = {
                   9271: 	parent:"body",
                   9272: 	windowId:null,
                   9273: 	content:null,
                   9274: 	width:null,
                   9275: 	height:null,
                   9276: 	close:function()
                   9277: 	{
                   9278: 	        $(".LCmodal-window").remove();
                   9279: 	        $(".LCmodal-overlay").remove();
                   9280: 	},
                   9281: 	open:function()
                   9282: 	{
                   9283: 		var modal = "";
                   9284: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9285: 		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;\">";
                   9286: 		modal += this.content;
                   9287: 		modal += "</div>";	
                   9288: 
                   9289: 		$(this.parent).append(modal);
                   9290: 
                   9291: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9292: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9293: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9294: 	}
                   9295: };
1.1140    raeburn  9296: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9297: 	{
1.1266    raeburn  9298:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9299: 		modalWindow.windowId = "myModal";
                   9300: 		modalWindow.width = width;
                   9301: 		modalWindow.height = height;
1.1196    raeburn  9302: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9303: 		modalWindow.open();
1.1208    raeburn  9304: 	};
1.1030    www      9305: // END LON-CAPA Internal -->
                   9306: // ]]>
                   9307: </script>
                   9308: ENDMODAL
                   9309: }
                   9310: 
                   9311: sub modal_link {
1.1140    raeburn  9312:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9313:     unless ($width) { $width=480; }
                   9314:     unless ($height) { $height=400; }
1.1031    www      9315:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9316:     unless ($transparency) { $transparency='true'; }
                   9317: 
1.1074    raeburn  9318:     my $target_attr;
                   9319:     if (defined($target)) {
                   9320:         $target_attr = 'target="'.$target.'"';
                   9321:     }
                   9322:     return <<"ENDLINK";
1.1336    raeburn  9323: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9324: ENDLINK
1.1030    www      9325: }
                   9326: 
1.1032    www      9327: sub modal_adhoc_script {
1.1365    raeburn  9328:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9329:     my $mathjax;
                   9330:     if ($possmathjax) {
                   9331:         $mathjax = <<'ENDJAX';
                   9332:                if (typeof MathJax == 'object') {
                   9333:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9334:                }
                   9335: ENDJAX
                   9336:     }
1.1032    www      9337:     return (<<ENDADHOC);
1.1046    raeburn  9338: <script type="text/javascript">
1.1032    www      9339: // <![CDATA[
                   9340:         var $funcname = function()
                   9341:         {
                   9342:                 modalWindow.windowId = "myModal";
                   9343:                 modalWindow.width = $width;
                   9344:                 modalWindow.height = $height;
                   9345:                 modalWindow.content = '$content';
                   9346:                 modalWindow.open();
1.1365    raeburn  9347:                 $mathjax
1.1032    www      9348:         };  
                   9349: // ]]>
                   9350: </script>
                   9351: ENDADHOC
                   9352: }
                   9353: 
1.1041    www      9354: sub modal_adhoc_inner {
1.1365    raeburn  9355:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9356:     my $innerwidth=$width-20;
                   9357:     $content=&js_ready(
1.1140    raeburn  9358:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9359:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9360:                  $content.
1.1041    www      9361:                  &end_scrollbox().
1.1140    raeburn  9362:                  &end_page()
1.1041    www      9363:              );
1.1365    raeburn  9364:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9365: }
                   9366: 
                   9367: sub modal_adhoc_window {
1.1365    raeburn  9368:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9369:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9370:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9371: }
                   9372: 
                   9373: sub modal_adhoc_launch {
                   9374:     my ($funcname,$width,$height,$content)=@_;
                   9375:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9376: <script type="text/javascript">
                   9377: // <![CDATA[
                   9378: $funcname();
                   9379: // ]]>
                   9380: </script>
                   9381: ENDLAUNCH
                   9382: }
                   9383: 
                   9384: sub modal_adhoc_close {
                   9385:     return (<<ENDCLOSE);
                   9386: <script type="text/javascript">
                   9387: // <![CDATA[
                   9388: modalWindow.close();
                   9389: // ]]>
                   9390: </script>
                   9391: ENDCLOSE
                   9392: }
                   9393: 
1.1038    www      9394: sub togglebox_script {
                   9395:    return(<<ENDTOGGLE);
                   9396: <script type="text/javascript"> 
                   9397: // <![CDATA[
                   9398: function LCtoggleDisplay(id,hidetext,showtext) {
                   9399:    link = document.getElementById(id + "link").childNodes[0];
                   9400:    with (document.getElementById(id).style) {
                   9401:       if (display == "none" ) {
                   9402:           display = "inline";
                   9403:           link.nodeValue = hidetext;
                   9404:         } else {
                   9405:           display = "none";
                   9406:           link.nodeValue = showtext;
                   9407:        }
                   9408:    }
                   9409: }
                   9410: // ]]>
                   9411: </script>
                   9412: ENDTOGGLE
                   9413: }
                   9414: 
1.1039    www      9415: sub start_togglebox {
                   9416:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9417:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9418:     unless ($showtext) { $showtext=&mt('show'); }
                   9419:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9420:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9421:     return &start_data_table().
                   9422:            &start_data_table_header_row().
                   9423:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9424:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9425:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9426:            &end_data_table_header_row().
                   9427:            '<tr id="'.$id.'" style="display:none""><td>';
                   9428: }
                   9429: 
                   9430: sub end_togglebox {
                   9431:     return '</td></tr>'.&end_data_table();
                   9432: }
                   9433: 
1.1041    www      9434: sub LCprogressbar_script {
1.1302    raeburn  9435:    my ($id,$number_to_do)=@_;
                   9436:    if ($number_to_do) {
                   9437:        return(<<ENDPROGRESS);
1.1041    www      9438: <script type="text/javascript">
                   9439: // <![CDATA[
1.1045    www      9440: \$('#progressbar$id').progressbar({
1.1041    www      9441:   value: 0,
                   9442:   change: function(event, ui) {
                   9443:     var newVal = \$(this).progressbar('option', 'value');
                   9444:     \$('.pblabel', this).text(LCprogressTxt);
                   9445:   }
                   9446: });
                   9447: // ]]>
                   9448: </script>
                   9449: ENDPROGRESS
1.1302    raeburn  9450:    } else {
                   9451:        return(<<ENDPROGRESS);
                   9452: <script type="text/javascript">
                   9453: // <![CDATA[
                   9454: \$('#progressbar$id').progressbar({
                   9455:   value: false,
                   9456:   create: function(event, ui) {
                   9457:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9458:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9459:   }
                   9460: });
                   9461: // ]]>
                   9462: </script>
                   9463: ENDPROGRESS
                   9464:    }
1.1041    www      9465: }
                   9466: 
                   9467: sub LCprogressbarUpdate_script {
                   9468:    return(<<ENDPROGRESSUPDATE);
                   9469: <style type="text/css">
                   9470: .ui-progressbar { position:relative; }
1.1302    raeburn  9471: .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      9472: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9473: </style>
                   9474: <script type="text/javascript">
                   9475: // <![CDATA[
1.1045    www      9476: var LCprogressTxt='---';
                   9477: 
1.1302    raeburn  9478: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9479:    LCprogressTxt=progresstext;
1.1302    raeburn  9480:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9481:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9482:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9483:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9484:    } else {
                   9485:        \$('#progressbar'+id).progressbar('value',percent);
                   9486:    }
1.1041    www      9487: }
                   9488: // ]]>
                   9489: </script>
                   9490: ENDPROGRESSUPDATE
                   9491: }
                   9492: 
1.1042    www      9493: my $LClastpercent;
1.1045    www      9494: my $LCidcnt;
                   9495: my $LCcurrentid;
1.1042    www      9496: 
1.1041    www      9497: sub LCprogressbar {
1.1302    raeburn  9498:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9499:     $LClastpercent=0;
1.1045    www      9500:     $LCidcnt++;
                   9501:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9502:     my ($starting,$content);
                   9503:     if ($number_to_do) {
                   9504:         $starting=&mt('Starting');
                   9505:         $content=(<<ENDPROGBAR);
                   9506: $preamble
1.1045    www      9507:   <div id="progressbar$LCcurrentid">
1.1041    www      9508:     <span class="pblabel">$starting</span>
                   9509:   </div>
                   9510: ENDPROGBAR
1.1302    raeburn  9511:     } else {
                   9512:         $starting=&mt('Loading...');
                   9513:         $LClastpercent='false';
                   9514:         $content=(<<ENDPROGBAR);
                   9515: $preamble
                   9516:   <div id="progressbar$LCcurrentid">
                   9517:       <div class="progress-label">$starting</div>
                   9518:   </div>
                   9519: ENDPROGBAR
                   9520:     }
                   9521:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9522: }
                   9523: 
                   9524: sub LCprogressbarUpdate {
1.1302    raeburn  9525:     my ($r,$val,$text,$number_to_do)=@_;
                   9526:     if ($number_to_do) {
                   9527:         unless ($val) { 
                   9528:             if ($LClastpercent) {
                   9529:                 $val=$LClastpercent;
                   9530:             } else {
                   9531:                 $val=0;
                   9532:             }
                   9533:         }
                   9534:         if ($val<0) { $val=0; }
                   9535:         if ($val>100) { $val=0; }
                   9536:         $LClastpercent=$val;
                   9537:         unless ($text) { $text=$val.'%'; }
                   9538:     } else {
                   9539:         $val = 'false';
1.1042    www      9540:     }
1.1041    www      9541:     $text=&js_ready($text);
1.1044    www      9542:     &r_print($r,<<ENDUPDATE);
1.1041    www      9543: <script type="text/javascript">
                   9544: // <![CDATA[
1.1302    raeburn  9545: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9546: // ]]>
                   9547: </script>
                   9548: ENDUPDATE
1.1035    www      9549: }
                   9550: 
1.1042    www      9551: sub LCprogressbarClose {
                   9552:     my ($r)=@_;
                   9553:     $LClastpercent=0;
1.1044    www      9554:     &r_print($r,<<ENDCLOSE);
1.1042    www      9555: <script type="text/javascript">
                   9556: // <![CDATA[
1.1045    www      9557: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9558: // ]]>
                   9559: </script>
                   9560: ENDCLOSE
1.1044    www      9561: }
                   9562: 
                   9563: sub r_print {
                   9564:     my ($r,$to_print)=@_;
                   9565:     if ($r) {
                   9566:       $r->print($to_print);
                   9567:       $r->rflush();
                   9568:     } else {
                   9569:       print($to_print);
                   9570:     }
1.1042    www      9571: }
                   9572: 
1.320     albertel 9573: sub html_encode {
                   9574:     my ($result) = @_;
                   9575: 
1.322     albertel 9576:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9577:     
                   9578:     return $result;
                   9579: }
1.1044    www      9580: 
1.317     albertel 9581: sub js_ready {
                   9582:     my ($result) = @_;
                   9583: 
1.323     albertel 9584:     $result =~ s/[\n\r]/ /xmsg;
                   9585:     $result =~ s/\\/\\\\/xmsg;
                   9586:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9587:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9588:     
                   9589:     return $result;
                   9590: }
                   9591: 
1.315     albertel 9592: sub validate_page {
                   9593:     if (  exists($env{'internal.start_page'})
1.316     albertel 9594: 	  &&     $env{'internal.start_page'} > 1) {
                   9595: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9596: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9597: 				 $ENV{'request.filename'});
1.315     albertel 9598:     }
                   9599:     if (  exists($env{'internal.end_page'})
1.316     albertel 9600: 	  &&     $env{'internal.end_page'} > 1) {
                   9601: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9602: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9603: 				 $env{'request.filename'});
1.315     albertel 9604:     }
                   9605:     if (     exists($env{'internal.start_page'})
                   9606: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9607: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9608: 				 $env{'request.filename'});
1.315     albertel 9609:     }
                   9610:     if (   ! exists($env{'internal.start_page'})
                   9611: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9612: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9613: 				 $env{'request.filename'});
1.315     albertel 9614:     }
1.306     albertel 9615: }
1.315     albertel 9616: 
1.996     www      9617: 
                   9618: sub start_scrollbox {
1.1140    raeburn  9619:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9620:     unless ($outerwidth) { $outerwidth='520px'; }
                   9621:     unless ($width) { $width='500px'; }
                   9622:     unless ($height) { $height='200px'; }
1.1075    raeburn  9623:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9624:     if ($id ne '') {
1.1140    raeburn  9625:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9626:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9627:     }
1.1075    raeburn  9628:     if ($bgcolor ne '') {
                   9629:         $tdcol = "background-color: $bgcolor;";
                   9630:     }
1.1137    raeburn  9631:     my $nicescroll_js;
                   9632:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9633:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9634:     }
                   9635:     return <<"END";
                   9636: $nicescroll_js
                   9637: 
                   9638: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9639: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9640: END
                   9641: }
                   9642: 
                   9643: sub end_scrollbox {
                   9644:     return '</div></td></tr></table>';
                   9645: }
                   9646: 
                   9647: sub nicescroll_javascript {
                   9648:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9649:     my %options;
                   9650:     if (ref($cursor) eq 'HASH') {
                   9651:         %options = %{$cursor};
                   9652:     }
                   9653:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9654:         $options{'railalign'} = 'left';
                   9655:     }
                   9656:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9657:         my $function  = &get_users_function();
                   9658:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9659:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9660:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9661:         }
1.1140    raeburn  9662:     }
                   9663:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9664:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9665:             $options{'cursoropacity'}='1.0';
                   9666:         }
1.1140    raeburn  9667:     } else {
                   9668:         $options{'cursoropacity'}='1.0';
                   9669:     }
                   9670:     if ($options{'cursorfixedheight'} eq 'none') {
                   9671:         delete($options{'cursorfixedheight'});
                   9672:     } else {
                   9673:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9674:     }
                   9675:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9676:         delete($options{'railoffset'});
                   9677:     }
                   9678:     my @niceoptions;
                   9679:     while (my($key,$value) = each(%options)) {
                   9680:         if ($value =~ /^\{.+\}$/) {
                   9681:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9682:         } else {
1.1140    raeburn  9683:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9684:         }
1.1140    raeburn  9685:     }
                   9686:     my $nicescroll_js = '
1.1137    raeburn  9687: $(document).ready(
1.1140    raeburn  9688:       function() {
                   9689:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9690:       }
1.1137    raeburn  9691: );
                   9692: ';
1.1140    raeburn  9693:     if ($framecheck) {
                   9694:         $nicescroll_js .= '
                   9695: function expand_div(caller) {
                   9696:     if (top === self) {
                   9697:         document.getElementById("'.$id.'").style.width = "auto";
                   9698:         document.getElementById("'.$id.'").style.height = "auto";
                   9699:     } else {
                   9700:         try {
                   9701:             if (parent.frames) {
                   9702:                 if (parent.frames.length > 1) {
                   9703:                     var framesrc = parent.frames[1].location.href;
                   9704:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9705:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9706:                         document.getElementById("'.$id.'").style.width = "auto";
                   9707:                         document.getElementById("'.$id.'").style.height = "auto";
                   9708:                     }
                   9709:                 }
                   9710:             }
                   9711:         } catch (e) {
                   9712:             return;
                   9713:         }
1.1137    raeburn  9714:     }
1.1140    raeburn  9715:     return;
1.996     www      9716: }
1.1140    raeburn  9717: ';
                   9718:     }
                   9719:     if ($needjsready) {
                   9720:         $nicescroll_js = '
                   9721: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9722:     } else {
                   9723:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9724:     }
                   9725:     return $nicescroll_js;
1.996     www      9726: }
                   9727: 
1.318     albertel 9728: sub simple_error_page {
1.1150    bisitz   9729:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9730:     my %displayargs;
1.1151    raeburn  9731:     if (ref($args) eq 'HASH') {
                   9732:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9733:         if ($args->{'only_body'}) {
                   9734:             $displayargs{'only_body'} = 1;
                   9735:         }
                   9736:         if ($args->{'no_nav_bar'}) {
                   9737:             $displayargs{'no_nav_bar'} = 1;
                   9738:         }
1.1151    raeburn  9739:     } else {
                   9740:         $msg = &mt($msg);
                   9741:     }
1.1150    bisitz   9742: 
1.318     albertel 9743:     my $page =
1.1304    raeburn  9744: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9745: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9746: 	&Apache::loncommon::end_page();
                   9747:     if (ref($r)) {
                   9748: 	$r->print($page);
1.327     albertel 9749: 	return;
1.318     albertel 9750:     }
                   9751:     return $page;
                   9752: }
1.347     albertel 9753: 
                   9754: {
1.610     albertel 9755:     my @row_count;
1.961     onken    9756: 
                   9757:     sub start_data_table_count {
                   9758:         unshift(@row_count, 0);
                   9759:         return;
                   9760:     }
                   9761: 
                   9762:     sub end_data_table_count {
                   9763:         shift(@row_count);
                   9764:         return;
                   9765:     }
                   9766: 
1.347     albertel 9767:     sub start_data_table {
1.1018    raeburn  9768: 	my ($add_class,$id) = @_;
1.422     albertel 9769: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9770:         my $table_id;
                   9771:         if (defined($id)) {
                   9772:             $table_id = ' id="'.$id.'"';
                   9773:         }
1.961     onken    9774: 	&start_data_table_count();
1.1018    raeburn  9775: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9776:     }
                   9777: 
                   9778:     sub end_data_table {
1.961     onken    9779: 	&end_data_table_count();
1.389     albertel 9780: 	return '</table>'."\n";;
1.347     albertel 9781:     }
                   9782: 
                   9783:     sub start_data_table_row {
1.974     wenzelju 9784: 	my ($add_class, $id) = @_;
1.610     albertel 9785: 	$row_count[0]++;
                   9786: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9787: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9788:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9789:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9790:     }
1.471     banghart 9791:     
                   9792:     sub continue_data_table_row {
1.974     wenzelju 9793: 	my ($add_class, $id) = @_;
1.610     albertel 9794: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9795: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9796:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9797:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9798:     }
1.347     albertel 9799: 
                   9800:     sub end_data_table_row {
1.389     albertel 9801: 	return '</tr>'."\n";;
1.347     albertel 9802:     }
1.367     www      9803: 
1.421     albertel 9804:     sub start_data_table_empty_row {
1.707     bisitz   9805: #	$row_count[0]++;
1.421     albertel 9806: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9807:     }
                   9808: 
                   9809:     sub end_data_table_empty_row {
                   9810: 	return '</tr>'."\n";;
                   9811:     }
                   9812: 
1.367     www      9813:     sub start_data_table_header_row {
1.389     albertel 9814: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9815:     }
                   9816: 
                   9817:     sub end_data_table_header_row {
1.389     albertel 9818: 	return '</tr>'."\n";;
1.367     www      9819:     }
1.890     droeschl 9820: 
                   9821:     sub data_table_caption {
                   9822:         my $caption = shift;
                   9823:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9824:     }
1.347     albertel 9825: }
                   9826: 
1.548     albertel 9827: =pod
                   9828: 
                   9829: =item * &inhibit_menu_check($arg)
                   9830: 
                   9831: Checks for a inhibitmenu state and generates output to preserve it
                   9832: 
                   9833: Inputs:         $arg - can be any of
                   9834:                      - undef - in which case the return value is a string 
                   9835:                                to add  into arguments list of a uri
                   9836:                      - 'input' - in which case the return value is a HTML
                   9837:                                  <form> <input> field of type hidden to
                   9838:                                  preserve the value
                   9839:                      - a url - in which case the return value is the url with
                   9840:                                the neccesary cgi args added to preserve the
                   9841:                                inhibitmenu state
                   9842:                      - a ref to a url - no return value, but the string is
                   9843:                                         updated to include the neccessary cgi
                   9844:                                         args to preserve the inhibitmenu state
                   9845: 
                   9846: =cut
                   9847: 
                   9848: sub inhibit_menu_check {
                   9849:     my ($arg) = @_;
                   9850:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9851:     if ($arg eq 'input') {
                   9852: 	if ($env{'form.inhibitmenu'}) {
                   9853: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9854: 	} else {
                   9855: 	    return
                   9856: 	}
                   9857:     }
                   9858:     if ($env{'form.inhibitmenu'}) {
                   9859: 	if (ref($arg)) {
                   9860: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9861: 	} elsif ($arg eq '') {
                   9862: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9863: 	} else {
                   9864: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9865: 	}
                   9866:     }
                   9867:     if (!ref($arg)) {
                   9868: 	return $arg;
                   9869:     }
                   9870: }
                   9871: 
1.251     albertel 9872: ###############################################
1.182     matthew  9873: 
                   9874: =pod
                   9875: 
1.549     albertel 9876: =back
                   9877: 
                   9878: =head1 User Information Routines
                   9879: 
                   9880: =over 4
                   9881: 
1.405     albertel 9882: =item * &get_users_function()
1.182     matthew  9883: 
                   9884: Used by &bodytag to determine the current users primary role.
                   9885: Returns either 'student','coordinator','admin', or 'author'.
                   9886: 
                   9887: =cut
                   9888: 
                   9889: ###############################################
                   9890: sub get_users_function {
1.815     tempelho 9891:     my $function = 'norole';
1.818     tempelho 9892:     if ($env{'request.role'}=~/^(st)/) {
                   9893:         $function='student';
                   9894:     }
1.907     raeburn  9895:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9896:         $function='coordinator';
                   9897:     }
1.258     albertel 9898:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9899:         $function='admin';
                   9900:     }
1.826     bisitz   9901:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9902:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9903:         $function='author';
                   9904:     }
                   9905:     return $function;
1.54      www      9906: }
1.99      www      9907: 
                   9908: ###############################################
                   9909: 
1.233     raeburn  9910: =pod
                   9911: 
1.821     raeburn  9912: =item * &show_course()
                   9913: 
                   9914: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9915: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9916: 
                   9917: Inputs:
                   9918: None
                   9919: 
                   9920: Outputs:
                   9921: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9922: 
                   9923: =cut
                   9924: 
                   9925: ###############################################
                   9926: sub show_course {
                   9927:     my $course = !$env{'user.adv'};
                   9928:     if (!$env{'user.adv'}) {
                   9929:         foreach my $env (keys(%env)) {
                   9930:             next if ($env !~ m/^user\.priv\./);
                   9931:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9932:                 $course = 0;
                   9933:                 last;
                   9934:             }
                   9935:         }
                   9936:     }
                   9937:     return $course;
                   9938: }
                   9939: 
                   9940: ###############################################
                   9941: 
                   9942: =pod
                   9943: 
1.542     raeburn  9944: =item * &check_user_status()
1.274     raeburn  9945: 
                   9946: Determines current status of supplied role for a
                   9947: specific user. Roles can be active, previous or future.
                   9948: 
                   9949: Inputs: 
                   9950: user's domain, user's username, course's domain,
1.375     raeburn  9951: course's number, optional section ID.
1.274     raeburn  9952: 
                   9953: Outputs:
                   9954: role status: active, previous or future. 
                   9955: 
                   9956: =cut
                   9957: 
                   9958: sub check_user_status {
1.412     raeburn  9959:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9960:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9961:     my @uroles = keys(%userinfo);
1.274     raeburn  9962:     my $srchstr;
                   9963:     my $active_chk = 'none';
1.412     raeburn  9964:     my $now = time;
1.274     raeburn  9965:     if (@uroles > 0) {
1.908     raeburn  9966:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9967:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9968:         } else {
1.412     raeburn  9969:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9970:         }
                   9971:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9972:             my $role_end = 0;
                   9973:             my $role_start = 0;
                   9974:             $active_chk = 'active';
1.412     raeburn  9975:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9976:                 $role_end = $1;
                   9977:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9978:                     $role_start = $1;
1.274     raeburn  9979:                 }
                   9980:             }
                   9981:             if ($role_start > 0) {
1.412     raeburn  9982:                 if ($now < $role_start) {
1.274     raeburn  9983:                     $active_chk = 'future';
                   9984:                 }
                   9985:             }
                   9986:             if ($role_end > 0) {
1.412     raeburn  9987:                 if ($now > $role_end) {
1.274     raeburn  9988:                     $active_chk = 'previous';
                   9989:                 }
                   9990:             }
                   9991:         }
                   9992:     }
                   9993:     return $active_chk;
                   9994: }
                   9995: 
                   9996: ###############################################
                   9997: 
                   9998: =pod
                   9999: 
1.405     albertel 10000: =item * &get_sections()
1.233     raeburn  10001: 
                   10002: Determines all the sections for a course including
                   10003: sections with students and sections containing other roles.
1.419     raeburn  10004: Incoming parameters: 
                   10005: 
                   10006: 1. domain
                   10007: 2. course number 
                   10008: 3. reference to array containing roles for which sections should 
                   10009: be gathered (optional).
                   10010: 4. reference to array containing status types for which sections 
                   10011: should be gathered (optional).
                   10012: 
                   10013: If the third argument is undefined, sections are gathered for any role. 
                   10014: If the fourth argument is undefined, sections are gathered for any status.
                   10015: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10016:  
1.374     raeburn  10017: Returns section hash (keys are section IDs, values are
                   10018: number of users in each section), subject to the
1.419     raeburn  10019: optional roles filter, optional status filter 
1.233     raeburn  10020: 
                   10021: =cut
                   10022: 
                   10023: ###############################################
                   10024: sub get_sections {
1.419     raeburn  10025:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10026:     if (!defined($cdom) || !defined($cnum)) {
                   10027:         my $cid =  $env{'request.course.id'};
                   10028: 
                   10029: 	return if (!defined($cid));
                   10030: 
                   10031:         $cdom = $env{'course.'.$cid.'.domain'};
                   10032:         $cnum = $env{'course.'.$cid.'.num'};
                   10033:     }
                   10034: 
                   10035:     my %sectioncount;
1.419     raeburn  10036:     my $now = time;
1.240     albertel 10037: 
1.1118    raeburn  10038:     my $check_students = 1;
                   10039:     my $only_students = 0;
                   10040:     if (ref($possible_roles) eq 'ARRAY') {
                   10041:         if (grep(/^st$/,@{$possible_roles})) {
                   10042:             if (@{$possible_roles} == 1) {
                   10043:                 $only_students = 1;
                   10044:             }
                   10045:         } else {
                   10046:             $check_students = 0;
                   10047:         }
                   10048:     }
                   10049: 
                   10050:     if ($check_students) { 
1.276     albertel 10051: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10052: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10053: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10054:         my $start_index = &Apache::loncoursedata::CL_START();
                   10055:         my $end_index = &Apache::loncoursedata::CL_END();
                   10056:         my $status;
1.366     albertel 10057: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10058: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10059: 				                     $data->[$status_index],
                   10060:                                                      $data->[$start_index],
                   10061:                                                      $data->[$end_index]);
                   10062:             if ($stu_status eq 'Active') {
                   10063:                 $status = 'active';
                   10064:             } elsif ($end < $now) {
                   10065:                 $status = 'previous';
                   10066:             } elsif ($start > $now) {
                   10067:                 $status = 'future';
                   10068:             } 
                   10069: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10070:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10071:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10072: 		    $sectioncount{$section}++;
                   10073:                 }
1.240     albertel 10074: 	    }
                   10075: 	}
                   10076:     }
1.1118    raeburn  10077:     if ($only_students) {
                   10078:         return %sectioncount;
                   10079:     }
1.240     albertel 10080:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10081:     foreach my $user (sort(keys(%courseroles))) {
                   10082: 	if ($user !~ /^(\w{2})/) { next; }
                   10083: 	my ($role) = ($user =~ /^(\w{2})/);
                   10084: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10085: 	my ($section,$status);
1.240     albertel 10086: 	if ($role eq 'cr' &&
                   10087: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10088: 	    $section=$1;
                   10089: 	}
                   10090: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10091: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10092:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10093:         if ($end == -1 && $start == -1) {
                   10094:             next; #deleted role
                   10095:         }
                   10096:         if (!defined($possible_status)) { 
                   10097:             $sectioncount{$section}++;
                   10098:         } else {
                   10099:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10100:                 $status = 'active';
                   10101:             } elsif ($end < $now) {
                   10102:                 $status = 'future';
                   10103:             } elsif ($start > $now) {
                   10104:                 $status = 'previous';
                   10105:             }
                   10106:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10107:                 $sectioncount{$section}++;
                   10108:             }
                   10109:         }
1.233     raeburn  10110:     }
1.366     albertel 10111:     return %sectioncount;
1.233     raeburn  10112: }
                   10113: 
1.274     raeburn  10114: ###############################################
1.294     raeburn  10115: 
                   10116: =pod
1.405     albertel 10117: 
                   10118: =item * &get_course_users()
                   10119: 
1.275     raeburn  10120: Retrieves usernames:domains for users in the specified course
                   10121: with specific role(s), and access status. 
                   10122: 
                   10123: Incoming parameters:
1.277     albertel 10124: 1. course domain
                   10125: 2. course number
                   10126: 3. access status: users must have - either active, 
1.275     raeburn  10127: previous, future, or all.
1.277     albertel 10128: 4. reference to array of permissible roles
1.288     raeburn  10129: 5. reference to array of section restrictions (optional)
                   10130: 6. reference to results object (hash of hashes).
                   10131: 7. reference to optional userdata hash
1.609     raeburn  10132: 8. reference to optional statushash
1.630     raeburn  10133: 9. flag if privileged users (except those set to unhide in
                   10134:    course settings) should be excluded    
1.609     raeburn  10135: Keys of top level results hash are roles.
1.275     raeburn  10136: Keys of inner hashes are username:domain, with 
                   10137: values set to access type.
1.288     raeburn  10138: Optional userdata hash returns an array with arguments in the 
                   10139: same order as loncoursedata::get_classlist() for student data.
                   10140: 
1.609     raeburn  10141: Optional statushash returns
                   10142: 
1.288     raeburn  10143: Entries for end, start, section and status are blank because
                   10144: of the possibility of multiple values for non-student roles.
                   10145: 
1.275     raeburn  10146: =cut
1.405     albertel 10147: 
1.275     raeburn  10148: ###############################################
1.405     albertel 10149: 
1.275     raeburn  10150: sub get_course_users {
1.630     raeburn  10151:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10152:     my %idx = ();
1.419     raeburn  10153:     my %seclists;
1.288     raeburn  10154: 
                   10155:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10156:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10157:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10158:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10159:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10160:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10161:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10162:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10163: 
1.290     albertel 10164:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10165:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10166:         my $now = time;
1.277     albertel 10167:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10168:             my $match = 0;
1.412     raeburn  10169:             my $secmatch = 0;
1.419     raeburn  10170:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10171:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10172:             if ($section eq '') {
                   10173:                 $section = 'none';
                   10174:             }
1.291     albertel 10175:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10176:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10177:                     $secmatch = 1;
                   10178:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10179:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10180:                         $secmatch = 1;
                   10181:                     }
                   10182:                 } else {  
1.419     raeburn  10183: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10184: 		        $secmatch = 1;
                   10185:                     }
1.290     albertel 10186: 		}
1.412     raeburn  10187:                 if (!$secmatch) {
                   10188:                     next;
                   10189:                 }
1.419     raeburn  10190:             }
1.275     raeburn  10191:             if (defined($$types{'active'})) {
1.288     raeburn  10192:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10193:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10194:                     $match = 1;
1.275     raeburn  10195:                 }
                   10196:             }
                   10197:             if (defined($$types{'previous'})) {
1.609     raeburn  10198:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10199:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10200:                     $match = 1;
1.275     raeburn  10201:                 }
                   10202:             }
                   10203:             if (defined($$types{'future'})) {
1.609     raeburn  10204:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10205:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10206:                     $match = 1;
1.275     raeburn  10207:                 }
                   10208:             }
1.609     raeburn  10209:             if ($match) {
                   10210:                 push(@{$seclists{$student}},$section);
                   10211:                 if (ref($userdata) eq 'HASH') {
                   10212:                     $$userdata{$student} = $$classlist{$student};
                   10213:                 }
                   10214:                 if (ref($statushash) eq 'HASH') {
                   10215:                     $statushash->{$student}{'st'}{$section} = $status;
                   10216:                 }
1.288     raeburn  10217:             }
1.275     raeburn  10218:         }
                   10219:     }
1.412     raeburn  10220:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10221:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10222:         my $now = time;
1.609     raeburn  10223:         my %displaystatus = ( previous => 'Expired',
                   10224:                               active   => 'Active',
                   10225:                               future   => 'Future',
                   10226:                             );
1.1121    raeburn  10227:         my (%nothide,@possdoms);
1.630     raeburn  10228:         if ($hidepriv) {
                   10229:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10230:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10231:                 if ($user !~ /:/) {
                   10232:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10233:                 } else {
                   10234:                     $nothide{$user} = 1;
                   10235:                 }
                   10236:             }
1.1121    raeburn  10237:             my @possdoms = ($cdom);
                   10238:             if ($coursehash{'checkforpriv'}) {
                   10239:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10240:             }
1.630     raeburn  10241:         }
1.439     raeburn  10242:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10243:             my $match = 0;
1.412     raeburn  10244:             my $secmatch = 0;
1.439     raeburn  10245:             my $status;
1.412     raeburn  10246:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10247:             $user =~ s/:$//;
1.439     raeburn  10248:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10249:             if ($end == -1 || $start == -1) {
                   10250:                 next;
                   10251:             }
                   10252:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10253:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10254:                 my ($uname,$udom) = split(/:/,$user);
                   10255:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10256:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10257:                         $secmatch = 1;
                   10258:                     } elsif ($usec eq '') {
1.420     albertel 10259:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10260:                             $secmatch = 1;
                   10261:                         }
                   10262:                     } else {
                   10263:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10264:                             $secmatch = 1;
                   10265:                         }
                   10266:                     }
                   10267:                     if (!$secmatch) {
                   10268:                         next;
                   10269:                     }
1.288     raeburn  10270:                 }
1.419     raeburn  10271:                 if ($usec eq '') {
                   10272:                     $usec = 'none';
                   10273:                 }
1.275     raeburn  10274:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10275:                     if ($hidepriv) {
1.1121    raeburn  10276:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10277:                             (!$nothide{$uname.':'.$udom})) {
                   10278:                             next;
                   10279:                         }
                   10280:                     }
1.503     raeburn  10281:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10282:                         $status = 'previous';
                   10283:                     } elsif ($start > $now) {
                   10284:                         $status = 'future';
                   10285:                     } else {
                   10286:                         $status = 'active';
                   10287:                     }
1.277     albertel 10288:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10289:                         if ($status eq $type) {
1.420     albertel 10290:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10291:                                 push(@{$$users{$role}{$user}},$type);
                   10292:                             }
1.288     raeburn  10293:                             $match = 1;
                   10294:                         }
                   10295:                     }
1.419     raeburn  10296:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10297:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10298: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10299:                         }
1.420     albertel 10300:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10301:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10302:                         }
1.609     raeburn  10303:                         if (ref($statushash) eq 'HASH') {
                   10304:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10305:                         }
1.275     raeburn  10306:                     }
                   10307:                 }
                   10308:             }
                   10309:         }
1.290     albertel 10310:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10311:             if ((defined($cdom)) && (defined($cnum))) {
                   10312:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10313:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10314:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10315:                     next if ($owner eq '');
                   10316:                     my ($ownername,$ownerdom);
                   10317:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10318:                         $ownername = $1;
                   10319:                         $ownerdom = $2;
                   10320:                     } else {
                   10321:                         $ownername = $owner;
                   10322:                         $ownerdom = $cdom;
                   10323:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10324:                     }
                   10325:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10326:                     if (defined($userdata) && 
1.609     raeburn  10327: 			!exists($$userdata{$owner})) {
                   10328: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10329:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10330:                             push(@{$seclists{$owner}},'none');
                   10331:                         }
                   10332:                         if (ref($statushash) eq 'HASH') {
                   10333:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10334:                         }
1.290     albertel 10335: 		    }
1.279     raeburn  10336:                 }
                   10337:             }
                   10338:         }
1.419     raeburn  10339:         foreach my $user (keys(%seclists)) {
                   10340:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10341:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10342:         }
1.275     raeburn  10343:     }
                   10344:     return;
                   10345: }
                   10346: 
1.288     raeburn  10347: sub get_user_info {
                   10348:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10349:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10350: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10351:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10352:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10353:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10354:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10355:     return;
                   10356: }
1.275     raeburn  10357: 
1.472     raeburn  10358: ###############################################
                   10359: 
                   10360: =pod
                   10361: 
                   10362: =item * &get_user_quota()
                   10363: 
1.1134    raeburn  10364: Retrieves quota assigned for storage of user files.
                   10365: Default is to report quota for portfolio files.
1.472     raeburn  10366: 
                   10367: Incoming parameters:
                   10368: 1. user's username
                   10369: 2. user's domain
1.1134    raeburn  10370: 3. quota name - portfolio, author, or course
1.1136    raeburn  10371:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10372: 4. crstype - official, unofficial, textbook, placement or community, 
                   10373:    if quota name is course
1.472     raeburn  10374: 
                   10375: Returns:
1.1163    raeburn  10376: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10377: 2. (Optional) Type of setting: custom or default
                   10378:    (individually assigned or default for user's 
                   10379:    institutional status).
                   10380: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10381:    or student - types as defined in localenroll::inst_usertypes 
                   10382:    for user's domain, which determines default quota for user.
                   10383: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10384: 
                   10385: If a value has been stored in the user's environment, 
1.536     raeburn  10386: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10387: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10388: 
                   10389: =cut
                   10390: 
                   10391: ###############################################
                   10392: 
                   10393: 
                   10394: sub get_user_quota {
1.1136    raeburn  10395:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10396:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10397:     if (!defined($udom)) {
                   10398:         $udom = $env{'user.domain'};
                   10399:     }
                   10400:     if (!defined($uname)) {
                   10401:         $uname = $env{'user.name'};
                   10402:     }
                   10403:     if (($udom eq '' || $uname eq '') ||
                   10404:         ($udom eq 'public') && ($uname eq 'public')) {
                   10405:         $quota = 0;
1.536     raeburn  10406:         $quotatype = 'default';
                   10407:         $defquota = 0; 
1.472     raeburn  10408:     } else {
1.536     raeburn  10409:         my $inststatus;
1.1134    raeburn  10410:         if ($quotaname eq 'course') {
                   10411:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10412:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10413:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10414:             } else {
                   10415:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10416:                 $quota = $cenv{'internal.uploadquota'};
                   10417:             }
1.536     raeburn  10418:         } else {
1.1134    raeburn  10419:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10420:                 if ($quotaname eq 'author') {
                   10421:                     $quota = $env{'environment.authorquota'};
                   10422:                 } else {
                   10423:                     $quota = $env{'environment.portfolioquota'};
                   10424:                 }
                   10425:                 $inststatus = $env{'environment.inststatus'};
                   10426:             } else {
                   10427:                 my %userenv = 
                   10428:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10429:                                          'authorquota','inststatus'],$udom,$uname);
                   10430:                 my ($tmp) = keys(%userenv);
                   10431:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10432:                     if ($quotaname eq 'author') {
                   10433:                         $quota = $userenv{'authorquota'};
                   10434:                     } else {
                   10435:                         $quota = $userenv{'portfolioquota'};
                   10436:                     }
                   10437:                     $inststatus = $userenv{'inststatus'};
                   10438:                 } else {
                   10439:                     undef(%userenv);
                   10440:                 }
                   10441:             }
                   10442:         }
                   10443:         if ($quota eq '' || wantarray) {
                   10444:             if ($quotaname eq 'course') {
                   10445:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10446:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10447:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10448:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10449:                     $defquota = $domdefs{$crstype.'quota'};
                   10450:                 }
                   10451:                 if ($defquota eq '') {
                   10452:                     $defquota = 500;
                   10453:                 }
1.1134    raeburn  10454:             } else {
                   10455:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10456:             }
                   10457:             if ($quota eq '') {
                   10458:                 $quota = $defquota;
                   10459:                 $quotatype = 'default';
                   10460:             } else {
                   10461:                 $quotatype = 'custom';
                   10462:             }
1.472     raeburn  10463:         }
                   10464:     }
1.536     raeburn  10465:     if (wantarray) {
                   10466:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10467:     } else {
                   10468:         return $quota;
                   10469:     }
1.472     raeburn  10470: }
                   10471: 
                   10472: ###############################################
                   10473: 
                   10474: =pod
                   10475: 
                   10476: =item * &default_quota()
                   10477: 
1.536     raeburn  10478: Retrieves default quota assigned for storage of user portfolio files,
                   10479: given an (optional) user's institutional status.
1.472     raeburn  10480: 
                   10481: Incoming parameters:
1.1142    raeburn  10482: 
1.472     raeburn  10483: 1. domain
1.536     raeburn  10484: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10485:    status types (e.g., faculty, staff, student etc.)
                   10486:    which apply to the user for whom the default is being retrieved.
                   10487:    If the institutional status string in undefined, the domain
1.1134    raeburn  10488:    default quota will be returned.
                   10489: 3.  quota name - portfolio, author, or course
                   10490:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10491: 
                   10492: Returns:
1.1142    raeburn  10493: 
1.1163    raeburn  10494: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10495: 2. (Optional) institutional type which determined the value of the
                   10496:    default quota.
1.472     raeburn  10497: 
                   10498: If a value has been stored in the domain's configuration db,
                   10499: it will return that, otherwise it returns 20 (for backwards 
                   10500: compatibility with domains which have not set up a configuration
1.1163    raeburn  10501: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10502: 
1.536     raeburn  10503: If the user's status includes multiple types (e.g., staff and student),
                   10504: the largest default quota which applies to the user determines the
                   10505: default quota returned.
                   10506: 
1.472     raeburn  10507: =cut
                   10508: 
                   10509: ###############################################
                   10510: 
                   10511: 
                   10512: sub default_quota {
1.1134    raeburn  10513:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10514:     my ($defquota,$settingstatus);
                   10515:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10516:                                             ['quotas'],$udom);
1.1134    raeburn  10517:     my $key = 'defaultquota';
                   10518:     if ($quotaname eq 'author') {
                   10519:         $key = 'authorquota';
                   10520:     }
1.622     raeburn  10521:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10522:         if ($inststatus ne '') {
1.765     raeburn  10523:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10524:             foreach my $item (@statuses) {
1.1134    raeburn  10525:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10526:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10527:                         if ($defquota eq '') {
1.1134    raeburn  10528:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10529:                             $settingstatus = $item;
1.1134    raeburn  10530:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10531:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10532:                             $settingstatus = $item;
                   10533:                         }
                   10534:                     }
1.1134    raeburn  10535:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10536:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10537:                         if ($defquota eq '') {
                   10538:                             $defquota = $quotahash{'quotas'}{$item};
                   10539:                             $settingstatus = $item;
                   10540:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10541:                             $defquota = $quotahash{'quotas'}{$item};
                   10542:                             $settingstatus = $item;
                   10543:                         }
1.536     raeburn  10544:                     }
                   10545:                 }
                   10546:             }
                   10547:         }
                   10548:         if ($defquota eq '') {
1.1134    raeburn  10549:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10550:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10551:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10552:                 $defquota = $quotahash{'quotas'}{'default'};
                   10553:             }
1.536     raeburn  10554:             $settingstatus = 'default';
1.1139    raeburn  10555:             if ($defquota eq '') {
                   10556:                 if ($quotaname eq 'author') {
                   10557:                     $defquota = 500;
                   10558:                 }
                   10559:             }
1.536     raeburn  10560:         }
                   10561:     } else {
                   10562:         $settingstatus = 'default';
1.1134    raeburn  10563:         if ($quotaname eq 'author') {
                   10564:             $defquota = 500;
                   10565:         } else {
                   10566:             $defquota = 20;
                   10567:         }
1.536     raeburn  10568:     }
                   10569:     if (wantarray) {
                   10570:         return ($defquota,$settingstatus);
1.472     raeburn  10571:     } else {
1.536     raeburn  10572:         return $defquota;
1.472     raeburn  10573:     }
                   10574: }
                   10575: 
1.1135    raeburn  10576: ###############################################
                   10577: 
                   10578: =pod
                   10579: 
1.1136    raeburn  10580: =item * &excess_filesize_warning()
1.1135    raeburn  10581: 
                   10582: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10583: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10584: space to be exceeded.
1.1136    raeburn  10585: 
                   10586: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10587: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10588: 
1.1165    raeburn  10589: Inputs: 7 
1.1136    raeburn  10590: 1. username or coursenum
1.1135    raeburn  10591: 2. domain
1.1136    raeburn  10592: 3. context ('author' or 'course')
1.1135    raeburn  10593: 4. filename of file for which action is being requested
                   10594: 5. filesize (kB) of file
                   10595: 6. action being taken: copy or upload.
1.1237    raeburn  10596: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10597: 
                   10598: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10599:          otherwise return null.
                   10600: 
                   10601: =back
1.1135    raeburn  10602: 
                   10603: =cut
                   10604: 
1.1136    raeburn  10605: sub excess_filesize_warning {
1.1165    raeburn  10606:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10607:     my $current_disk_usage = 0;
1.1165    raeburn  10608:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10609:     if ($context eq 'author') {
                   10610:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10611:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10612:     } else {
                   10613:         foreach my $subdir ('docs','supplemental') {
                   10614:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10615:         }
                   10616:     }
1.1135    raeburn  10617:     $disk_quota = int($disk_quota * 1000);
                   10618:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10619:         return '<p class="LC_warning">'.
1.1135    raeburn  10620:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10621:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10622:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10623:                             $disk_quota,$current_disk_usage).
                   10624:                '</p>';
                   10625:     }
                   10626:     return;
                   10627: }
                   10628: 
                   10629: ###############################################
                   10630: 
                   10631: 
1.1136    raeburn  10632: 
                   10633: 
1.384     raeburn  10634: sub get_secgrprole_info {
                   10635:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10636:     my %sections_count = &get_sections($cdom,$cnum);
                   10637:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10638:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10639:     my @groups = sort(keys(%curr_groups));
                   10640:     my $allroles = [];
                   10641:     my $rolehash;
                   10642:     my $accesshash = {
                   10643:                      active => 'Currently has access',
                   10644:                      future => 'Will have future access',
                   10645:                      previous => 'Previously had access',
                   10646:                   };
                   10647:     if ($needroles) {
                   10648:         $rolehash = {'all' => 'all'};
1.385     albertel 10649:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10650: 	if (&Apache::lonnet::error(%user_roles)) {
                   10651: 	    undef(%user_roles);
                   10652: 	}
                   10653:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10654:             my ($role)=split(/\:/,$item,2);
                   10655:             if ($role eq 'cr') { next; }
                   10656:             if ($role =~ /^cr/) {
                   10657:                 $$rolehash{$role} = (split('/',$role))[3];
                   10658:             } else {
                   10659:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10660:             }
                   10661:         }
                   10662:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10663:             push(@{$allroles},$key);
                   10664:         }
                   10665:         push (@{$allroles},'st');
                   10666:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10667:     }
                   10668:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10669: }
                   10670: 
1.555     raeburn  10671: sub user_picker {
1.1279    raeburn  10672:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10673:     my $currdom = $dom;
1.1253    raeburn  10674:     my @alldoms = &Apache::lonnet::all_domains();
                   10675:     if (@alldoms == 1) {
                   10676:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10677:                                                ['directorysrch'],$alldoms[0]);
                   10678:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10679:         my $showdom = $domdesc;
                   10680:         if ($showdom eq '') {
                   10681:             $showdom = $dom;
                   10682:         }
                   10683:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10684:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10685:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10686:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10687:             }
                   10688:         }
                   10689:     }
1.555     raeburn  10690:     my %curr_selected = (
                   10691:                         srchin => 'dom',
1.580     raeburn  10692:                         srchby => 'lastname',
1.555     raeburn  10693:                       );
                   10694:     my $srchterm;
1.625     raeburn  10695:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10696:         if ($srch->{'srchby'} ne '') {
                   10697:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10698:         }
                   10699:         if ($srch->{'srchin'} ne '') {
                   10700:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10701:         }
                   10702:         if ($srch->{'srchtype'} ne '') {
                   10703:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10704:         }
                   10705:         if ($srch->{'srchdomain'} ne '') {
                   10706:             $currdom = $srch->{'srchdomain'};
                   10707:         }
                   10708:         $srchterm = $srch->{'srchterm'};
                   10709:     }
1.1222    damieng  10710:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10711:                     'usr'       => 'Search criteria',
1.563     raeburn  10712:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10713:                     'uname'     => 'username',
                   10714:                     'lastname'  => 'last name',
1.555     raeburn  10715:                     'lastfirst' => 'last name, first name',
1.558     albertel 10716:                     'crs'       => 'in this course',
1.576     raeburn  10717:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10718:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10719:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10720:                     'exact'     => 'is',
                   10721:                     'contains'  => 'contains',
1.569     raeburn  10722:                     'begins'    => 'begins with',
1.1222    damieng  10723:                                        );
                   10724:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10725:                     'youm'      => "You must include some text to search for.",
                   10726:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10727:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10728:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10729:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10730:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10731:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10732:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10733:                                        );
1.1222    damieng  10734:     &html_escape(\%html_lt);
                   10735:     &js_escape(\%js_lt);
1.1255    raeburn  10736:     my $domform;
1.1277    raeburn  10737:     my $allow_blank = 1;
1.1255    raeburn  10738:     if ($fixeddom) {
1.1277    raeburn  10739:         $allow_blank = 0;
                   10740:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10741:     } else {
1.1287    raeburn  10742:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10743:         my ($trusted,$untrusted);
1.1287    raeburn  10744:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10745:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10746:         } elsif ($context eq 'author') {
1.1288    raeburn  10747:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10748:         } elsif ($context eq 'domain') {
1.1288    raeburn  10749:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10750:         }
1.1288    raeburn  10751:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10752:     }
1.563     raeburn  10753:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10754: 
                   10755:     my @srchins = ('crs','dom','alc','instd');
                   10756: 
                   10757:     foreach my $option (@srchins) {
                   10758:         # FIXME 'alc' option unavailable until 
                   10759:         #       loncreateuser::print_user_query_page()
                   10760:         #       has been completed.
                   10761:         next if ($option eq 'alc');
1.880     raeburn  10762:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10763:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10764:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10765:         if ($curr_selected{'srchin'} eq $option) {
                   10766:             $srchinsel .= ' 
1.1222    damieng  10767:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10768:         } else {
                   10769:             $srchinsel .= '
1.1222    damieng  10770:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10771:         }
1.555     raeburn  10772:     }
1.563     raeburn  10773:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10774: 
                   10775:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10776:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10777:         if ($curr_selected{'srchby'} eq $option) {
                   10778:             $srchbysel .= '
1.1222    damieng  10779:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10780:         } else {
                   10781:             $srchbysel .= '
1.1222    damieng  10782:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10783:          }
                   10784:     }
                   10785:     $srchbysel .= "\n  </select>\n";
                   10786: 
                   10787:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10788:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10789:         if ($curr_selected{'srchtype'} eq $option) {
                   10790:             $srchtypesel .= '
1.1222    damieng  10791:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10792:         } else {
                   10793:             $srchtypesel .= '
1.1222    damieng  10794:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10795:         }
                   10796:     }
                   10797:     $srchtypesel .= "\n  </select>\n";
                   10798: 
1.558     albertel 10799:     my ($newuserscript,$new_user_create);
1.994     raeburn  10800:     my $context_dom = $env{'request.role.domain'};
                   10801:     if ($context eq 'requestcrs') {
                   10802:         if ($env{'form.coursedom'} ne '') { 
                   10803:             $context_dom = $env{'form.coursedom'};
                   10804:         }
                   10805:     }
1.556     raeburn  10806:     if ($forcenewuser) {
1.576     raeburn  10807:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10808:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10809:                 if ($cancreate) {
                   10810:                     $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>';
                   10811:                 } else {
1.799     bisitz   10812:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10813:                     my %usertypetext = (
                   10814:                         official   => 'institutional',
                   10815:                         unofficial => 'non-institutional',
                   10816:                     );
1.799     bisitz   10817:                     $new_user_create = '<p class="LC_warning">'
                   10818:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10819:                                       .' '
                   10820:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10821:                                           ,'<a href="'.$helplink.'">','</a>')
                   10822:                                       .'</p><br />';
1.627     raeburn  10823:                 }
1.576     raeburn  10824:             }
                   10825:         }
                   10826: 
1.556     raeburn  10827:         $newuserscript = <<"ENDSCRIPT";
                   10828: 
1.570     raeburn  10829: function setSearch(createnew,callingForm) {
1.556     raeburn  10830:     if (createnew == 1) {
1.570     raeburn  10831:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10832:             if (callingForm.srchby.options[i].value == 'uname') {
                   10833:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10834:             }
                   10835:         }
1.570     raeburn  10836:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10837:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10838: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10839:             }
                   10840:         }
1.570     raeburn  10841:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10842:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10843:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10844:             }
                   10845:         }
1.570     raeburn  10846:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10847:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10848:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10849:             }
                   10850:         }
                   10851:     }
                   10852: }
                   10853: ENDSCRIPT
1.558     albertel 10854: 
1.556     raeburn  10855:     }
                   10856: 
1.555     raeburn  10857:     my $output = <<"END_BLOCK";
1.556     raeburn  10858: <script type="text/javascript">
1.824     bisitz   10859: // <![CDATA[
1.570     raeburn  10860: function validateEntry(callingForm) {
1.558     albertel 10861: 
1.556     raeburn  10862:     var checkok = 1;
1.558     albertel 10863:     var srchin;
1.570     raeburn  10864:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10865: 	if ( callingForm.srchin[i].checked ) {
                   10866: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10867: 	}
                   10868:     }
                   10869: 
1.570     raeburn  10870:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10871:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10872:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10873:     var srchterm =  callingForm.srchterm.value;
                   10874:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10875:     var msg = "";
                   10876: 
                   10877:     if (srchterm == "") {
                   10878:         checkok = 0;
1.1222    damieng  10879:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10880:     }
                   10881: 
1.569     raeburn  10882:     if (srchtype== 'begins') {
                   10883:         if (srchterm.length < 2) {
                   10884:             checkok = 0;
1.1222    damieng  10885:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10886:         }
                   10887:     }
                   10888: 
1.556     raeburn  10889:     if (srchtype== 'contains') {
                   10890:         if (srchterm.length < 3) {
                   10891:             checkok = 0;
1.1222    damieng  10892:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10893:         }
                   10894:     }
                   10895:     if (srchin == 'instd') {
                   10896:         if (srchdomain == '') {
                   10897:             checkok = 0;
1.1222    damieng  10898:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10899:         }
                   10900:     }
                   10901:     if (srchin == 'dom') {
                   10902:         if (srchdomain == '') {
                   10903:             checkok = 0;
1.1222    damieng  10904:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10905:         }
                   10906:     }
                   10907:     if (srchby == 'lastfirst') {
                   10908:         if (srchterm.indexOf(",") == -1) {
                   10909:             checkok = 0;
1.1222    damieng  10910:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10911:         }
                   10912:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10913:             checkok = 0;
1.1222    damieng  10914:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10915:         }
                   10916:     }
                   10917:     if (checkok == 0) {
1.1222    damieng  10918:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10919:         return;
                   10920:     }
                   10921:     if (checkok == 1) {
1.570     raeburn  10922:         callingForm.submit();
1.556     raeburn  10923:     }
                   10924: }
                   10925: 
                   10926: $newuserscript
                   10927: 
1.824     bisitz   10928: // ]]>
1.556     raeburn  10929: </script>
1.558     albertel 10930: 
                   10931: $new_user_create
                   10932: 
1.555     raeburn  10933: END_BLOCK
1.558     albertel 10934: 
1.876     raeburn  10935:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10936:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10937:                $domform.
                   10938:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10939:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10940:                $srchbysel.
                   10941:                $srchtypesel. 
                   10942:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10943:                $srchinsel.
                   10944:                &Apache::lonhtmlcommon::row_closure(1). 
                   10945:                &Apache::lonhtmlcommon::end_pick_box().
                   10946:                '<br />';
1.1253    raeburn  10947:     return ($output,1);
1.555     raeburn  10948: }
                   10949: 
1.612     raeburn  10950: sub user_rule_check {
1.615     raeburn  10951:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10952:     my ($response,%inst_response);
1.612     raeburn  10953:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10954:         if (keys(%{$usershash}) > 1) {
                   10955:             my (%by_username,%by_id,%userdoms);
                   10956:             my $checkid; 
                   10957:             if (ref($checks) eq 'HASH') {
                   10958:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10959:                     $checkid = 1;
                   10960:                 }
                   10961:             }
                   10962:             foreach my $user (keys(%{$usershash})) {
                   10963:                 my ($uname,$udom) = split(/:/,$user);
                   10964:                 if ($checkid) {
                   10965:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10966:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10967:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10968:                             $userdoms{$udom} = 1;
1.1227    raeburn  10969:                             if (ref($inst_results) eq 'HASH') {
                   10970:                                 $inst_results->{$uname.':'.$udom} = {};
                   10971:                             }
1.1226    raeburn  10972:                         }
                   10973:                     }
                   10974:                 } else {
                   10975:                     $by_username{$udom}{$uname} = 1;
                   10976:                     $userdoms{$udom} = 1;
1.1227    raeburn  10977:                     if (ref($inst_results) eq 'HASH') {
                   10978:                         $inst_results->{$uname.':'.$udom} = {};
                   10979:                     }
1.1226    raeburn  10980:                 }
                   10981:             }
                   10982:             foreach my $udom (keys(%userdoms)) {
                   10983:                 if (!$got_rules->{$udom}) {
                   10984:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10985:                                                              ['usercreation'],$udom);
                   10986:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10987:                         foreach my $item ('username','id') {
                   10988:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10989:                                 $$curr_rules{$udom}{$item} =
                   10990:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10991:                             }
                   10992:                         }
                   10993:                     }
                   10994:                     $got_rules->{$udom} = 1;
                   10995:                 }
1.612     raeburn  10996:             }
1.1226    raeburn  10997:             if ($checkid) {
                   10998:                 foreach my $udom (keys(%by_id)) {
                   10999:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11000:                     if ($outcome eq 'ok') {
1.1227    raeburn  11001:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11002:                             my $uname = $by_id{$udom}{$id};
                   11003:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11004:                         }
1.1226    raeburn  11005:                         if (ref($results) eq 'HASH') {
                   11006:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11007:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11008:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11009:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11010:                                 }
1.1226    raeburn  11011:                             }
                   11012:                         }
                   11013:                     }
1.612     raeburn  11014:                 }
1.615     raeburn  11015:             } else {
1.1226    raeburn  11016:                 foreach my $udom (keys(%by_username)) {
                   11017:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11018:                     if ($outcome eq 'ok') {
1.1227    raeburn  11019:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11020:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11021:                         }
1.1226    raeburn  11022:                         if (ref($results) eq 'HASH') {
                   11023:                             foreach my $uname (keys(%{$results})) {
                   11024:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11025:                             }
                   11026:                         }
                   11027:                     }
                   11028:                 }
1.612     raeburn  11029:             }
1.1226    raeburn  11030:         } elsif (keys(%{$usershash}) == 1) {
                   11031:             my $user = (keys(%{$usershash}))[0];
                   11032:             my ($uname,$udom) = split(/:/,$user);
                   11033:             if (($udom ne '') && ($uname ne '')) {
                   11034:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11035:                     if (ref($checks) eq 'HASH') {
                   11036:                         if (defined($checks->{'username'})) {
                   11037:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11038:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11039:                         } elsif (defined($checks->{'id'})) {
                   11040:                             if ($usershash->{$user}->{'id'} ne '') {
                   11041:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11042:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11043:                                                                   $usershash->{$user}->{'id'});
                   11044:                             } else {
                   11045:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11046:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11047:                             }
1.585     raeburn  11048:                         }
1.1226    raeburn  11049:                     } else {
                   11050:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11051:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11052:                        return;
                   11053:                     }
                   11054:                     if (!$got_rules->{$udom}) {
                   11055:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11056:                                                                  ['usercreation'],$udom);
                   11057:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11058:                             foreach my $item ('username','id') {
                   11059:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11060:                                    $$curr_rules{$udom}{$item} = 
                   11061:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11062:                                 }
                   11063:                             }
                   11064:                         }
                   11065:                         $got_rules->{$udom} = 1;
1.585     raeburn  11066:                     }
                   11067:                 }
1.1226    raeburn  11068:             } else {
                   11069:                 return;
                   11070:             }
                   11071:         } else {
                   11072:             return;
                   11073:         }
                   11074:         foreach my $user (keys(%{$usershash})) {
                   11075:             my ($uname,$udom) = split(/:/,$user);
                   11076:             next if (($udom eq '') || ($uname eq ''));
                   11077:             my $id;
1.1227    raeburn  11078:             if (ref($inst_results) eq 'HASH') {
                   11079:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11080:                     $id = $inst_results->{$user}->{'id'};
                   11081:                 }
                   11082:             }
                   11083:             if ($id eq '') { 
                   11084:                 if (ref($usershash->{$user})) {
                   11085:                     $id = $usershash->{$user}->{'id'};
                   11086:                 }
1.585     raeburn  11087:             }
1.612     raeburn  11088:             foreach my $item (keys(%{$checks})) {
                   11089:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11090:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11091:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11092:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11093:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11094:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11095:                                 if ($rule_check{$rule}) {
                   11096:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11097:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11098:                                         if (ref($inst_results) eq 'HASH') {
                   11099:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11100:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11101:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11102:                                                 } elsif ($item eq 'id') {
                   11103:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11104:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11105:                                                     }
1.615     raeburn  11106:                                                 }
1.612     raeburn  11107:                                             }
                   11108:                                         }
1.615     raeburn  11109:                                     }
                   11110:                                     last;
1.585     raeburn  11111:                                 }
                   11112:                             }
                   11113:                         }
                   11114:                     }
                   11115:                 }
                   11116:             }
                   11117:         }
                   11118:     }
1.612     raeburn  11119:     return;
                   11120: }
                   11121: 
                   11122: sub user_rule_formats {
                   11123:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11124:     my %text = ( 
                   11125:                  'username' => 'Usernames',
                   11126:                  'id'       => 'IDs',
                   11127:                );
                   11128:     my $output;
                   11129:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11130:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11131:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11132:             $output = '<br />'.
                   11133:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11134:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11135:                       ' <ul>';
1.612     raeburn  11136:             foreach my $rule (@{$ruleorder}) {
                   11137:                 if (ref($curr_rules) eq 'ARRAY') {
                   11138:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11139:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11140:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11141:                                         $rules->{$rule}{'desc'}.'</li>';
                   11142:                         }
                   11143:                     }
                   11144:                 }
                   11145:             }
                   11146:             $output .= '</ul>';
                   11147:         }
                   11148:     }
                   11149:     return $output;
                   11150: }
                   11151: 
                   11152: sub instrule_disallow_msg {
1.615     raeburn  11153:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11154:     my $response;
                   11155:     my %text = (
                   11156:                   item   => 'username',
                   11157:                   items  => 'usernames',
                   11158:                   match  => 'matches',
                   11159:                   do     => 'does',
                   11160:                   action => 'a username',
                   11161:                   one    => 'one',
                   11162:                );
                   11163:     if ($count > 1) {
                   11164:         $text{'item'} = 'usernames';
                   11165:         $text{'match'} ='match';
                   11166:         $text{'do'} = 'do';
                   11167:         $text{'action'} = 'usernames',
                   11168:         $text{'one'} = 'ones';
                   11169:     }
                   11170:     if ($checkitem eq 'id') {
                   11171:         $text{'items'} = 'IDs';
                   11172:         $text{'item'} = 'ID';
                   11173:         $text{'action'} = 'an ID';
1.615     raeburn  11174:         if ($count > 1) {
                   11175:             $text{'item'} = 'IDs';
                   11176:             $text{'action'} = 'IDs';
                   11177:         }
1.612     raeburn  11178:     }
1.674     bisitz   11179:     $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  11180:     if ($mode eq 'upload') {
                   11181:         if ($checkitem eq 'username') {
                   11182:             $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'}.");
                   11183:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11184:             $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  11185:         }
1.669     raeburn  11186:     } elsif ($mode eq 'selfcreate') {
                   11187:         if ($checkitem eq 'id') {
                   11188:             $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.");
                   11189:         }
1.615     raeburn  11190:     } else {
                   11191:         if ($checkitem eq 'username') {
                   11192:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11193:         } elsif ($checkitem eq 'id') {
                   11194:             $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.");
                   11195:         }
1.612     raeburn  11196:     }
                   11197:     return $response;
1.585     raeburn  11198: }
                   11199: 
1.624     raeburn  11200: sub personal_data_fieldtitles {
                   11201:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11202:                         id => 'Student/Employee ID',
                   11203:                         permanentemail => 'E-mail address',
                   11204:                         lastname => 'Last Name',
                   11205:                         firstname => 'First Name',
                   11206:                         middlename => 'Middle Name',
                   11207:                         generation => 'Generation',
                   11208:                         gen => 'Generation',
1.765     raeburn  11209:                         inststatus => 'Affiliation',
1.624     raeburn  11210:                    );
                   11211:     return %fieldtitles;
                   11212: }
                   11213: 
1.642     raeburn  11214: sub sorted_inst_types {
                   11215:     my ($dom) = @_;
1.1185    raeburn  11216:     my ($usertypes,$order);
                   11217:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11218:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11219:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11220:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11221:     } else {
                   11222:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11223:     }
1.642     raeburn  11224:     my $othertitle = &mt('All users');
                   11225:     if ($env{'request.course.id'}) {
1.668     raeburn  11226:         $othertitle  = &mt('Any users');
1.642     raeburn  11227:     }
                   11228:     my @types;
                   11229:     if (ref($order) eq 'ARRAY') {
                   11230:         @types = @{$order};
                   11231:     }
                   11232:     if (@types == 0) {
                   11233:         if (ref($usertypes) eq 'HASH') {
                   11234:             @types = sort(keys(%{$usertypes}));
                   11235:         }
                   11236:     }
                   11237:     if (keys(%{$usertypes}) > 0) {
                   11238:         $othertitle = &mt('Other users');
                   11239:     }
                   11240:     return ($othertitle,$usertypes,\@types);
                   11241: }
                   11242: 
1.645     raeburn  11243: sub get_institutional_codes {
1.1361    raeburn  11244:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11245: # Get complete list of course sections to update
                   11246:     my @currsections = ();
                   11247:     my @currxlists = ();
1.1361    raeburn  11248:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11249:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11250:     my $crskey = $crs.':'.$coursecode;
                   11251:     @{$unclutteredsec{$crskey}} = ();
                   11252:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11253: 
                   11254:     if ($$settings{'internal.sectionnums'} ne '') {
                   11255:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11256:     }
                   11257: 
                   11258:     if ($$settings{'internal.crosslistings'} ne '') {
                   11259:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11260:     }
                   11261: 
                   11262:     if (@currxlists > 0) {
1.1361    raeburn  11263:         foreach my $xl (@currxlists) {
                   11264:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11265:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11266:                     push(@{$allcourses},$1);
1.645     raeburn  11267:                     $$LC_code{$1} = $2;
                   11268:                 }
                   11269:             }
                   11270:         }
                   11271:     }
1.1361    raeburn  11272: 
1.645     raeburn  11273:     if (@currsections > 0) {
1.1361    raeburn  11274:         foreach my $sec (@currsections) {
                   11275:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11276:                 my $instsec = $1;
1.645     raeburn  11277:                 my $lc_sec = $2;
1.1361    raeburn  11278:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11279:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11280:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11281:                 }
                   11282:             }
                   11283:         }
                   11284:     }
                   11285: 
                   11286:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11287:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11288:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11289:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11290:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11291:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11292:                     push(@{$allcourses},$sec);
1.1361    raeburn  11293:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11294:                 }
                   11295:             }
                   11296:         }
                   11297:     }
                   11298:     return;
                   11299: }
                   11300: 
1.971     raeburn  11301: sub get_standard_codeitems {
                   11302:     return ('Year','Semester','Department','Number','Section');
                   11303: }
                   11304: 
1.112     bowersj2 11305: =pod
                   11306: 
1.780     raeburn  11307: =head1 Slot Helpers
                   11308: 
                   11309: =over 4
                   11310: 
                   11311: =item * sorted_slots()
                   11312: 
1.1040    raeburn  11313: Sorts an array of slot names in order of an optional sort key,
                   11314: default sort is by slot start time (earliest first). 
1.780     raeburn  11315: 
                   11316: Inputs:
                   11317: 
                   11318: =over 4
                   11319: 
                   11320: slotsarr  - Reference to array of unsorted slot names.
                   11321: 
                   11322: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11323: 
1.1040    raeburn  11324: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11325: 
1.549     albertel 11326: =back
                   11327: 
1.780     raeburn  11328: Returns:
                   11329: 
                   11330: =over 4
                   11331: 
1.1040    raeburn  11332: sorted   - An array of slot names sorted by a specified sort key 
                   11333:            (default sort key is start time of the slot).
1.780     raeburn  11334: 
                   11335: =back
                   11336: 
                   11337: =cut
                   11338: 
                   11339: 
                   11340: sub sorted_slots {
1.1040    raeburn  11341:     my ($slotsarr,$slots,$sortkey) = @_;
                   11342:     if ($sortkey eq '') {
                   11343:         $sortkey = 'starttime';
                   11344:     }
1.780     raeburn  11345:     my @sorted;
                   11346:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11347:         @sorted =
                   11348:             sort {
                   11349:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11350:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11351:                      }
                   11352:                      if (ref($slots->{$a})) { return -1;}
                   11353:                      if (ref($slots->{$b})) { return 1;}
                   11354:                      return 0;
                   11355:                  } @{$slotsarr};
                   11356:     }
                   11357:     return @sorted;
                   11358: }
                   11359: 
1.1040    raeburn  11360: =pod
                   11361: 
                   11362: =item * get_future_slots()
                   11363: 
                   11364: Inputs:
                   11365: 
                   11366: =over 4
                   11367: 
                   11368: cnum - course number
                   11369: 
                   11370: cdom - course domain
                   11371: 
                   11372: now - current UNIX time
                   11373: 
                   11374: symb - optional symb
                   11375: 
                   11376: =back
                   11377: 
                   11378: Returns:
                   11379: 
                   11380: =over 4
                   11381: 
                   11382: sorted_reservable - ref to array of student_schedulable slots currently 
                   11383:                     reservable, ordered by end date of reservation period.
                   11384: 
                   11385: reservable_now - ref to hash of student_schedulable slots currently
                   11386:                  reservable.
                   11387: 
                   11388:     Keys in inner hash are:
                   11389:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11390:     (b) endreserve: end date of reservation period.
                   11391:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11392:         selected.
1.1040    raeburn  11393: 
                   11394: sorted_future - ref to array of student_schedulable slots reservable in
                   11395:                 the future, ordered by start date of reservation period.
                   11396: 
                   11397: future_reservable - ref to hash of student_schedulable slots reservable
                   11398:                     in the future.
                   11399: 
                   11400:     Keys in inner hash are:
                   11401:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11402:     (b) startreserve: start date of reservation period.
                   11403:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11404:         selected.
1.1040    raeburn  11405: 
                   11406: =back
                   11407: 
                   11408: =cut
                   11409: 
                   11410: sub get_future_slots {
                   11411:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11412:     my $map;
                   11413:     if ($symb) {
                   11414:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11415:     }
1.1040    raeburn  11416:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11417:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11418:     foreach my $slot (keys(%slots)) {
                   11419:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11420:         if ($symb) {
1.1229    raeburn  11421:             if ($slots{$slot}->{'symb'} ne '') {
                   11422:                 my $canuse;
                   11423:                 my %oksymbs;
                   11424:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11425:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11426:                 if ($oksymbs{$symb}) {
                   11427:                     $canuse = 1;
                   11428:                 } else {
                   11429:                     foreach my $item (@slotsymbs) {
                   11430:                         if ($item =~ /\.(page|sequence)$/) {
                   11431:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11432:                             if (($map ne '') && ($map eq $sloturl)) {
                   11433:                                 $canuse = 1;
                   11434:                                 last;
                   11435:                             }
                   11436:                         }
                   11437:                     }
                   11438:                 }
                   11439:                 next unless ($canuse);
                   11440:             }
1.1040    raeburn  11441:         }
                   11442:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11443:             ($slots{$slot}->{'endtime'} > $now)) {
                   11444:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11445:                 my $userallowed = 0;
                   11446:                 if ($slots{$slot}->{'allowedsections'}) {
                   11447:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11448:                     if (!defined($env{'request.role.sec'})
                   11449:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11450:                         $userallowed=1;
                   11451:                     } else {
                   11452:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11453:                             $userallowed=1;
                   11454:                         }
                   11455:                     }
                   11456:                     unless ($userallowed) {
                   11457:                         if (defined($env{'request.course.groups'})) {
                   11458:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11459:                             foreach my $group (@groups) {
                   11460:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11461:                                     $userallowed=1;
                   11462:                                     last;
                   11463:                                 }
                   11464:                             }
                   11465:                         }
                   11466:                     }
                   11467:                 }
                   11468:                 if ($slots{$slot}->{'allowedusers'}) {
                   11469:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11470:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11471:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11472:                         $userallowed = 1;
                   11473:                     }
                   11474:                 }
                   11475:                 next unless($userallowed);
                   11476:             }
                   11477:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11478:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11479:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11480:             my $uniqueperiod;
                   11481:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11482:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11483:             }
1.1040    raeburn  11484:             if (($startreserve < $now) &&
                   11485:                 (!$endreserve || $endreserve > $now)) {
                   11486:                 my $lastres = $endreserve;
                   11487:                 if (!$lastres) {
                   11488:                     $lastres = $slots{$slot}->{'starttime'};
                   11489:                 }
                   11490:                 $reservable_now{$slot} = {
                   11491:                                            symb       => $symb,
1.1250    raeburn  11492:                                            endreserve => $lastres,
                   11493:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11494:                                          };
                   11495:             } elsif (($startreserve > $now) &&
                   11496:                      (!$endreserve || $endreserve > $startreserve)) {
                   11497:                 $future_reservable{$slot} = {
                   11498:                                               symb         => $symb,
1.1250    raeburn  11499:                                               startreserve => $startreserve,
                   11500:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11501:                                             };
                   11502:             }
                   11503:         }
                   11504:     }
                   11505:     my @unsorted_reservable = keys(%reservable_now);
                   11506:     if (@unsorted_reservable > 0) {
                   11507:         @sorted_reservable = 
                   11508:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11509:     }
                   11510:     my @unsorted_future = keys(%future_reservable);
                   11511:     if (@unsorted_future > 0) {
                   11512:         @sorted_future =
                   11513:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11514:     }
                   11515:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11516: }
1.780     raeburn  11517: 
                   11518: =pod
                   11519: 
1.1057    foxr     11520: =back
                   11521: 
1.549     albertel 11522: =head1 HTTP Helpers
                   11523: 
                   11524: =over 4
                   11525: 
1.648     raeburn  11526: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11527: 
1.258     albertel 11528: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11529: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11530: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11531: 
                   11532: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11533: $possible_names is an ref to an array of form element names.  As an example:
                   11534: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11535: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11536: 
                   11537: =cut
1.1       albertel 11538: 
1.6       albertel 11539: sub get_unprocessed_cgi {
1.25      albertel 11540:   my ($query,$possible_names)= @_;
1.26      matthew  11541:   # $Apache::lonxml::debug=1;
1.356     albertel 11542:   foreach my $pair (split(/&/,$query)) {
                   11543:     my ($name, $value) = split(/=/,$pair);
1.369     www      11544:     $name = &unescape($name);
1.25      albertel 11545:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11546:       $value =~ tr/+/ /;
                   11547:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11548:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11549:     }
1.16      harris41 11550:   }
1.6       albertel 11551: }
                   11552: 
1.112     bowersj2 11553: =pod
                   11554: 
1.648     raeburn  11555: =item * &cacheheader() 
1.112     bowersj2 11556: 
                   11557: returns cache-controlling header code
                   11558: 
                   11559: =cut
                   11560: 
1.7       albertel 11561: sub cacheheader {
1.258     albertel 11562:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11563:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11564:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11565:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11566:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11567:     return $output;
1.7       albertel 11568: }
                   11569: 
1.112     bowersj2 11570: =pod
                   11571: 
1.648     raeburn  11572: =item * &no_cache($r) 
1.112     bowersj2 11573: 
                   11574: specifies header code to not have cache
                   11575: 
                   11576: =cut
                   11577: 
1.9       albertel 11578: sub no_cache {
1.216     albertel 11579:     my ($r) = @_;
                   11580:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11581: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11582:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11583:     $r->no_cache(1);
                   11584:     $r->header_out("Expires" => $date);
                   11585:     $r->header_out("Pragma" => "no-cache");
1.123     www      11586: }
                   11587: 
                   11588: sub content_type {
1.181     albertel 11589:     my ($r,$type,$charset) = @_;
1.299     foxr     11590:     if ($r) {
                   11591: 	#  Note that printout.pl calls this with undef for $r.
                   11592: 	&no_cache($r);
                   11593:     }
1.258     albertel 11594:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11595:     unless ($charset) {
                   11596: 	$charset=&Apache::lonlocal::current_encoding;
                   11597:     }
                   11598:     if ($charset) { $type.='; charset='.$charset; }
                   11599:     if ($r) {
                   11600: 	$r->content_type($type);
                   11601:     } else {
                   11602: 	print("Content-type: $type\n\n");
                   11603:     }
1.9       albertel 11604: }
1.25      albertel 11605: 
1.112     bowersj2 11606: =pod
                   11607: 
1.648     raeburn  11608: =item * &add_to_env($name,$value) 
1.112     bowersj2 11609: 
1.258     albertel 11610: adds $name to the %env hash with value
1.112     bowersj2 11611: $value, if $name already exists, the entry is converted to an array
                   11612: reference and $value is added to the array.
                   11613: 
                   11614: =cut
                   11615: 
1.25      albertel 11616: sub add_to_env {
                   11617:   my ($name,$value)=@_;
1.258     albertel 11618:   if (defined($env{$name})) {
                   11619:     if (ref($env{$name})) {
1.25      albertel 11620:       #already have multiple values
1.258     albertel 11621:       push(@{ $env{$name} },$value);
1.25      albertel 11622:     } else {
                   11623:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11624:       my $first=$env{$name};
                   11625:       undef($env{$name});
                   11626:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11627:     }
                   11628:   } else {
1.258     albertel 11629:     $env{$name}=$value;
1.25      albertel 11630:   }
1.31      albertel 11631: }
1.149     albertel 11632: 
                   11633: =pod
                   11634: 
1.648     raeburn  11635: =item * &get_env_multiple($name) 
1.149     albertel 11636: 
1.258     albertel 11637: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11638: values may be defined and end up as an array ref.
                   11639: 
                   11640: returns an array of values
                   11641: 
                   11642: =cut
                   11643: 
                   11644: sub get_env_multiple {
                   11645:     my ($name) = @_;
                   11646:     my @values;
1.258     albertel 11647:     if (defined($env{$name})) {
1.149     albertel 11648:         # exists is it an array
1.258     albertel 11649:         if (ref($env{$name})) {
                   11650:             @values=@{ $env{$name} };
1.149     albertel 11651:         } else {
1.258     albertel 11652:             $values[0]=$env{$name};
1.149     albertel 11653:         }
                   11654:     }
                   11655:     return(@values);
                   11656: }
                   11657: 
1.1249    damieng  11658: # Looks at given dependencies, and returns something depending on the context.
                   11659: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11660: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11661: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11662: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11663: # $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.
                   11664: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11665: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11666: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11667: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11668: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11669: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11670: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11671: # @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)
                   11672: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11673: sub ask_for_embedded_content {
1.1249    damieng  11674:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11675:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11676:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11677:         %currsubfile,%unused,$rem);
1.1071    raeburn  11678:     my $counter = 0;
                   11679:     my $numnew = 0;
1.987     raeburn  11680:     my $numremref = 0;
                   11681:     my $numinvalid = 0;
                   11682:     my $numpathchg = 0;
                   11683:     my $numexisting = 0;
1.1071    raeburn  11684:     my $numunused = 0;
                   11685:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11686:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11687:     my $heading = &mt('Upload embedded files');
                   11688:     my $buttontext = &mt('Upload');
                   11689: 
1.1249    damieng  11690:     # fills these variables based on the context:
                   11691:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11692:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11693:     if ($env{'request.course.id'}) {
1.1123    raeburn  11694:         if ($actionurl eq '/adm/dependencies') {
                   11695:             $navmap = Apache::lonnavmaps::navmap->new();
                   11696:         }
                   11697:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11698:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11699:     }
1.1123    raeburn  11700:     if (($actionurl eq '/adm/portfolio') || 
                   11701:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11702:         my $current_path='/';
                   11703:         if ($env{'form.currentpath'}) {
                   11704:             $current_path = $env{'form.currentpath'};
                   11705:         }
                   11706:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11707:             $udom = $cdom;
                   11708:             $uname = $cnum;
1.984     raeburn  11709:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11710:         } else {
                   11711:             $udom = $env{'user.domain'};
                   11712:             $uname = $env{'user.name'};
                   11713:             $url = '/userfiles/portfolio';
                   11714:         }
1.987     raeburn  11715:         $toplevel = $url.'/';
1.984     raeburn  11716:         $url .= $current_path;
                   11717:         $getpropath = 1;
1.987     raeburn  11718:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11719:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11720:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11721:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11722:         $toplevel = $url;
1.984     raeburn  11723:         if ($rest ne '') {
1.987     raeburn  11724:             $url .= $rest;
                   11725:         }
                   11726:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11727:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11728:             $url = $args->{'docs_url'};
                   11729:             $toplevel = $url;
1.1084    raeburn  11730:             if ($args->{'context'} eq 'paste') {
                   11731:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11732:                 ($path) = 
                   11733:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11734:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11735:                 $fileloc =~ s{^/}{};
                   11736:             }
1.1071    raeburn  11737:         }
1.1084    raeburn  11738:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11739:         if ($env{'request.course.id'} ne '') {
                   11740:             if (ref($args) eq 'HASH') {
                   11741:                 $url = $args->{'docs_url'};
                   11742:                 $title = $args->{'docs_title'};
1.1126    raeburn  11743:                 $toplevel = $url; 
                   11744:                 unless ($toplevel =~ m{^/}) {
                   11745:                     $toplevel = "/$url";
                   11746:                 }
1.1085    raeburn  11747:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11748:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11749:                     $path = $1;
                   11750:                 } else {
                   11751:                     ($path) =
                   11752:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11753:                 }
1.1195    raeburn  11754:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11755:                     $fileloc = $toplevel;
                   11756:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11757:                     my ($udom,$uname,$fname) =
                   11758:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11759:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11760:                 } else {
                   11761:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11762:                 }
1.1071    raeburn  11763:                 $fileloc =~ s{^/}{};
                   11764:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11765:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11766:             }
1.987     raeburn  11767:         }
1.1123    raeburn  11768:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11769:         $udom = $cdom;
                   11770:         $uname = $cnum;
                   11771:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11772:         $toplevel = $url;
                   11773:         $path = $url;
                   11774:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11775:         $fileloc =~ s{^/}{};
1.987     raeburn  11776:     }
1.1249    damieng  11777:     
                   11778:     # parses the dependency paths to get some info
                   11779:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11780:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11781:     # (will be completed later)
                   11782:     # $mapping:
                   11783:     #   for external URLs: external URL -> external URL
                   11784:     #   for relative paths: clean path -> original path
                   11785:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11786:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11787:     foreach my $file (keys(%{$allfiles})) {
                   11788:         my $embed_file;
                   11789:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11790:             $embed_file = $1;
                   11791:         } else {
                   11792:             $embed_file = $file;
                   11793:         }
1.1158    raeburn  11794:         my ($absolutepath,$cleaned_file);
                   11795:         if ($embed_file =~ m{^\w+://}) {
                   11796:             $cleaned_file = $embed_file;
1.1147    raeburn  11797:             $newfiles{$cleaned_file} = 1;
                   11798:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11799:         } else {
1.1158    raeburn  11800:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11801:             if ($embed_file =~ m{^/}) {
                   11802:                 $absolutepath = $embed_file;
                   11803:             }
1.1147    raeburn  11804:             if ($cleaned_file =~ m{/}) {
                   11805:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11806:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11807:                 my $item = $fname;
                   11808:                 if ($path ne '') {
                   11809:                     $item = $path.'/'.$fname;
                   11810:                     $subdependencies{$path}{$fname} = 1;
                   11811:                 } else {
                   11812:                     $dependencies{$item} = 1;
                   11813:                 }
                   11814:                 if ($absolutepath) {
                   11815:                     $mapping{$item} = $absolutepath;
                   11816:                 } else {
                   11817:                     $mapping{$item} = $embed_file;
                   11818:                 }
                   11819:             } else {
                   11820:                 $dependencies{$embed_file} = 1;
                   11821:                 if ($absolutepath) {
1.1147    raeburn  11822:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11823:                 } else {
1.1147    raeburn  11824:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11825:                 }
                   11826:             }
1.984     raeburn  11827:         }
                   11828:     }
1.1249    damieng  11829:     
                   11830:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11831:     # and lists
                   11832:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11833:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11834:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11835:     #                                    the path had to be cleaned up
                   11836:     # $existing: hash clean path -> 1 if the file exists
                   11837:     # $numexisting: number of keys in $existing
                   11838:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11839:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11840:     #                                      dependency subdirectories that are
                   11841:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11842:     my $dirptr = 16384;
1.984     raeburn  11843:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11844:         $currsubfile{$path} = {};
1.1123    raeburn  11845:         if (($actionurl eq '/adm/portfolio') || 
                   11846:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11847:             my ($sublistref,$listerror) =
                   11848:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11849:             if (ref($sublistref) eq 'ARRAY') {
                   11850:                 foreach my $line (@{$sublistref}) {
                   11851:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11852:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11853:                 }
1.984     raeburn  11854:             }
1.987     raeburn  11855:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11856:             if (opendir(my $dir,$url.'/'.$path)) {
                   11857:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11858:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11859:             }
1.1084    raeburn  11860:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11861:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11862:                   ($args->{'context'} eq 'paste')) ||
                   11863:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11864:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11865:                 my $dir;
                   11866:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11867:                     $dir = $fileloc;
                   11868:                 } else {
                   11869:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11870:                 }
1.1071    raeburn  11871:                 if ($dir ne '') {
                   11872:                     my ($sublistref,$listerror) =
                   11873:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11874:                     if (ref($sublistref) eq 'ARRAY') {
                   11875:                         foreach my $line (@{$sublistref}) {
                   11876:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11877:                                 undef,$mtime)=split(/\&/,$line,12);
                   11878:                             unless (($testdir&$dirptr) ||
                   11879:                                     ($file_name =~ /^\.\.?$/)) {
                   11880:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11881:                             }
                   11882:                         }
                   11883:                     }
                   11884:                 }
1.984     raeburn  11885:             }
                   11886:         }
                   11887:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11888:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11889:                 my $item = $path.'/'.$file;
                   11890:                 unless ($mapping{$item} eq $item) {
                   11891:                     $pathchanges{$item} = 1;
                   11892:                 }
                   11893:                 $existing{$item} = 1;
                   11894:                 $numexisting ++;
                   11895:             } else {
                   11896:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11897:             }
                   11898:         }
1.1071    raeburn  11899:         if ($actionurl eq '/adm/dependencies') {
                   11900:             foreach my $path (keys(%currsubfile)) {
                   11901:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11902:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11903:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11904:                              next if (($rem ne '') &&
                   11905:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11906:                                        (ref($navmap) &&
                   11907:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11908:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11909:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11910:                              $unused{$path.'/'.$file} = 1; 
                   11911:                          }
                   11912:                     }
                   11913:                 }
                   11914:             }
                   11915:         }
1.984     raeburn  11916:     }
1.1249    damieng  11917:     
                   11918:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11919:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11920:     my %currfile;
1.1123    raeburn  11921:     if (($actionurl eq '/adm/portfolio') ||
                   11922:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11923:         my ($dirlistref,$listerror) =
                   11924:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11925:         if (ref($dirlistref) eq 'ARRAY') {
                   11926:             foreach my $line (@{$dirlistref}) {
                   11927:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11928:                 $currfile{$file_name} = 1;
                   11929:             }
1.984     raeburn  11930:         }
1.987     raeburn  11931:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11932:         if (opendir(my $dir,$url)) {
1.987     raeburn  11933:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11934:             map {$currfile{$_} = 1;} @dir_list;
                   11935:         }
1.1084    raeburn  11936:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11937:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11938:               ($args->{'context'} eq 'paste')) ||
                   11939:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11940:         if ($env{'request.course.id'} ne '') {
                   11941:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11942:             if ($dir ne '') {
                   11943:                 my ($dirlistref,$listerror) =
                   11944:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11945:                 if (ref($dirlistref) eq 'ARRAY') {
                   11946:                     foreach my $line (@{$dirlistref}) {
                   11947:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11948:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11949:                         unless (($testdir&$dirptr) ||
                   11950:                                 ($file_name =~ /^\.\.?$/)) {
                   11951:                             $currfile{$file_name} = [$size,$mtime];
                   11952:                         }
                   11953:                     }
                   11954:                 }
                   11955:             }
                   11956:         }
1.984     raeburn  11957:     }
1.1249    damieng  11958:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11959:     # are not in subdirectories, using $currfile
1.984     raeburn  11960:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11961:         if (exists($currfile{$file})) {
1.987     raeburn  11962:             unless ($mapping{$file} eq $file) {
                   11963:                 $pathchanges{$file} = 1;
                   11964:             }
                   11965:             $existing{$file} = 1;
                   11966:             $numexisting ++;
                   11967:         } else {
1.984     raeburn  11968:             $newfiles{$file} = 1;
                   11969:         }
                   11970:     }
1.1071    raeburn  11971:     foreach my $file (keys(%currfile)) {
                   11972:         unless (($file eq $filename) ||
                   11973:                 ($file eq $filename.'.bak') ||
                   11974:                 ($dependencies{$file})) {
1.1085    raeburn  11975:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11976:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11977:                     next if (($rem ne '') &&
                   11978:                              (($env{"httpref.$rem".$file} ne '') ||
                   11979:                               (ref($navmap) &&
                   11980:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11981:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11982:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11983:                 }
1.1085    raeburn  11984:             }
1.1071    raeburn  11985:             $unused{$file} = 1;
                   11986:         }
                   11987:     }
1.1249    damieng  11988:     
                   11989:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11990:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11991:         ($args->{'context'} eq 'paste')) {
                   11992:         $counter = scalar(keys(%existing));
                   11993:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11994:         return ($output,$counter,$numpathchg,\%existing);
                   11995:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11996:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11997:         $counter = scalar(keys(%existing));
                   11998:         $numpathchg = scalar(keys(%pathchanges));
                   11999:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12000:     }
1.1249    damieng  12001:     
                   12002:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12003:     
                   12004:     # $upload_output: missing dependencies (with upload form)
                   12005:     # $modify_output: uploaded dependencies (in use)
                   12006:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12007:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12008:         if ($actionurl eq '/adm/dependencies') {
                   12009:             next if ($embed_file =~ m{^\w+://});
                   12010:         }
1.660     raeburn  12011:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12012:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12013:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12014:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12015:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12016:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12017:         }
1.1123    raeburn  12018:         $upload_output .= '</td>';
1.1071    raeburn  12019:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12020:             $upload_output.='<td align="right">'.
                   12021:                             '<span class="LC_info LC_fontsize_medium">'.
                   12022:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12023:             $numremref++;
1.660     raeburn  12024:         } elsif ($args->{'error_on_invalid_names'}
                   12025:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12026:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12027:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12028:             $numinvalid++;
1.660     raeburn  12029:         } else {
1.1123    raeburn  12030:             $upload_output .= '<td>'.
                   12031:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12032:                                                      $embed_file,\%mapping,
1.1071    raeburn  12033:                                                      $allfiles,$codebase,'upload');
                   12034:             $counter ++;
                   12035:             $numnew ++;
1.987     raeburn  12036:         }
                   12037:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12038:     }
                   12039:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12040:         if ($actionurl eq '/adm/dependencies') {
                   12041:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12042:             $modify_output .= &start_data_table_row().
                   12043:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12044:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12045:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12046:                               '<td>'.$size.'</td>'.
                   12047:                               '<td>'.$mtime.'</td>'.
                   12048:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12049:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12050:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12051:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12052:                               &embedded_file_element('upload_embedded',$counter,
                   12053:                                                      $embed_file,\%mapping,
                   12054:                                                      $allfiles,$codebase,'modify').
                   12055:                               '</div></td>'.
                   12056:                               &end_data_table_row()."\n";
                   12057:             $counter ++;
                   12058:         } else {
                   12059:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12060:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12061:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12062:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12063:                               &Apache::loncommon::end_data_table_row()."\n";
                   12064:         }
                   12065:     }
                   12066:     my $delidx = $counter;
                   12067:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12068:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12069:         $delete_output .= &start_data_table_row().
                   12070:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12071:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12072:                           '<td>'.$size.'</td>'.
                   12073:                           '<td>'.$mtime.'</td>'.
                   12074:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12075:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12076:                           &embedded_file_element('upload_embedded',$delidx,
                   12077:                                                  $oldfile,\%mapping,$allfiles,
                   12078:                                                  $codebase,'delete').'</td>'.
                   12079:                           &end_data_table_row()."\n"; 
                   12080:         $numunused ++;
                   12081:         $delidx ++;
1.987     raeburn  12082:     }
                   12083:     if ($upload_output) {
                   12084:         $upload_output = &start_data_table().
                   12085:                          $upload_output.
                   12086:                          &end_data_table()."\n";
                   12087:     }
1.1071    raeburn  12088:     if ($modify_output) {
                   12089:         $modify_output = &start_data_table().
                   12090:                          &start_data_table_header_row().
                   12091:                          '<th>'.&mt('File').'</th>'.
                   12092:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12093:                          '<th>'.&mt('Modified').'</th>'.
                   12094:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12095:                          &end_data_table_header_row().
                   12096:                          $modify_output.
                   12097:                          &end_data_table()."\n";
                   12098:     }
                   12099:     if ($delete_output) {
                   12100:         $delete_output = &start_data_table().
                   12101:                          &start_data_table_header_row().
                   12102:                          '<th>'.&mt('File').'</th>'.
                   12103:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12104:                          '<th>'.&mt('Modified').'</th>'.
                   12105:                          '<th>'.&mt('Delete?').'</th>'.
                   12106:                          &end_data_table_header_row().
                   12107:                          $delete_output.
                   12108:                          &end_data_table()."\n";
                   12109:     }
1.987     raeburn  12110:     my $applies = 0;
                   12111:     if ($numremref) {
                   12112:         $applies ++;
                   12113:     }
                   12114:     if ($numinvalid) {
                   12115:         $applies ++;
                   12116:     }
                   12117:     if ($numexisting) {
                   12118:         $applies ++;
                   12119:     }
1.1071    raeburn  12120:     if ($counter || $numunused) {
1.987     raeburn  12121:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12122:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12123:                   $state.'<h3>'.$heading.'</h3>'; 
                   12124:         if ($actionurl eq '/adm/dependencies') {
                   12125:             if ($numnew) {
                   12126:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12127:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12128:                            $upload_output.'<br />'."\n";
                   12129:             }
                   12130:             if ($numexisting) {
                   12131:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12132:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12133:                            $modify_output.'<br />'."\n";
                   12134:                            $buttontext = &mt('Save changes');
                   12135:             }
                   12136:             if ($numunused) {
                   12137:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12138:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12139:                            $delete_output.'<br />'."\n";
                   12140:                            $buttontext = &mt('Save changes');
                   12141:             }
                   12142:         } else {
                   12143:             $output .= $upload_output.'<br />'."\n";
                   12144:         }
                   12145:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12146:                    $counter.'" />'."\n";
                   12147:         if ($actionurl eq '/adm/dependencies') { 
                   12148:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12149:                        $numnew.'" />'."\n";
                   12150:         } elsif ($actionurl eq '') {
1.987     raeburn  12151:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12152:         }
                   12153:     } elsif ($applies) {
                   12154:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12155:         if ($applies > 1) {
                   12156:             $output .=  
1.1123    raeburn  12157:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12158:             if ($numremref) {
                   12159:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12160:             }
                   12161:             if ($numinvalid) {
                   12162:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12163:             }
                   12164:             if ($numexisting) {
                   12165:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12166:             }
                   12167:             $output .= '</ul><br />';
                   12168:         } elsif ($numremref) {
                   12169:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12170:         } elsif ($numinvalid) {
                   12171:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12172:         } elsif ($numexisting) {
                   12173:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12174:         }
                   12175:         $output .= $upload_output.'<br />';
                   12176:     }
                   12177:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12178:     $chgcount = $counter;
1.987     raeburn  12179:     if (keys(%pathchanges) > 0) {
                   12180:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12181:             if ($counter) {
1.987     raeburn  12182:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12183:                                                   $embed_file,\%mapping,
1.1071    raeburn  12184:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12185:             } else {
                   12186:                 $pathchange_output .= 
                   12187:                     &start_data_table_row().
                   12188:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12189:                     $chgcount.'" checked="checked" /></td>'.
                   12190:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12191:                     '<td>'.$embed_file.
                   12192:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12193:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12194:                     '</td>'.&end_data_table_row();
1.660     raeburn  12195:             }
1.987     raeburn  12196:             $numpathchg ++;
                   12197:             $chgcount ++;
1.660     raeburn  12198:         }
                   12199:     }
1.1127    raeburn  12200:     if (($counter) || ($numunused)) {
1.987     raeburn  12201:         if ($numpathchg) {
                   12202:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12203:                        $numpathchg.'" />'."\n";
                   12204:         }
                   12205:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12206:             ($actionurl eq '/adm/imsimport')) {
                   12207:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12208:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12209:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12210:         } elsif ($actionurl eq '/adm/dependencies') {
                   12211:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12212:         }
1.1123    raeburn  12213:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12214:     } elsif ($numpathchg) {
                   12215:         my %pathchange = ();
                   12216:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12217:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12218:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12219:         }
1.987     raeburn  12220:     }
1.1071    raeburn  12221:     return ($output,$counter,$numpathchg);
1.987     raeburn  12222: }
                   12223: 
1.1147    raeburn  12224: =pod
                   12225: 
                   12226: =item * clean_path($name)
                   12227: 
                   12228: Performs clean-up of directories, subdirectories and filename in an
                   12229: embedded object, referenced in an HTML file which is being uploaded
                   12230: to a course or portfolio, where 
                   12231: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12232: checked.
                   12233: 
                   12234: Clean-up is similar to replacements in lonnet::clean_filename()
                   12235: except each / between sub-directory and next level is preserved.
                   12236: 
                   12237: =cut
                   12238: 
                   12239: sub clean_path {
                   12240:     my ($embed_file) = @_;
                   12241:     $embed_file =~s{^/+}{};
                   12242:     my @contents;
                   12243:     if ($embed_file =~ m{/}) {
                   12244:         @contents = split(/\//,$embed_file);
                   12245:     } else {
                   12246:         @contents = ($embed_file);
                   12247:     }
                   12248:     my $lastidx = scalar(@contents)-1;
                   12249:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12250:         $contents[$i]=~s{\\}{/}g;
                   12251:         $contents[$i]=~s/\s+/\_/g;
                   12252:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12253:         if ($i == $lastidx) {
                   12254:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12255:         }
                   12256:     }
                   12257:     if ($lastidx > 0) {
                   12258:         return join('/',@contents);
                   12259:     } else {
                   12260:         return $contents[0];
                   12261:     }
                   12262: }
                   12263: 
1.987     raeburn  12264: sub embedded_file_element {
1.1071    raeburn  12265:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12266:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12267:                    (ref($codebase) eq 'HASH'));
                   12268:     my $output;
1.1071    raeburn  12269:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12270:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12271:     }
                   12272:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12273:                &escape($embed_file).'" />';
                   12274:     unless (($context eq 'upload_embedded') && 
                   12275:             ($mapping->{$embed_file} eq $embed_file)) {
                   12276:         $output .='
                   12277:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12278:     }
                   12279:     my $attrib;
                   12280:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12281:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12282:     }
                   12283:     $output .=
                   12284:         "\n\t\t".
                   12285:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12286:         $attrib.'" />';
                   12287:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12288:         $output .=
                   12289:             "\n\t\t".
                   12290:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12291:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12292:     }
1.987     raeburn  12293:     return $output;
1.660     raeburn  12294: }
                   12295: 
1.1071    raeburn  12296: sub get_dependency_details {
                   12297:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12298:     my ($size,$mtime,$showsize,$showmtime);
                   12299:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12300:         if ($embed_file =~ m{/}) {
                   12301:             my ($path,$fname) = split(/\//,$embed_file);
                   12302:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12303:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12304:             }
                   12305:         } else {
                   12306:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12307:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12308:             }
                   12309:         }
                   12310:         $showsize = $size/1024.0;
                   12311:         $showsize = sprintf("%.1f",$showsize);
                   12312:         if ($mtime > 0) {
                   12313:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12314:         }
                   12315:     }
                   12316:     return ($showsize,$showmtime);
                   12317: }
                   12318: 
                   12319: sub ask_embedded_js {
                   12320:     return <<"END";
                   12321: <script type="text/javascript"">
                   12322: // <![CDATA[
                   12323: function toggleBrowse(counter) {
                   12324:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12325:     var fileid = document.getElementById('embedded_item_'+counter);
                   12326:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12327:     if (chkboxid.checked == true) {
                   12328:         uploaddivid.style.display='block';
                   12329:     } else {
                   12330:         uploaddivid.style.display='none';
                   12331:         fileid.value = '';
                   12332:     }
                   12333: }
                   12334: // ]]>
                   12335: </script>
                   12336: 
                   12337: END
                   12338: }
                   12339: 
1.661     raeburn  12340: sub upload_embedded {
                   12341:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12342:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12343:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12344:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12345:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12346:         my $orig_uploaded_filename =
                   12347:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12348:         foreach my $type ('orig','ref','attrib','codebase') {
                   12349:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12350:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12351:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12352:             }
                   12353:         }
1.661     raeburn  12354:         my ($path,$fname) =
                   12355:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12356:         # no path, whole string is fname
                   12357:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12358:         $fname = &Apache::lonnet::clean_filename($fname);
                   12359:         # See if there is anything left
                   12360:         next if ($fname eq '');
                   12361: 
                   12362:         # Check if file already exists as a file or directory.
                   12363:         my ($state,$msg);
                   12364:         if ($context eq 'portfolio') {
                   12365:             my $port_path = $dirpath;
                   12366:             if ($group ne '') {
                   12367:                 $port_path = "groups/$group/$port_path";
                   12368:             }
1.987     raeburn  12369:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12370:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12371:                                               $dir_root,$port_path,$disk_quota,
                   12372:                                               $current_disk_usage,$uname,$udom);
                   12373:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12374:                 || $state eq 'file_locked') {
1.661     raeburn  12375:                 $output .= $msg;
                   12376:                 next;
                   12377:             }
                   12378:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12379:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12380:             if ($state eq 'exists') {
                   12381:                 $output .= $msg;
                   12382:                 next;
                   12383:             }
                   12384:         }
                   12385:         # Check if extension is valid
                   12386:         if (($fname =~ /\.(\w+)$/) &&
                   12387:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12388:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12389:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12390:             next;
                   12391:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12392:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12393:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12394:             next;
                   12395:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12396:             $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  12397:             next;
                   12398:         }
                   12399:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12400:         my $subdir = $path;
                   12401:         $subdir =~ s{/+$}{};
1.661     raeburn  12402:         if ($context eq 'portfolio') {
1.984     raeburn  12403:             my $result;
                   12404:             if ($state eq 'existingfile') {
                   12405:                 $result=
                   12406:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12407:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12408:             } else {
1.984     raeburn  12409:                 $result=
                   12410:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12411:                                                     $dirpath.
1.1123    raeburn  12412:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12413:                 if ($result !~ m|^/uploaded/|) {
                   12414:                     $output .= '<span class="LC_error">'
                   12415:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12416:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12417:                                .'</span><br />';
                   12418:                     next;
                   12419:                 } else {
1.987     raeburn  12420:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12421:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12422:                 }
1.661     raeburn  12423:             }
1.1123    raeburn  12424:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12425:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12426:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12427:             my $result =
1.1126    raeburn  12428:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12429:             if ($result !~ m|^/uploaded/|) {
                   12430:                 $output .= '<span class="LC_error">'
                   12431:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12432:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12433:                            .'</span><br />';
                   12434:                     next;
                   12435:             } else {
                   12436:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12437:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12438:                 if ($context eq 'syllabus') {
                   12439:                     &Apache::lonnet::make_public_indefinitely($result);
                   12440:                 }
1.987     raeburn  12441:             }
1.661     raeburn  12442:         } else {
                   12443: # Save the file
                   12444:             my $target = $env{'form.embedded_item_'.$i};
                   12445:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12446:             my $dest = $fullpath.$fname;
                   12447:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12448:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12449:             my $count;
                   12450:             my $filepath = $dir_root;
1.1027    raeburn  12451:             foreach my $subdir (@parts) {
                   12452:                 $filepath .= "/$subdir";
                   12453:                 if (!-e $filepath) {
1.661     raeburn  12454:                     mkdir($filepath,0770);
                   12455:                 }
                   12456:             }
                   12457:             my $fh;
                   12458:             if (!open($fh,'>'.$dest)) {
                   12459:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12460:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12461:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12462:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12463:                            '</span><br />';
                   12464:             } else {
                   12465:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12466:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12467:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12468:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12469:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12470:                               '</span><br />';
                   12471:                 } else {
1.987     raeburn  12472:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12473:                                $url.'</span>').'<br />';
                   12474:                     unless ($context eq 'testbank') {
                   12475:                         $footer .= &mt('View embedded file: [_1]',
                   12476:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12477:                     }
                   12478:                 }
                   12479:                 close($fh);
                   12480:             }
                   12481:         }
                   12482:         if ($env{'form.embedded_ref_'.$i}) {
                   12483:             $pathchange{$i} = 1;
                   12484:         }
                   12485:     }
                   12486:     if ($output) {
                   12487:         $output = '<p>'.$output.'</p>';
                   12488:     }
                   12489:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12490:     $returnflag = 'ok';
1.1071    raeburn  12491:     my $numpathchgs = scalar(keys(%pathchange));
                   12492:     if ($numpathchgs > 0) {
1.987     raeburn  12493:         if ($context eq 'portfolio') {
                   12494:             $output .= '<p>'.&mt('or').'</p>';
                   12495:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12496:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12497:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12498:             $returnflag = 'modify_orightml';
                   12499:         }
                   12500:     }
1.1071    raeburn  12501:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12502: }
                   12503: 
                   12504: sub modify_html_form {
                   12505:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12506:     my $end = 0;
                   12507:     my $modifyform;
                   12508:     if ($context eq 'upload_embedded') {
                   12509:         return unless (ref($pathchange) eq 'HASH');
                   12510:         if ($env{'form.number_embedded_items'}) {
                   12511:             $end += $env{'form.number_embedded_items'};
                   12512:         }
                   12513:         if ($env{'form.number_pathchange_items'}) {
                   12514:             $end += $env{'form.number_pathchange_items'};
                   12515:         }
                   12516:         if ($end) {
                   12517:             for (my $i=0; $i<$end; $i++) {
                   12518:                 if ($i < $env{'form.number_embedded_items'}) {
                   12519:                     next unless($pathchange->{$i});
                   12520:                 }
                   12521:                 $modifyform .=
                   12522:                     &start_data_table_row().
                   12523:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12524:                     'checked="checked" /></td>'.
                   12525:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12526:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12527:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12528:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12529:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12530:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12531:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12532:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12533:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12534:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12535:                     &end_data_table_row();
1.1071    raeburn  12536:             }
1.987     raeburn  12537:         }
                   12538:     } else {
                   12539:         $modifyform = $pathchgtable;
                   12540:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12541:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12542:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12543:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12544:         }
                   12545:     }
                   12546:     if ($modifyform) {
1.1071    raeburn  12547:         if ($actionurl eq '/adm/dependencies') {
                   12548:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12549:         }
1.987     raeburn  12550:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12551:                '<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".
                   12552:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12553:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12554:                '</ol></p>'."\n".'<p>'.
                   12555:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12556:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12557:                &start_data_table()."\n".
                   12558:                &start_data_table_header_row().
                   12559:                '<th>'.&mt('Change?').'</th>'.
                   12560:                '<th>'.&mt('Current reference').'</th>'.
                   12561:                '<th>'.&mt('Required reference').'</th>'.
                   12562:                &end_data_table_header_row()."\n".
                   12563:                $modifyform.
                   12564:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12565:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12566:                '</form>'."\n";
                   12567:     }
                   12568:     return;
                   12569: }
                   12570: 
                   12571: sub modify_html_refs {
1.1123    raeburn  12572:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12573:     my $container;
                   12574:     if ($context eq 'portfolio') {
                   12575:         $container = $env{'form.container'};
                   12576:     } elsif ($context eq 'coursedoc') {
                   12577:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12578:     } elsif ($context eq 'manage_dependencies') {
                   12579:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12580:         $container = "/$container";
1.1123    raeburn  12581:     } elsif ($context eq 'syllabus') {
                   12582:         $container = $url;
1.987     raeburn  12583:     } else {
1.1027    raeburn  12584:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12585:     }
                   12586:     my (%allfiles,%codebase,$output,$content);
                   12587:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12588:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12589:         if (wantarray) {
                   12590:             return ('',0,0); 
                   12591:         } else {
                   12592:             return;
                   12593:         }
                   12594:     }
                   12595:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12596:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12597:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12598:             if (wantarray) {
                   12599:                 return ('',0,0);
                   12600:             } else {
                   12601:                 return;
                   12602:             }
                   12603:         } 
1.987     raeburn  12604:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12605:         if ($content eq '-1') {
                   12606:             if (wantarray) {
                   12607:                 return ('',0,0);
                   12608:             } else {
                   12609:                 return;
                   12610:             }
                   12611:         }
1.987     raeburn  12612:     } else {
1.1071    raeburn  12613:         unless ($container =~ /^\Q$dir_root\E/) {
                   12614:             if (wantarray) {
                   12615:                 return ('',0,0);
                   12616:             } else {
                   12617:                 return;
                   12618:             }
                   12619:         } 
1.1317    raeburn  12620:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12621:             $content = join('', <$fh>);
                   12622:             close($fh);
                   12623:         } else {
1.1071    raeburn  12624:             if (wantarray) {
                   12625:                 return ('',0,0);
                   12626:             } else {
                   12627:                 return;
                   12628:             }
1.987     raeburn  12629:         }
                   12630:     }
                   12631:     my ($count,$codebasecount) = (0,0);
                   12632:     my $mm = new File::MMagic;
                   12633:     my $mime_type = $mm->checktype_contents($content);
                   12634:     if ($mime_type eq 'text/html') {
                   12635:         my $parse_result = 
                   12636:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12637:                                                     \%codebase,\$content);
                   12638:         if ($parse_result eq 'ok') {
                   12639:             foreach my $i (@changes) {
                   12640:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12641:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12642:                 if ($allfiles{$ref}) {
                   12643:                     my $newname =  $orig;
                   12644:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12645:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12646:                     if ($attrib_regexp =~ /:/) {
                   12647:                         $attrib_regexp =~ s/\:/|/g;
                   12648:                     }
                   12649:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12650:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12651:                         $count += $numchg;
1.1123    raeburn  12652:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12653:                         delete($allfiles{$ref});
1.987     raeburn  12654:                     }
                   12655:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12656:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12657:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12658:                         $codebasecount ++;
                   12659:                     }
                   12660:                 }
                   12661:             }
1.1123    raeburn  12662:             my $skiprewrites;
1.987     raeburn  12663:             if ($count || $codebasecount) {
                   12664:                 my $saveresult;
1.1071    raeburn  12665:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12666:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12667:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12668:                     if ($url eq $container) {
                   12669:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12670:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12671:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12672:                                             $fname.'</span>').'</p>';
1.987     raeburn  12673:                     } else {
                   12674:                          $output = '<p class="LC_error">'.
                   12675:                                    &mt('Error: update failed for: [_1].',
                   12676:                                    '<span class="LC_filename">'.
                   12677:                                    $container.'</span>').'</p>';
                   12678:                     }
1.1123    raeburn  12679:                     if ($context eq 'syllabus') {
                   12680:                         unless ($saveresult eq 'ok') {
                   12681:                             $skiprewrites = 1;
                   12682:                         }
                   12683:                     }
1.987     raeburn  12684:                 } else {
1.1317    raeburn  12685:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12686:                         print $fh $content;
                   12687:                         close($fh);
                   12688:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12689:                                   $count,'<span class="LC_filename">'.
                   12690:                                   $container.'</span>').'</p>';
1.661     raeburn  12691:                     } else {
1.987     raeburn  12692:                          $output = '<p class="LC_error">'.
                   12693:                                    &mt('Error: could not update [_1].',
                   12694:                                    '<span class="LC_filename">'.
                   12695:                                    $container.'</span>').'</p>';
1.661     raeburn  12696:                     }
                   12697:                 }
                   12698:             }
1.1123    raeburn  12699:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12700:                 my ($actionurl,$state);
                   12701:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12702:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12703:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12704:                                               \%codebase,
                   12705:                                               {'context' => 'rewrites',
                   12706:                                                'ignore_remote_references' => 1,});
                   12707:                 if (ref($mapping) eq 'HASH') {
                   12708:                     my $rewrites = 0;
                   12709:                     foreach my $key (keys(%{$mapping})) {
                   12710:                         next if ($key =~ m{^https?://});
                   12711:                         my $ref = $mapping->{$key};
                   12712:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12713:                         my $attrib;
                   12714:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12715:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12716:                         }
                   12717:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12718:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12719:                             $rewrites += $numchg;
                   12720:                         }
                   12721:                     }
                   12722:                     if ($rewrites) {
                   12723:                         my $saveresult; 
                   12724:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12725:                         if ($url eq $container) {
                   12726:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12727:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12728:                                             $count,'<span class="LC_filename">'.
                   12729:                                             $fname.'</span>').'</p>';
                   12730:                         } else {
                   12731:                             $output .= '<p class="LC_error">'.
                   12732:                                        &mt('Error: could not update links in [_1].',
                   12733:                                        '<span class="LC_filename">'.
                   12734:                                        $container.'</span>').'</p>';
                   12735: 
                   12736:                         }
                   12737:                     }
                   12738:                 }
                   12739:             }
1.987     raeburn  12740:         } else {
                   12741:             &logthis('Failed to parse '.$container.
                   12742:                      ' to modify references: '.$parse_result);
1.661     raeburn  12743:         }
                   12744:     }
1.1071    raeburn  12745:     if (wantarray) {
                   12746:         return ($output,$count,$codebasecount);
                   12747:     } else {
                   12748:         return $output;
                   12749:     }
1.661     raeburn  12750: }
                   12751: 
                   12752: sub check_for_existing {
                   12753:     my ($path,$fname,$element) = @_;
                   12754:     my ($state,$msg);
                   12755:     if (-d $path.'/'.$fname) {
                   12756:         $state = 'exists';
                   12757:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12758:     } elsif (-e $path.'/'.$fname) {
                   12759:         $state = 'exists';
                   12760:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12761:     }
                   12762:     if ($state eq 'exists') {
                   12763:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12764:     }
                   12765:     return ($state,$msg);
                   12766: }
                   12767: 
                   12768: sub check_for_upload {
                   12769:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12770:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12771:     my $filesize = length($env{'form.'.$element});
                   12772:     if (!$filesize) {
                   12773:         my $msg = '<span class="LC_error">'.
                   12774:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12775:                       '<span class="LC_filename">'.$fname.'</span>',
                   12776:                       $filesize).'<br />'.
1.1007    raeburn  12777:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12778:                   '</span>';
                   12779:         return ('zero_bytes',$msg);
                   12780:     }
                   12781:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12782:     my $getpropath = 1;
1.1021    raeburn  12783:     my ($dirlistref,$listerror) =
                   12784:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12785:     my $found_file = 0;
                   12786:     my $locked_file = 0;
1.991     raeburn  12787:     my @lockers;
                   12788:     my $navmap;
                   12789:     if ($env{'request.course.id'}) {
                   12790:         $navmap = Apache::lonnavmaps::navmap->new();
                   12791:     }
1.1021    raeburn  12792:     if (ref($dirlistref) eq 'ARRAY') {
                   12793:         foreach my $line (@{$dirlistref}) {
                   12794:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12795:             if ($file_name eq $fname){
                   12796:                 $file_name = $path.$file_name;
                   12797:                 if ($group ne '') {
                   12798:                     $file_name = $group.$file_name;
                   12799:                 }
                   12800:                 $found_file = 1;
                   12801:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12802:                     foreach my $lock (@lockers) {
                   12803:                         if (ref($lock) eq 'ARRAY') {
                   12804:                             my ($symb,$crsid) = @{$lock};
                   12805:                             if ($crsid eq $env{'request.course.id'}) {
                   12806:                                 if (ref($navmap)) {
                   12807:                                     my $res = $navmap->getBySymb($symb);
                   12808:                                     foreach my $part (@{$res->parts()}) { 
                   12809:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12810:                                         unless (($slot_status == $res->RESERVED) ||
                   12811:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12812:                                             $locked_file = 1;
                   12813:                                         }
1.991     raeburn  12814:                                     }
1.1021    raeburn  12815:                                 } else {
                   12816:                                     $locked_file = 1;
1.991     raeburn  12817:                                 }
                   12818:                             } else {
                   12819:                                 $locked_file = 1;
                   12820:                             }
                   12821:                         }
1.1021    raeburn  12822:                    }
                   12823:                 } else {
                   12824:                     my @info = split(/\&/,$rest);
                   12825:                     my $currsize = $info[6]/1000;
                   12826:                     if ($currsize < $filesize) {
                   12827:                         my $extra = $filesize - $currsize;
                   12828:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12829:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12830:                                       &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   12831:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12832:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12833:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12834:                             return ('will_exceed_quota',$msg);
                   12835:                         }
1.984     raeburn  12836:                     }
                   12837:                 }
1.661     raeburn  12838:             }
                   12839:         }
                   12840:     }
                   12841:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12842:         my $msg = '<p class="LC_warning">'.
                   12843:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12844:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12845:         return ('will_exceed_quota',$msg);
                   12846:     } elsif ($found_file) {
                   12847:         if ($locked_file) {
1.1179    bisitz   12848:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12849:             $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   12850:             $msg .= '</p>';
1.661     raeburn  12851:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12852:             return ('file_locked',$msg);
                   12853:         } else {
1.1179    bisitz   12854:             my $msg = '<p class="LC_error">';
1.984     raeburn  12855:             $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   12856:             $msg .= '</p>';
1.984     raeburn  12857:             return ('existingfile',$msg);
1.661     raeburn  12858:         }
                   12859:     }
                   12860: }
                   12861: 
1.987     raeburn  12862: sub check_for_traversal {
                   12863:     my ($path,$url,$toplevel) = @_;
                   12864:     my @parts=split(/\//,$path);
                   12865:     my $cleanpath;
                   12866:     my $fullpath = $url;
                   12867:     for (my $i=0;$i<@parts;$i++) {
                   12868:         next if ($parts[$i] eq '.');
                   12869:         if ($parts[$i] eq '..') {
                   12870:             $fullpath =~ s{([^/]+/)$}{};
                   12871:         } else {
                   12872:             $fullpath .= $parts[$i].'/';
                   12873:         }
                   12874:     }
                   12875:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12876:         $cleanpath = $1;
                   12877:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12878:         my $curr_toprel = $1;
                   12879:         my @parts = split(/\//,$curr_toprel);
                   12880:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12881:         my @urlparts = split(/\//,$url_toprel);
                   12882:         my $doubledots;
                   12883:         my $startdiff = -1;
                   12884:         for (my $i=0; $i<@urlparts; $i++) {
                   12885:             if ($startdiff == -1) {
                   12886:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12887:                     $startdiff = $i;
                   12888:                     $doubledots .= '../';
                   12889:                 }
                   12890:             } else {
                   12891:                 $doubledots .= '../';
                   12892:             }
                   12893:         }
                   12894:         if ($startdiff > -1) {
                   12895:             $cleanpath = $doubledots;
                   12896:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12897:                 $cleanpath .= $parts[$i].'/';
                   12898:             }
                   12899:         }
                   12900:     }
                   12901:     $cleanpath =~ s{(/)$}{};
                   12902:     return $cleanpath;
                   12903: }
1.31      albertel 12904: 
1.1053    raeburn  12905: sub is_archive_file {
                   12906:     my ($mimetype) = @_;
                   12907:     if (($mimetype eq 'application/octet-stream') ||
                   12908:         ($mimetype eq 'application/x-stuffit') ||
                   12909:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12910:         return 1;
                   12911:     }
                   12912:     return;
                   12913: }
                   12914: 
                   12915: sub decompress_form {
1.1065    raeburn  12916:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12917:     my %lt = &Apache::lonlocal::texthash (
                   12918:         this => 'This file is an archive file.',
1.1067    raeburn  12919:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12920:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12921:         youm => 'You may wish to extract its contents.',
                   12922:         extr => 'Extract contents',
1.1067    raeburn  12923:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12924:         proa => 'Process automatically?',
1.1053    raeburn  12925:         yes  => 'Yes',
                   12926:         no   => 'No',
1.1067    raeburn  12927:         fold => 'Title for folder containing movie',
                   12928:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12929:     );
1.1065    raeburn  12930:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12931:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12932:     my $info = &list_archive_contents($fileloc,\@paths);
                   12933:     if (@paths) {
                   12934:         foreach my $path (@paths) {
                   12935:             $path =~ s{^/}{};
1.1067    raeburn  12936:             if ($path =~ m{^([^/]+)/$}) {
                   12937:                 $topdir = $1;
                   12938:             }
1.1065    raeburn  12939:             if ($path =~ m{^([^/]+)/}) {
                   12940:                 $toplevel{$1} = $path;
                   12941:             } else {
                   12942:                 $toplevel{$path} = $path;
                   12943:             }
                   12944:         }
                   12945:     }
1.1067    raeburn  12946:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12947:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12948:                         "$topdir/media/",
                   12949:                         "$topdir/media/$topdir.mp4",
                   12950:                         "$topdir/media/FirstFrame.png",
                   12951:                         "$topdir/media/player.swf",
                   12952:                         "$topdir/media/swfobject.js",
                   12953:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12954:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12955:                          "$topdir/$topdir.mp4",
                   12956:                          "$topdir/$topdir\_config.xml",
                   12957:                          "$topdir/$topdir\_controller.swf",
                   12958:                          "$topdir/$topdir\_embed.css",
                   12959:                          "$topdir/$topdir\_First_Frame.png",
                   12960:                          "$topdir/$topdir\_player.html",
                   12961:                          "$topdir/$topdir\_Thumbnails.png",
                   12962:                          "$topdir/playerProductInstall.swf",
                   12963:                          "$topdir/scripts/",
                   12964:                          "$topdir/scripts/config_xml.js",
                   12965:                          "$topdir/scripts/handlebars.js",
                   12966:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12967:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12968:                          "$topdir/scripts/modernizr.js",
                   12969:                          "$topdir/scripts/player-min.js",
                   12970:                          "$topdir/scripts/swfobject.js",
                   12971:                          "$topdir/skins/",
                   12972:                          "$topdir/skins/configuration_express.xml",
                   12973:                          "$topdir/skins/express_show/",
                   12974:                          "$topdir/skins/express_show/player-min.css",
                   12975:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12976:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12977:                          "$topdir/$topdir.mp4",
                   12978:                          "$topdir/$topdir\_config.xml",
                   12979:                          "$topdir/$topdir\_controller.swf",
                   12980:                          "$topdir/$topdir\_embed.css",
                   12981:                          "$topdir/$topdir\_First_Frame.png",
                   12982:                          "$topdir/$topdir\_player.html",
                   12983:                          "$topdir/$topdir\_Thumbnails.png",
                   12984:                          "$topdir/playerProductInstall.swf",
                   12985:                          "$topdir/scripts/",
                   12986:                          "$topdir/scripts/config_xml.js",
                   12987:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12988:                          "$topdir/skins/",
                   12989:                          "$topdir/skins/configuration_express.xml",
                   12990:                          "$topdir/skins/express_show/",
                   12991:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12992:                          "$topdir/skins/express_show/spritesheet.png",
                   12993:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12994:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12995:         if (@diffs == 0) {
1.1164    raeburn  12996:             $is_camtasia = 6;
                   12997:         } else {
1.1197    raeburn  12998:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12999:             if (@diffs == 0) {
                   13000:                 $is_camtasia = 8;
1.1197    raeburn  13001:             } else {
                   13002:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13003:                 if (@diffs == 0) {
                   13004:                     $is_camtasia = 8;
                   13005:                 }
1.1164    raeburn  13006:             }
1.1067    raeburn  13007:         }
                   13008:     }
                   13009:     my $output;
                   13010:     if ($is_camtasia) {
                   13011:         $output = <<"ENDCAM";
                   13012: <script type="text/javascript" language="Javascript">
                   13013: // <![CDATA[
                   13014: 
                   13015: function camtasiaToggle() {
                   13016:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13017:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13018:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13019:                 document.getElementById('camtasia_titles').style.display='block';
                   13020:             } else {
                   13021:                 document.getElementById('camtasia_titles').style.display='none';
                   13022:             }
                   13023:         }
                   13024:     }
                   13025:     return;
                   13026: }
                   13027: 
                   13028: // ]]>
                   13029: </script>
                   13030: <p>$lt{'camt'}</p>
                   13031: ENDCAM
1.1065    raeburn  13032:     } else {
1.1067    raeburn  13033:         $output = '<p>'.$lt{'this'};
                   13034:         if ($info eq '') {
                   13035:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13036:         } else {
                   13037:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13038:                        '<div><pre>'.$info.'</pre></div>';
                   13039:         }
1.1065    raeburn  13040:     }
1.1067    raeburn  13041:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13042:     my $duplicates;
                   13043:     my $num = 0;
                   13044:     if (ref($dirlist) eq 'ARRAY') {
                   13045:         foreach my $item (@{$dirlist}) {
                   13046:             if (ref($item) eq 'ARRAY') {
                   13047:                 if (exists($toplevel{$item->[0]})) {
                   13048:                     $duplicates .= 
                   13049:                         &start_data_table_row().
                   13050:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13051:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13052:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13053:                         'value="1" />'.&mt('Yes').'</label>'.
                   13054:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13055:                         '<td>'.$item->[0].'</td>';
                   13056:                     if ($item->[2]) {
                   13057:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13058:                     } else {
                   13059:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13060:                     }
                   13061:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13062:                                    '<td>'.
                   13063:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13064:                                    '</td>'.
                   13065:                                    &end_data_table_row();
                   13066:                     $num ++;
                   13067:                 }
                   13068:             }
                   13069:         }
                   13070:     }
                   13071:     my $itemcount;
                   13072:     if (@paths > 0) {
                   13073:         $itemcount = scalar(@paths);
                   13074:     } else {
                   13075:         $itemcount = 1;
                   13076:     }
1.1067    raeburn  13077:     if ($is_camtasia) {
                   13078:         $output .= $lt{'auto'}.'<br />'.
                   13079:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13080:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13081:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13082:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13083:                    $lt{'no'}.'</label></span><br />'.
                   13084:                    '<div id="camtasia_titles" style="display:block">'.
                   13085:                    &Apache::lonhtmlcommon::start_pick_box().
                   13086:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13087:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13088:                    &Apache::lonhtmlcommon::row_closure().
                   13089:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13090:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13091:                    &Apache::lonhtmlcommon::row_closure(1).
                   13092:                    &Apache::lonhtmlcommon::end_pick_box().
                   13093:                    '</div>';
                   13094:     }
1.1065    raeburn  13095:     $output .= 
                   13096:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13097:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13098:         "\n";
1.1065    raeburn  13099:     if ($duplicates ne '') {
                   13100:         $output .= '<p><span class="LC_warning">'.
                   13101:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13102:                    &start_data_table().
                   13103:                    &start_data_table_header_row().
                   13104:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13105:                    '<th>'.&mt('Name').'</th>'.
                   13106:                    '<th>'.&mt('Type').'</th>'.
                   13107:                    '<th>'.&mt('Size').'</th>'.
                   13108:                    '<th>'.&mt('Last modified').'</th>'.
                   13109:                    &end_data_table_header_row().
                   13110:                    $duplicates.
                   13111:                    &end_data_table().
                   13112:                    '</p>';
                   13113:     }
1.1067    raeburn  13114:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13115:     if (ref($hiddenelements) eq 'HASH') {
                   13116:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13117:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13118:         }
                   13119:     }
                   13120:     $output .= <<"END";
1.1067    raeburn  13121: <br />
1.1053    raeburn  13122: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13123: </form>
                   13124: $noextract
                   13125: END
                   13126:     return $output;
                   13127: }
                   13128: 
1.1065    raeburn  13129: sub decompression_utility {
                   13130:     my ($program) = @_;
                   13131:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13132:     my $location;
                   13133:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13134:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13135:                          '/usr/sbin/') {
                   13136:             if (-x $dir.$program) {
                   13137:                 $location = $dir.$program;
                   13138:                 last;
                   13139:             }
                   13140:         }
                   13141:     }
                   13142:     return $location;
                   13143: }
                   13144: 
                   13145: sub list_archive_contents {
                   13146:     my ($file,$pathsref) = @_;
                   13147:     my (@cmd,$output);
                   13148:     my $needsregexp;
                   13149:     if ($file =~ /\.zip$/) {
                   13150:         @cmd = (&decompression_utility('unzip'),"-l");
                   13151:         $needsregexp = 1;
                   13152:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13153:              ($file =~ /\.tgz$/)) {
                   13154:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13155:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13156:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13157:     } elsif ($file =~ m|\.tar$|) {
                   13158:         @cmd = (&decompression_utility('tar'),"-tf");
                   13159:     }
                   13160:     if (@cmd) {
                   13161:         undef($!);
                   13162:         undef($@);
                   13163:         if (open(my $fh,"-|", @cmd, $file)) {
                   13164:             while (my $line = <$fh>) {
                   13165:                 $output .= $line;
                   13166:                 chomp($line);
                   13167:                 my $item;
                   13168:                 if ($needsregexp) {
                   13169:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13170:                 } else {
                   13171:                     $item = $line;
                   13172:                 }
                   13173:                 if ($item ne '') {
                   13174:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13175:                         push(@{$pathsref},$item);
                   13176:                     } 
                   13177:                 }
                   13178:             }
                   13179:             close($fh);
                   13180:         }
                   13181:     }
                   13182:     return $output;
                   13183: }
                   13184: 
1.1053    raeburn  13185: sub decompress_uploaded_file {
                   13186:     my ($file,$dir) = @_;
                   13187:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13188:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13189:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13190:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13191:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13192:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13193:     my $decompressed = $env{'cgi.decompressed'};
                   13194:     &Apache::lonnet::delenv('cgi.file');
                   13195:     &Apache::lonnet::delenv('cgi.dir');
                   13196:     &Apache::lonnet::delenv('cgi.decompressed');
                   13197:     return ($decompressed,$result);
                   13198: }
                   13199: 
1.1055    raeburn  13200: sub process_decompression {
                   13201:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13202:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13203:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13204:                &mt('Unexpected file path.').'</p>'."\n";
                   13205:     }
                   13206:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13207:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13208:                &mt('Unexpected course context.').'</p>'."\n";
                   13209:     }
1.1293    raeburn  13210:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13211:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13212:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13213:     }
1.1055    raeburn  13214:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13215:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13216:         $error = &mt('Filename not a supported archive file type.').
                   13217:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13218:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13219:     } else {
                   13220:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13221:         if ($docuhome eq 'no_host') {
                   13222:             $error = &mt('Could not determine home server for course.');
                   13223:         } else {
                   13224:             my @ids=&Apache::lonnet::current_machine_ids();
                   13225:             my $currdir = "$dir_root/$destination";
                   13226:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13227:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13228:                        "$dir_root/$destination";
                   13229:             } else {
                   13230:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13231:                        "$dir_root/$docudom/$docuname/$destination";
                   13232:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13233:                     $error = &mt('Archive file not found.');
                   13234:                 }
                   13235:             }
1.1065    raeburn  13236:             my (@to_overwrite,@to_skip);
                   13237:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13238:                 my $total = $env{'form.archive_overwrite_total'};
                   13239:                 for (my $i=0; $i<$total; $i++) {
                   13240:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13241:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13242:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13243:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13244:                     }
                   13245:                 }
                   13246:             }
                   13247:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13248:             my $numoverwrite = scalar(@to_overwrite);
                   13249:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13250:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13251:             } elsif ($dir eq '') {
1.1055    raeburn  13252:                 $error = &mt('Directory containing archive file unavailable.');
                   13253:             } elsif (!$error) {
1.1065    raeburn  13254:                 my ($decompressed,$display);
1.1292    raeburn  13255:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13256:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13257:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13258:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13259:                         ($decompressed,$display) = 
                   13260:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13261:                         foreach my $item (@to_skip) {
                   13262:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13263:                                 if (-f "$dir/$tempdir/$item") { 
                   13264:                                     unlink("$dir/$tempdir/$item");
                   13265:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13266:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13267:                                 }
                   13268:                             }
                   13269:                         }
                   13270:                         foreach my $item (@to_overwrite) {
                   13271:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13272:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13273:                                     if (-f "$dir/$item") {
                   13274:                                         unlink("$dir/$item");
                   13275:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13276:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13277:                                     }
                   13278:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13279:                                 }
1.1065    raeburn  13280:                             }
                   13281:                         }
1.1292    raeburn  13282:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13283:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13284:                         }
1.1065    raeburn  13285:                     }
                   13286:                 } else {
                   13287:                     ($decompressed,$display) = 
                   13288:                         &decompress_uploaded_file($file,$dir);
                   13289:                 }
1.1055    raeburn  13290:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13291:                     $output = '<p class="LC_info">'.
                   13292:                               &mt('Files extracted successfully from archive.').
                   13293:                               '</p>'."\n";
1.1055    raeburn  13294:                     my ($warning,$result,@contents);
                   13295:                     my ($newdirlistref,$newlisterror) =
                   13296:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13297:                                                  $docuname,1);
                   13298:                     my (%is_dir,%changes,@newitems);
                   13299:                     my $dirptr = 16384;
1.1065    raeburn  13300:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13301:                         foreach my $dir_line (@{$newdirlistref}) {
                   13302:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13303:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13304:                                 push(@newitems,$item);
                   13305:                                 if ($dirptr&$testdir) {
                   13306:                                     $is_dir{$item} = 1;
                   13307:                                 }
                   13308:                                 $changes{$item} = 1;
                   13309:                             }
                   13310:                         }
                   13311:                     }
                   13312:                     if (keys(%changes) > 0) {
                   13313:                         foreach my $item (sort(@newitems)) {
                   13314:                             if ($changes{$item}) {
                   13315:                                 push(@contents,$item);
                   13316:                             }
                   13317:                         }
                   13318:                     }
                   13319:                     if (@contents > 0) {
1.1067    raeburn  13320:                         my $wantform;
                   13321:                         unless ($env{'form.autoextract_camtasia'}) {
                   13322:                             $wantform = 1;
                   13323:                         }
1.1056    raeburn  13324:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13325:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13326:                                                                 $currdir,\%is_dir,
                   13327:                                                                 \%children,\%parent,
1.1056    raeburn  13328:                                                                 \@contents,\%dirorder,
                   13329:                                                                 \%titles,$wantform);
1.1055    raeburn  13330:                         if ($datatable ne '') {
                   13331:                             $output .= &archive_options_form('decompressed',$datatable,
                   13332:                                                              $count,$hiddenelem);
1.1065    raeburn  13333:                             my $startcount = 6;
1.1055    raeburn  13334:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13335:                                                            \%titles,\%children);
1.1055    raeburn  13336:                         }
1.1067    raeburn  13337:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13338:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13339:                             my %displayed;
                   13340:                             my $total = 1;
                   13341:                             $env{'form.archive_directory'} = [];
                   13342:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13343:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13344:                                 $path =~ s{/$}{};
                   13345:                                 my $item;
                   13346:                                 if ($path ne '') {
                   13347:                                     $item = "$path/$titles{$i}";
                   13348:                                 } else {
                   13349:                                     $item = $titles{$i};
                   13350:                                 }
                   13351:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13352:                                 if ($item eq $contents[0]) {
                   13353:                                     push(@{$env{'form.archive_directory'}},$i);
                   13354:                                     $env{'form.archive_'.$i} = 'display';
                   13355:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13356:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13357:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13358:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13359:                                     $env{'form.archive_'.$i} = 'display';
                   13360:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13361:                                     $displayed{'web'} = $i;
                   13362:                                 } else {
1.1164    raeburn  13363:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13364:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13365:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13366:                                         push(@{$env{'form.archive_directory'}},$i);
                   13367:                                     }
                   13368:                                     $env{'form.archive_'.$i} = 'dependency';
                   13369:                                 }
                   13370:                                 $total ++;
                   13371:                             }
                   13372:                             for (my $i=1; $i<$total; $i++) {
                   13373:                                 next if ($i == $displayed{'web'});
                   13374:                                 next if ($i == $displayed{'folder'});
                   13375:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13376:                             }
                   13377:                             $env{'form.phase'} = 'decompress_cleanup';
                   13378:                             $env{'form.archivedelete'} = 1;
                   13379:                             $env{'form.archive_count'} = $total-1;
                   13380:                             $output .=
                   13381:                                 &process_extracted_files('coursedocs',$docudom,
                   13382:                                                          $docuname,$destination,
                   13383:                                                          $dir_root,$hiddenelem);
                   13384:                         }
1.1055    raeburn  13385:                     } else {
                   13386:                         $warning = &mt('No new items extracted from archive file.');
                   13387:                     }
                   13388:                 } else {
                   13389:                     $output = $display;
                   13390:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13391:                 }
                   13392:             }
                   13393:         }
                   13394:     }
                   13395:     if ($error) {
                   13396:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13397:                    $error.'</p>'."\n";
                   13398:     }
                   13399:     if ($warning) {
                   13400:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13401:     }
                   13402:     return $output;
                   13403: }
                   13404: 
                   13405: sub get_extracted {
1.1056    raeburn  13406:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13407:         $titles,$wantform) = @_;
1.1055    raeburn  13408:     my $count = 0;
                   13409:     my $depth = 0;
                   13410:     my $datatable;
1.1056    raeburn  13411:     my @hierarchy;
1.1055    raeburn  13412:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13413:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13414:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13415:     foreach my $item (@{$contents}) {
                   13416:         $count ++;
1.1056    raeburn  13417:         @{$dirorder->{$count}} = @hierarchy;
                   13418:         $titles->{$count} = $item;
1.1055    raeburn  13419:         &archive_hierarchy($depth,$count,$parent,$children);
                   13420:         if ($wantform) {
                   13421:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13422:                                        $currdir,$depth,$count);
                   13423:         }
                   13424:         if ($is_dir->{$item}) {
                   13425:             $depth ++;
1.1056    raeburn  13426:             push(@hierarchy,$count);
                   13427:             $parent->{$depth} = $count;
1.1055    raeburn  13428:             $datatable .=
                   13429:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13430:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13431:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13432:             $depth --;
1.1056    raeburn  13433:             pop(@hierarchy);
1.1055    raeburn  13434:         }
                   13435:     }
                   13436:     return ($count,$datatable);
                   13437: }
                   13438: 
                   13439: sub recurse_extracted_archive {
1.1056    raeburn  13440:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13441:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13442:     my $result='';
1.1056    raeburn  13443:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13444:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13445:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13446:         return $result;
                   13447:     }
                   13448:     my $dirptr = 16384;
                   13449:     my ($newdirlistref,$newlisterror) =
                   13450:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13451:     if (ref($newdirlistref) eq 'ARRAY') {
                   13452:         foreach my $dir_line (@{$newdirlistref}) {
                   13453:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13454:             unless ($item =~ /^\.+$/) {
                   13455:                 $$count ++;
1.1056    raeburn  13456:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13457:                 $titles->{$$count} = $item;
1.1055    raeburn  13458:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13459: 
1.1055    raeburn  13460:                 my $is_dir;
                   13461:                 if ($dirptr&$testdir) {
                   13462:                     $is_dir = 1;
                   13463:                 }
                   13464:                 if ($wantform) {
                   13465:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13466:                 }
                   13467:                 if ($is_dir) {
                   13468:                     $$depth ++;
1.1056    raeburn  13469:                     push(@{$hierarchy},$$count);
                   13470:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13471:                     $result .=
                   13472:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13473:                                                    $docuname,$depth,$count,
1.1056    raeburn  13474:                                                    $hierarchy,$dirorder,$children,
                   13475:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13476:                     $$depth --;
1.1056    raeburn  13477:                     pop(@{$hierarchy});
1.1055    raeburn  13478:                 }
                   13479:             }
                   13480:         }
                   13481:     }
                   13482:     return $result;
                   13483: }
                   13484: 
                   13485: sub archive_hierarchy {
                   13486:     my ($depth,$count,$parent,$children) =@_;
                   13487:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13488:         if (exists($parent->{$depth})) {
                   13489:              $children->{$parent->{$depth}} .= $count.':';
                   13490:         }
                   13491:     }
                   13492:     return;
                   13493: }
                   13494: 
                   13495: sub archive_row {
                   13496:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13497:     my ($name) = ($item =~ m{([^/]+)$});
                   13498:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13499:                                        'display'    => 'Add as file',
1.1055    raeburn  13500:                                        'dependency' => 'Include as dependency',
                   13501:                                        'discard'    => 'Discard',
                   13502:                                       );
                   13503:     if ($is_dir) {
1.1059    raeburn  13504:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13505:     }
1.1056    raeburn  13506:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13507:     my $offset = 0;
1.1055    raeburn  13508:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13509:         $offset ++;
1.1065    raeburn  13510:         if ($action ne 'display') {
                   13511:             $offset ++;
                   13512:         }  
1.1055    raeburn  13513:         $output .= '<td><span class="LC_nobreak">'.
                   13514:                    '<label><input type="radio" name="archive_'.$count.
                   13515:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13516:         my $text = $choices{$action};
                   13517:         if ($is_dir) {
                   13518:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13519:             if ($action eq 'display') {
1.1059    raeburn  13520:                 $text = &mt('Add as folder');
1.1055    raeburn  13521:             }
1.1056    raeburn  13522:         } else {
                   13523:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13524: 
                   13525:         }
                   13526:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13527:         if ($action eq 'dependency') {
                   13528:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13529:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13530:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13531:                        '<option value=""></option>'."\n".
                   13532:                        '</select>'."\n".
                   13533:                        '</div>';
1.1059    raeburn  13534:         } elsif ($action eq 'display') {
                   13535:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13536:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13537:                        '</div>';
1.1055    raeburn  13538:         }
1.1056    raeburn  13539:         $output .= '</td>';
1.1055    raeburn  13540:     }
                   13541:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13542:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13543:     for (my $i=0; $i<$depth; $i++) {
                   13544:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13545:     }
                   13546:     if ($is_dir) {
                   13547:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13548:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13549:     } else {
                   13550:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13551:     }
                   13552:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13553:                &end_data_table_row();
                   13554:     return $output;
                   13555: }
                   13556: 
                   13557: sub archive_options_form {
1.1065    raeburn  13558:     my ($form,$display,$count,$hiddenelem) = @_;
                   13559:     my %lt = &Apache::lonlocal::texthash(
                   13560:                perm => 'Permanently remove archive file?',
                   13561:                hows => 'How should each extracted item be incorporated in the course?',
                   13562:                cont => 'Content actions for all',
                   13563:                addf => 'Add as folder/file',
                   13564:                incd => 'Include as dependency for a displayed file',
                   13565:                disc => 'Discard',
                   13566:                no   => 'No',
                   13567:                yes  => 'Yes',
                   13568:                save => 'Save',
                   13569:     );
                   13570:     my $output = <<"END";
                   13571: <form name="$form" method="post" action="">
                   13572: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13573: <label>
                   13574:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13575: </label>
                   13576: &nbsp;
                   13577: <label>
                   13578:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13579: </span>
                   13580: </p>
                   13581: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13582: <br />$lt{'hows'}
                   13583: <div class="LC_columnSection">
                   13584:   <fieldset>
                   13585:     <legend>$lt{'cont'}</legend>
                   13586:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13587:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13588:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13589:   </fieldset>
                   13590: </div>
                   13591: END
                   13592:     return $output.
1.1055    raeburn  13593:            &start_data_table()."\n".
1.1065    raeburn  13594:            $display."\n".
1.1055    raeburn  13595:            &end_data_table()."\n".
                   13596:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13597:            $hiddenelem.
1.1065    raeburn  13598:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13599:            '</form>';
                   13600: }
                   13601: 
                   13602: sub archive_javascript {
1.1056    raeburn  13603:     my ($startcount,$numitems,$titles,$children) = @_;
                   13604:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13605:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13606:     my $scripttag = <<START;
                   13607: <script type="text/javascript">
                   13608: // <![CDATA[
                   13609: 
                   13610: function checkAll(form,prefix) {
                   13611:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13612:     for (var i=0; i < form.elements.length; i++) {
                   13613:         var id = form.elements[i].id;
                   13614:         if ((id != '') && (id != undefined)) {
                   13615:             if (idstr.test(id)) {
                   13616:                 if (form.elements[i].type == 'radio') {
                   13617:                     form.elements[i].checked = true;
1.1056    raeburn  13618:                     var nostart = i-$startcount;
1.1059    raeburn  13619:                     var offset = nostart%7;
                   13620:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13621:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13622:                 }
                   13623:             }
                   13624:         }
                   13625:     }
                   13626: }
                   13627: 
                   13628: function propagateCheck(form,count) {
                   13629:     if (count > 0) {
1.1059    raeburn  13630:         var startelement = $startcount + ((count-1) * 7);
                   13631:         for (var j=1; j<6; j++) {
                   13632:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13633:                 var item = startelement + j; 
                   13634:                 if (form.elements[item].type == 'radio') {
                   13635:                     if (form.elements[item].checked) {
                   13636:                         containerCheck(form,count,j);
                   13637:                         break;
                   13638:                     }
1.1055    raeburn  13639:                 }
                   13640:             }
                   13641:         }
                   13642:     }
                   13643: }
                   13644: 
                   13645: numitems = $numitems
1.1056    raeburn  13646: var titles = new Array(numitems);
                   13647: var parents = new Array(numitems);
1.1055    raeburn  13648: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13649:     parents[i] = new Array;
1.1055    raeburn  13650: }
1.1059    raeburn  13651: var maintitle = '$maintitle';
1.1055    raeburn  13652: 
                   13653: START
                   13654: 
1.1056    raeburn  13655:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13656:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13657:         for (my $i=0; $i<@contents; $i ++) {
                   13658:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13659:         }
                   13660:     }
                   13661: 
1.1056    raeburn  13662:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13663:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13664:     }
                   13665: 
1.1055    raeburn  13666:     $scripttag .= <<END;
                   13667: 
                   13668: function containerCheck(form,count,offset) {
                   13669:     if (count > 0) {
1.1056    raeburn  13670:         dependencyCheck(form,count,offset);
1.1059    raeburn  13671:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13672:         form.elements[item].checked = true;
                   13673:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13674:             if (parents[count].length > 0) {
                   13675:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13676:                     containerCheck(form,parents[count][j],offset);
                   13677:                 }
                   13678:             }
                   13679:         }
                   13680:     }
                   13681: }
                   13682: 
                   13683: function dependencyCheck(form,count,offset) {
                   13684:     if (count > 0) {
1.1059    raeburn  13685:         var chosen = (offset+$startcount)+7*(count-1);
                   13686:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13687:         var currtype = form.elements[depitem].type;
                   13688:         if (form.elements[chosen].value == 'dependency') {
                   13689:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13690:             form.elements[depitem].options.length = 0;
                   13691:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13692:             for (var i=1; i<=numitems; i++) {
                   13693:                 if (i == count) {
                   13694:                     continue;
                   13695:                 }
1.1059    raeburn  13696:                 var startelement = $startcount + (i-1) * 7;
                   13697:                 for (var j=1; j<6; j++) {
                   13698:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13699:                         var item = startelement + j;
                   13700:                         if (form.elements[item].type == 'radio') {
                   13701:                             if (form.elements[item].checked) {
                   13702:                                 if (form.elements[item].value == 'display') {
                   13703:                                     var n = form.elements[depitem].options.length;
                   13704:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13705:                                 }
                   13706:                             }
                   13707:                         }
                   13708:                     }
                   13709:                 }
                   13710:             }
                   13711:         } else {
                   13712:             document.getElementById('arc_depon_'+count).style.display='none';
                   13713:             form.elements[depitem].options.length = 0;
                   13714:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13715:         }
1.1059    raeburn  13716:         titleCheck(form,count,offset);
1.1056    raeburn  13717:     }
                   13718: }
                   13719: 
                   13720: function propagateSelect(form,count,offset) {
                   13721:     if (count > 0) {
1.1065    raeburn  13722:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13723:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13724:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13725:             if (parents[count].length > 0) {
                   13726:                 for (var j=0; j<parents[count].length; j++) {
                   13727:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13728:                 }
                   13729:             }
                   13730:         }
                   13731:     }
                   13732: }
1.1056    raeburn  13733: 
                   13734: function containerSelect(form,count,offset,picked) {
                   13735:     if (count > 0) {
1.1065    raeburn  13736:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13737:         if (form.elements[item].type == 'radio') {
                   13738:             if (form.elements[item].value == 'dependency') {
                   13739:                 if (form.elements[item+1].type == 'select-one') {
                   13740:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13741:                         if (form.elements[item+1].options[i].value == picked) {
                   13742:                             form.elements[item+1].selectedIndex = i;
                   13743:                             break;
                   13744:                         }
                   13745:                     }
                   13746:                 }
                   13747:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13748:                     if (parents[count].length > 0) {
                   13749:                         for (var j=0; j<parents[count].length; j++) {
                   13750:                             containerSelect(form,parents[count][j],offset,picked);
                   13751:                         }
                   13752:                     }
                   13753:                 }
                   13754:             }
                   13755:         }
                   13756:     }
                   13757: }
                   13758: 
1.1059    raeburn  13759: function titleCheck(form,count,offset) {
                   13760:     if (count > 0) {
                   13761:         var chosen = (offset+$startcount)+7*(count-1);
                   13762:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13763:         var currtype = form.elements[depitem].type;
                   13764:         if (form.elements[chosen].value == 'display') {
                   13765:             document.getElementById('arc_title_'+count).style.display='block';
                   13766:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13767:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13768:             }
                   13769:         } else {
                   13770:             document.getElementById('arc_title_'+count).style.display='none';
                   13771:             if (currtype == 'text') { 
                   13772:                 document.getElementById('archive_title_'+count).value='';
                   13773:             }
                   13774:         }
                   13775:     }
                   13776:     return;
                   13777: }
                   13778: 
1.1055    raeburn  13779: // ]]>
                   13780: </script>
                   13781: END
                   13782:     return $scripttag;
                   13783: }
                   13784: 
                   13785: sub process_extracted_files {
1.1067    raeburn  13786:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13787:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13788:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13789:     my @ids=&Apache::lonnet::current_machine_ids();
                   13790:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13791:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13792:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13793:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13794:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13795:         $pathtocheck = "$dir_root/$destination";
                   13796:         $dir = $dir_root;
                   13797:         $ishome = 1;
                   13798:     } else {
                   13799:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13800:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13801:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13802:     }
                   13803:     my $currdir = "$dir_root/$destination";
                   13804:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13805:     if ($env{'form.folderpath'}) {
                   13806:         my @items = split('&',$env{'form.folderpath'});
                   13807:         $folders{'0'} = $items[-2];
1.1099    raeburn  13808:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13809:             $containers{'0'}='page';
                   13810:         } else {  
                   13811:             $containers{'0'}='sequence';
                   13812:         }
1.1055    raeburn  13813:     }
                   13814:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13815:     if ($numitems) {
                   13816:         for (my $i=1; $i<=$numitems; $i++) {
                   13817:             my $path = $env{'form.archive_content_'.$i};
                   13818:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13819:                 my $item = $1;
                   13820:                 $toplevelitems{$item} = $i;
                   13821:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13822:                     $is_dir{$item} = 1;
                   13823:                 }
                   13824:             }
                   13825:         }
                   13826:     }
1.1067    raeburn  13827:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13828:     if (keys(%toplevelitems) > 0) {
                   13829:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13830:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13831:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13832:     }
1.1066    raeburn  13833:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13834:     if ($numitems) {
                   13835:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13836:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13837:             my $path = $env{'form.archive_content_'.$i};
                   13838:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13839:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13840:                     if ($prefix ne '' && $path ne '') {
                   13841:                         if (-e $prefix.$path) {
1.1066    raeburn  13842:                             if ((@archdirs > 0) && 
                   13843:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13844:                                 $todeletedir{$prefix.$path} = 1;
                   13845:                             } else {
                   13846:                                 $todelete{$prefix.$path} = 1;
                   13847:                             }
1.1055    raeburn  13848:                         }
                   13849:                     }
                   13850:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13851:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13852:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13853:                     $docstitle = $env{'form.archive_title_'.$i};
                   13854:                     if ($docstitle eq '') {
                   13855:                         $docstitle = $title;
                   13856:                     }
1.1055    raeburn  13857:                     $outer = 0;
1.1056    raeburn  13858:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13859:                         if (@{$dirorder{$i}} > 0) {
                   13860:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13861:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13862:                                     $outer = $item;
                   13863:                                     last;
                   13864:                                 }
                   13865:                             }
                   13866:                         }
                   13867:                     }
                   13868:                     my ($errtext,$fatal) = 
                   13869:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13870:                                                '/'.$folders{$outer}.'.'.
                   13871:                                                $containers{$outer});
                   13872:                     next if ($fatal);
                   13873:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13874:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13875:                             $mapinner{$i} = time;
1.1055    raeburn  13876:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13877:                             $containers{$i} = 'sequence';
                   13878:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13879:                                       $folders{$i}.'.'.$containers{$i};
                   13880:                             my $newidx = &LONCAPA::map::getresidx();
                   13881:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13882:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13883:                             push(@LONCAPA::map::order,$newidx);
                   13884:                             my ($outtext,$errtext) =
                   13885:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13886:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13887:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13888:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13889:                             unless ($errtext) {
1.1294    raeburn  13890:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13891:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13892:                                             '</li>'."\n";
1.1067    raeburn  13893:                             }
1.1055    raeburn  13894:                         }
                   13895:                     } else {
                   13896:                         if ($context eq 'coursedocs') {
                   13897:                             my $newidx=&LONCAPA::map::getresidx();
                   13898:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13899:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13900:                                       $title;
1.1294    raeburn  13901:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13902:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13903:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13904:                                 }
                   13905:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13906:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13907:                                 }
                   13908:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13909:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13910:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13911:                                         unless ($ishome) {
                   13912:                                             my $fetch = "$newdest{$i}/$title";
                   13913:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13914:                                             $prompttofetch{$fetch} = 1;
                   13915:                                         }
1.1292    raeburn  13916:                                     }
1.1067    raeburn  13917:                                 }
1.1294    raeburn  13918:                                 $LONCAPA::map::resources[$newidx]=
                   13919:                                     $docstitle.':'.$url.':false:normal:res';
                   13920:                                 push(@LONCAPA::map::order, $newidx);
                   13921:                                 my ($outtext,$errtext)=
                   13922:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13923:                                                             $docuname.'/'.$folders{$outer}.
                   13924:                                                             '.'.$containers{$outer},1,1);
                   13925:                                 unless ($errtext) {
                   13926:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13927:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13928:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13929:                                                    '</li>'."\n";
                   13930:                                     }
1.1067    raeburn  13931:                                 }
1.1294    raeburn  13932:                             } else {
                   13933:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13934:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13935:                             }
1.1055    raeburn  13936:                         }
                   13937:                     }
1.1086    raeburn  13938:                 }
                   13939:             } else {
1.1294    raeburn  13940:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13941:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13942:             }
                   13943:         }
                   13944:         for (my $i=1; $i<=$numitems; $i++) {
                   13945:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13946:             my $path = $env{'form.archive_content_'.$i};
                   13947:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13948:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13949:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13950:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13951:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13952:                         my ($itemidx,$fullpath,$relpath);
                   13953:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13954:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13955:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13956:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13957:                                     $itemidx = $j;
1.1056    raeburn  13958:                                 }
                   13959:                             }
1.1086    raeburn  13960:                         }
                   13961:                         if ($itemidx eq '') {
                   13962:                             $itemidx =  0;
                   13963:                         } 
                   13964:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13965:                             if ($mapinner{$referrer{$i}}) {
                   13966:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13967:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13968:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13969:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13970:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13971:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13972:                                             if (!-e $fullpath) {
                   13973:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13974:                                             }
                   13975:                                         }
1.1086    raeburn  13976:                                     } else {
                   13977:                                         last;
1.1056    raeburn  13978:                                     }
1.1086    raeburn  13979:                                 }
                   13980:                             }
                   13981:                         } elsif ($newdest{$referrer{$i}}) {
                   13982:                             $fullpath = $newdest{$referrer{$i}};
                   13983:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13984:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13985:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13986:                                     last;
                   13987:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13988:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13989:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13990:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13991:                                         if (!-e $fullpath) {
                   13992:                                             mkdir($fullpath,0755);
1.1056    raeburn  13993:                                         }
                   13994:                                     }
1.1086    raeburn  13995:                                 } else {
                   13996:                                     last;
1.1056    raeburn  13997:                                 }
1.1055    raeburn  13998:                             }
                   13999:                         }
1.1086    raeburn  14000:                         if ($fullpath ne '') {
                   14001:                             if (-e "$prefix$path") {
1.1292    raeburn  14002:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14003:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14004:                                 }
1.1086    raeburn  14005:                             }
                   14006:                             if (-e "$fullpath/$title") {
                   14007:                                 my $showpath;
                   14008:                                 if ($relpath ne '') {
                   14009:                                     $showpath = "$relpath/$title";
                   14010:                                 } else {
                   14011:                                     $showpath = "/$title";
                   14012:                                 } 
1.1294    raeburn  14013:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14014:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14015:                                            '</li>'."\n";
1.1292    raeburn  14016:                                 unless ($ishome) {
                   14017:                                     my $fetch = "$fullpath/$title";
                   14018:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14019:                                     $prompttofetch{$fetch} = 1;
                   14020:                                 }
1.1086    raeburn  14021:                             }
                   14022:                         }
1.1055    raeburn  14023:                     }
1.1086    raeburn  14024:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14025:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14026:                                     &HTML::Entities::encode($path,'<>&"'),
                   14027:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14028:                                 '<br />';
1.1055    raeburn  14029:                 }
                   14030:             } else {
1.1294    raeburn  14031:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14032:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14033:             }
                   14034:         }
                   14035:         if (keys(%todelete)) {
                   14036:             foreach my $key (keys(%todelete)) {
                   14037:                 unlink($key);
1.1066    raeburn  14038:             }
                   14039:         }
                   14040:         if (keys(%todeletedir)) {
                   14041:             foreach my $key (keys(%todeletedir)) {
                   14042:                 rmdir($key);
                   14043:             }
                   14044:         }
                   14045:         foreach my $dir (sort(keys(%is_dir))) {
                   14046:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14047:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14048:             }
                   14049:         }
1.1067    raeburn  14050:         if ($result ne '') {
                   14051:             $output .= '<ul>'."\n".
                   14052:                        $result."\n".
                   14053:                        '</ul>';
                   14054:         }
                   14055:         unless ($ishome) {
                   14056:             my $replicationfail;
                   14057:             foreach my $item (keys(%prompttofetch)) {
                   14058:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14059:                 unless ($fetchresult eq 'ok') {
                   14060:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14061:                 }
                   14062:             }
                   14063:             if ($replicationfail) {
                   14064:                 $output .= '<p class="LC_error">'.
                   14065:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14066:                            $replicationfail.
                   14067:                            '</ul></p>';
                   14068:             }
                   14069:         }
1.1055    raeburn  14070:     } else {
                   14071:         $warning = &mt('No items found in archive.');
                   14072:     }
                   14073:     if ($error) {
                   14074:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14075:                    $error.'</p>'."\n";
                   14076:     }
                   14077:     if ($warning) {
                   14078:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14079:     }
                   14080:     return $output;
                   14081: }
                   14082: 
1.1066    raeburn  14083: sub cleanup_empty_dirs {
                   14084:     my ($path) = @_;
                   14085:     if (($path ne '') && (-d $path)) {
                   14086:         if (opendir(my $dirh,$path)) {
                   14087:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14088:             my $numitems = 0;
                   14089:             foreach my $item (@dircontents) {
                   14090:                 if (-d "$path/$item") {
1.1111    raeburn  14091:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14092:                     if (-e "$path/$item") {
                   14093:                         $numitems ++;
                   14094:                     }
                   14095:                 } else {
                   14096:                     $numitems ++;
                   14097:                 }
                   14098:             }
                   14099:             if ($numitems == 0) {
                   14100:                 rmdir($path);
                   14101:             }
                   14102:             closedir($dirh);
                   14103:         }
                   14104:     }
                   14105:     return;
                   14106: }
                   14107: 
1.41      ng       14108: =pod
1.45      matthew  14109: 
1.1162    raeburn  14110: =item * &get_folder_hierarchy()
1.1068    raeburn  14111: 
                   14112: Provides hierarchy of names of folders/sub-folders containing the current
                   14113: item,
                   14114: 
                   14115: Inputs: 3
                   14116:      - $navmap - navmaps object
                   14117: 
                   14118:      - $map - url for map (either the trigger itself, or map containing
                   14119:                            the resource, which is the trigger).
                   14120: 
                   14121:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14122: 
                   14123: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14124: 
                   14125: =cut
                   14126: 
                   14127: sub get_folder_hierarchy {
                   14128:     my ($navmap,$map,$showitem) = @_;
                   14129:     my @pathitems;
                   14130:     if (ref($navmap)) {
                   14131:         my $mapres = $navmap->getResourceByUrl($map);
                   14132:         if (ref($mapres)) {
                   14133:             my $pcslist = $mapres->map_hierarchy();
                   14134:             if ($pcslist ne '') {
                   14135:                 my @pcs = split(/,/,$pcslist);
                   14136:                 foreach my $pc (@pcs) {
                   14137:                     if ($pc == 1) {
1.1129    raeburn  14138:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14139:                     } else {
                   14140:                         my $res = $navmap->getByMapPc($pc);
                   14141:                         if (ref($res)) {
                   14142:                             my $title = $res->compTitle();
                   14143:                             $title =~ s/\W+/_/g;
                   14144:                             if ($title ne '') {
                   14145:                                 push(@pathitems,$title);
                   14146:                             }
                   14147:                         }
                   14148:                     }
                   14149:                 }
                   14150:             }
1.1071    raeburn  14151:             if ($showitem) {
                   14152:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14153:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14154:                 } else {
                   14155:                     my $maptitle = $mapres->compTitle();
                   14156:                     $maptitle =~ s/\W+/_/g;
                   14157:                     if ($maptitle ne '') {
                   14158:                         push(@pathitems,$maptitle);
                   14159:                     }
1.1068    raeburn  14160:                 }
                   14161:             }
                   14162:         }
                   14163:     }
                   14164:     return @pathitems;
                   14165: }
                   14166: 
                   14167: =pod
                   14168: 
1.1015    raeburn  14169: =item * &get_turnedin_filepath()
                   14170: 
                   14171: Determines path in a user's portfolio file for storage of files uploaded
                   14172: to a specific essayresponse or dropbox item.
                   14173: 
                   14174: Inputs: 3 required + 1 optional.
                   14175: $symb is symb for resource, $uname and $udom are for current user (required).
                   14176: $caller is optional (can be "submission", if routine is called when storing
                   14177: an upoaded file when "Submit Answer" button was pressed).
                   14178: 
                   14179: Returns array containing $path and $multiresp. 
                   14180: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14181: than one file upload item.  Callers of routine should append partid as a 
                   14182: subdirectory to $path in cases where $multiresp is 1.
                   14183: 
                   14184: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14185: 
                   14186: =cut
                   14187: 
                   14188: sub get_turnedin_filepath {
                   14189:     my ($symb,$uname,$udom,$caller) = @_;
                   14190:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14191:     my $turnindir;
                   14192:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14193:     $turnindir = $userhash{'turnindir'};
                   14194:     my ($path,$multiresp);
                   14195:     if ($turnindir eq '') {
                   14196:         if ($caller eq 'submission') {
                   14197:             $turnindir = &mt('turned in');
                   14198:             $turnindir =~ s/\W+/_/g;
                   14199:             my %newhash = (
                   14200:                             'turnindir' => $turnindir,
                   14201:                           );
                   14202:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14203:         }
                   14204:     }
                   14205:     if ($turnindir ne '') {
                   14206:         $path = '/'.$turnindir.'/';
                   14207:         my ($multipart,$turnin,@pathitems);
                   14208:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14209:         if (defined($navmap)) {
                   14210:             my $mapres = $navmap->getResourceByUrl($map);
                   14211:             if (ref($mapres)) {
                   14212:                 my $pcslist = $mapres->map_hierarchy();
                   14213:                 if ($pcslist ne '') {
                   14214:                     foreach my $pc (split(/,/,$pcslist)) {
                   14215:                         my $res = $navmap->getByMapPc($pc);
                   14216:                         if (ref($res)) {
                   14217:                             my $title = $res->compTitle();
                   14218:                             $title =~ s/\W+/_/g;
                   14219:                             if ($title ne '') {
1.1149    raeburn  14220:                                 if (($pc > 1) && (length($title) > 12)) {
                   14221:                                     $title = substr($title,0,12);
                   14222:                                 }
1.1015    raeburn  14223:                                 push(@pathitems,$title);
                   14224:                             }
                   14225:                         }
                   14226:                     }
                   14227:                 }
                   14228:                 my $maptitle = $mapres->compTitle();
                   14229:                 $maptitle =~ s/\W+/_/g;
                   14230:                 if ($maptitle ne '') {
1.1149    raeburn  14231:                     if (length($maptitle) > 12) {
                   14232:                         $maptitle = substr($maptitle,0,12);
                   14233:                     }
1.1015    raeburn  14234:                     push(@pathitems,$maptitle);
                   14235:                 }
                   14236:                 unless ($env{'request.state'} eq 'construct') {
                   14237:                     my $res = $navmap->getBySymb($symb);
                   14238:                     if (ref($res)) {
                   14239:                         my $partlist = $res->parts();
                   14240:                         my $totaluploads = 0;
                   14241:                         if (ref($partlist) eq 'ARRAY') {
                   14242:                             foreach my $part (@{$partlist}) {
                   14243:                                 my @types = $res->responseType($part);
                   14244:                                 my @ids = $res->responseIds($part);
                   14245:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14246:                                     if ($types[$i] eq 'essay') {
                   14247:                                         my $partid = $part.'_'.$ids[$i];
                   14248:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14249:                                             $totaluploads ++;
                   14250:                                         }
                   14251:                                     }
                   14252:                                 }
                   14253:                             }
                   14254:                             if ($totaluploads > 1) {
                   14255:                                 $multiresp = 1;
                   14256:                             }
                   14257:                         }
                   14258:                     }
                   14259:                 }
                   14260:             } else {
                   14261:                 return;
                   14262:             }
                   14263:         } else {
                   14264:             return;
                   14265:         }
                   14266:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14267:         $restitle =~ s/\W+/_/g;
                   14268:         if ($restitle eq '') {
                   14269:             $restitle = ($resurl =~ m{/[^/]+$});
                   14270:             if ($restitle eq '') {
                   14271:                 $restitle = time;
                   14272:             }
                   14273:         }
1.1149    raeburn  14274:         if (length($restitle) > 12) {
                   14275:             $restitle = substr($restitle,0,12);
                   14276:         }
1.1015    raeburn  14277:         push(@pathitems,$restitle);
                   14278:         $path .= join('/',@pathitems);
                   14279:     }
                   14280:     return ($path,$multiresp);
                   14281: }
                   14282: 
                   14283: =pod
                   14284: 
1.464     albertel 14285: =back
1.41      ng       14286: 
1.112     bowersj2 14287: =head1 CSV Upload/Handling functions
1.38      albertel 14288: 
1.41      ng       14289: =over 4
                   14290: 
1.648     raeburn  14291: =item * &upfile_store($r)
1.41      ng       14292: 
                   14293: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14294: needs $env{'form.upfile'}
1.41      ng       14295: returns $datatoken to be put into hidden field
                   14296: 
                   14297: =cut
1.31      albertel 14298: 
                   14299: sub upfile_store {
                   14300:     my $r=shift;
1.258     albertel 14301:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14302:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14303:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14304:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14305: 
1.1299    raeburn  14306:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14307:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14308:                                      time.'_'.$$);
                   14309:     return if ($datatoken eq '');
                   14310: 
1.31      albertel 14311:     {
1.158     raeburn  14312:         my $datafile = $r->dir_config('lonDaemons').
                   14313:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14314:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14315:             print $fh $env{'form.upfile'};
1.158     raeburn  14316:             close($fh);
                   14317:         }
1.31      albertel 14318:     }
                   14319:     return $datatoken;
                   14320: }
                   14321: 
1.56      matthew  14322: =pod
                   14323: 
1.1290    raeburn  14324: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14325: 
                   14326: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14327: $datatoken is the name to assign to the temporary file.
1.258     albertel 14328: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14329: 
                   14330: =cut
1.31      albertel 14331: 
                   14332: sub load_tmp_file {
1.1290    raeburn  14333:     my ($r,$datatoken) = @_;
                   14334:     return if ($datatoken eq '');
1.31      albertel 14335:     my @studentdata=();
                   14336:     {
1.158     raeburn  14337:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14338:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14339:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14340:             @studentdata=<$fh>;
                   14341:             close($fh);
                   14342:         }
1.31      albertel 14343:     }
1.258     albertel 14344:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14345: }
                   14346: 
1.1290    raeburn  14347: sub valid_datatoken {
                   14348:     my ($datatoken) = @_;
1.1325    raeburn  14349:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14350:         return $datatoken;
                   14351:     }
                   14352:     return;
                   14353: }
                   14354: 
1.56      matthew  14355: =pod
                   14356: 
1.648     raeburn  14357: =item * &upfile_record_sep()
1.41      ng       14358: 
                   14359: Separate uploaded file into records
                   14360: returns array of records,
1.258     albertel 14361: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14362: 
                   14363: =cut
1.31      albertel 14364: 
                   14365: sub upfile_record_sep {
1.258     albertel 14366:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14367:     } else {
1.248     albertel 14368: 	my @records;
1.258     albertel 14369: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14370: 	    if ($line=~/^\s*$/) { next; }
                   14371: 	    push(@records,$line);
                   14372: 	}
                   14373: 	return @records;
1.31      albertel 14374:     }
                   14375: }
                   14376: 
1.56      matthew  14377: =pod
                   14378: 
1.648     raeburn  14379: =item * &record_sep($record)
1.41      ng       14380: 
1.258     albertel 14381: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14382: 
                   14383: =cut
                   14384: 
1.263     www      14385: sub takeleft {
                   14386:     my $index=shift;
                   14387:     return substr('0000'.$index,-4,4);
                   14388: }
                   14389: 
1.31      albertel 14390: sub record_sep {
                   14391:     my $record=shift;
                   14392:     my %components=();
1.258     albertel 14393:     if ($env{'form.upfiletype'} eq 'xml') {
                   14394:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14395:         my $i=0;
1.356     albertel 14396:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14397:             $field=~s/^(\"|\')//;
                   14398:             $field=~s/(\"|\')$//;
1.263     www      14399:             $components{&takeleft($i)}=$field;
1.31      albertel 14400:             $i++;
                   14401:         }
1.258     albertel 14402:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14403:         my $i=0;
1.356     albertel 14404:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14405:             $field=~s/^(\"|\')//;
                   14406:             $field=~s/(\"|\')$//;
1.263     www      14407:             $components{&takeleft($i)}=$field;
1.31      albertel 14408:             $i++;
                   14409:         }
                   14410:     } else {
1.561     www      14411:         my $separator=',';
1.480     banghart 14412:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14413:             $separator=';';
1.480     banghart 14414:         }
1.31      albertel 14415:         my $i=0;
1.561     www      14416: # the character we are looking for to indicate the end of a quote or a record 
                   14417:         my $looking_for=$separator;
                   14418: # do not add the characters to the fields
                   14419:         my $ignore=0;
                   14420: # we just encountered a separator (or the beginning of the record)
                   14421:         my $just_found_separator=1;
                   14422: # store the field we are working on here
                   14423:         my $field='';
                   14424: # work our way through all characters in record
                   14425:         foreach my $character ($record=~/(.)/g) {
                   14426:             if ($character eq $looking_for) {
                   14427:                if ($character ne $separator) {
                   14428: # Found the end of a quote, again looking for separator
                   14429:                   $looking_for=$separator;
                   14430:                   $ignore=1;
                   14431:                } else {
                   14432: # Found a separator, store away what we got
                   14433:                   $components{&takeleft($i)}=$field;
                   14434: 	          $i++;
                   14435:                   $just_found_separator=1;
                   14436:                   $ignore=0;
                   14437:                   $field='';
                   14438:                }
                   14439:                next;
                   14440:             }
                   14441: # single or double quotation marks after a separator indicate beginning of a quote
                   14442: # we are now looking for the end of the quote and need to ignore separators
                   14443:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14444:                $looking_for=$character;
                   14445:                next;
                   14446:             }
                   14447: # ignore would be true after we reached the end of a quote
                   14448:             if ($ignore) { next; }
                   14449:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14450:             $field.=$character;
                   14451:             $just_found_separator=0; 
1.31      albertel 14452:         }
1.561     www      14453: # catch the very last entry, since we never encountered the separator
                   14454:         $components{&takeleft($i)}=$field;
1.31      albertel 14455:     }
                   14456:     return %components;
                   14457: }
                   14458: 
1.144     matthew  14459: ######################################################
                   14460: ######################################################
                   14461: 
1.56      matthew  14462: =pod
                   14463: 
1.648     raeburn  14464: =item * &upfile_select_html()
1.41      ng       14465: 
1.144     matthew  14466: Return HTML code to select a file from the users machine and specify 
                   14467: the file type.
1.41      ng       14468: 
                   14469: =cut
                   14470: 
1.144     matthew  14471: ######################################################
                   14472: ######################################################
1.31      albertel 14473: sub upfile_select_html {
1.144     matthew  14474:     my %Types = (
                   14475:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14476:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14477:                  space => &mt('Space separated'),
                   14478:                  tab   => &mt('Tabulator separated'),
                   14479: #                 xml   => &mt('HTML/XML'),
                   14480:                  );
                   14481:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14482:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14483:     foreach my $type (sort(keys(%Types))) {
                   14484:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14485:     }
                   14486:     $Str .= "</select>\n";
                   14487:     return $Str;
1.31      albertel 14488: }
                   14489: 
1.301     albertel 14490: sub get_samples {
                   14491:     my ($records,$toget) = @_;
                   14492:     my @samples=({});
                   14493:     my $got=0;
                   14494:     foreach my $rec (@$records) {
                   14495: 	my %temp = &record_sep($rec);
                   14496: 	if (! grep(/\S/, values(%temp))) { next; }
                   14497: 	if (%temp) {
                   14498: 	    $samples[$got]=\%temp;
                   14499: 	    $got++;
                   14500: 	    if ($got == $toget) { last; }
                   14501: 	}
                   14502:     }
                   14503:     return \@samples;
                   14504: }
                   14505: 
1.144     matthew  14506: ######################################################
                   14507: ######################################################
                   14508: 
1.56      matthew  14509: =pod
                   14510: 
1.648     raeburn  14511: =item * &csv_print_samples($r,$records)
1.41      ng       14512: 
                   14513: Prints a table of sample values from each column uploaded $r is an
                   14514: Apache Request ref, $records is an arrayref from
                   14515: &Apache::loncommon::upfile_record_sep
                   14516: 
                   14517: =cut
                   14518: 
1.144     matthew  14519: ######################################################
                   14520: ######################################################
1.31      albertel 14521: sub csv_print_samples {
                   14522:     my ($r,$records) = @_;
1.662     bisitz   14523:     my $samples = &get_samples($records,5);
1.301     albertel 14524: 
1.594     raeburn  14525:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14526:               &start_data_table_header_row());
1.356     albertel 14527:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14528:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14529:     $r->print(&end_data_table_header_row());
1.301     albertel 14530:     foreach my $hash (@$samples) {
1.594     raeburn  14531: 	$r->print(&start_data_table_row());
1.356     albertel 14532: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14533: 	    $r->print('<td>');
1.356     albertel 14534: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14535: 	    $r->print('</td>');
                   14536: 	}
1.594     raeburn  14537: 	$r->print(&end_data_table_row());
1.31      albertel 14538:     }
1.594     raeburn  14539:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14540: }
                   14541: 
1.144     matthew  14542: ######################################################
                   14543: ######################################################
                   14544: 
1.56      matthew  14545: =pod
                   14546: 
1.648     raeburn  14547: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14548: 
                   14549: Prints a table to create associations between values and table columns.
1.144     matthew  14550: 
1.41      ng       14551: $r is an Apache Request ref,
                   14552: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14553: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14554: 
                   14555: =cut
                   14556: 
1.144     matthew  14557: ######################################################
                   14558: ######################################################
1.31      albertel 14559: sub csv_print_select_table {
                   14560:     my ($r,$records,$d) = @_;
1.301     albertel 14561:     my $i=0;
                   14562:     my $samples = &get_samples($records,1);
1.144     matthew  14563:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14564: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14565:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14566:               '<th>'.&mt('Column').'</th>'.
                   14567:               &end_data_table_header_row()."\n");
1.356     albertel 14568:     foreach my $array_ref (@$d) {
                   14569: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14570: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14571: 
1.875     bisitz   14572: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14573: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14574: 	$r->print('<option value="none"></option>');
1.356     albertel 14575: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14576: 	    $r->print('<option value="'.$sample.'"'.
                   14577:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14578:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14579: 	}
1.594     raeburn  14580: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14581: 	$i++;
                   14582:     }
1.594     raeburn  14583:     $r->print(&end_data_table());
1.31      albertel 14584:     $i--;
                   14585:     return $i;
                   14586: }
1.56      matthew  14587: 
1.144     matthew  14588: ######################################################
                   14589: ######################################################
                   14590: 
1.56      matthew  14591: =pod
1.31      albertel 14592: 
1.648     raeburn  14593: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14594: 
                   14595: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14596: 
                   14597: $r is an Apache Request ref,
                   14598: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14599: $d is an array of 2 element arrays (internal name, displayed name)
                   14600: 
                   14601: =cut
                   14602: 
1.144     matthew  14603: ######################################################
                   14604: ######################################################
1.31      albertel 14605: sub csv_samples_select_table {
                   14606:     my ($r,$records,$d) = @_;
                   14607:     my $i=0;
1.144     matthew  14608:     #
1.662     bisitz   14609:     my $max_samples = 5;
                   14610:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14611:     $r->print(&start_data_table().
                   14612:               &start_data_table_header_row().'<th>'.
                   14613:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14614:               &end_data_table_header_row());
1.301     albertel 14615: 
                   14616:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14617: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14618: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14619: 	foreach my $option (@$d) {
                   14620: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14621: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14622:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14623:                       $display.'</option>');
1.31      albertel 14624: 	}
                   14625: 	$r->print('</select></td><td>');
1.662     bisitz   14626: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14627: 	    if (defined($samples->[$line]{$key})) { 
                   14628: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14629: 	    }
                   14630: 	}
1.594     raeburn  14631: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14632: 	$i++;
                   14633:     }
1.594     raeburn  14634:     $r->print(&end_data_table());
1.31      albertel 14635:     $i--;
                   14636:     return($i);
1.115     matthew  14637: }
                   14638: 
1.144     matthew  14639: ######################################################
                   14640: ######################################################
                   14641: 
1.115     matthew  14642: =pod
                   14643: 
1.648     raeburn  14644: =item * &clean_excel_name($name)
1.115     matthew  14645: 
                   14646: Returns a replacement for $name which does not contain any illegal characters.
                   14647: 
                   14648: =cut
                   14649: 
1.144     matthew  14650: ######################################################
                   14651: ######################################################
1.115     matthew  14652: sub clean_excel_name {
                   14653:     my ($name) = @_;
                   14654:     $name =~ s/[:\*\?\/\\]//g;
                   14655:     if (length($name) > 31) {
                   14656:         $name = substr($name,0,31);
                   14657:     }
                   14658:     return $name;
1.25      albertel 14659: }
1.84      albertel 14660: 
1.85      albertel 14661: =pod
                   14662: 
1.648     raeburn  14663: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14664: 
                   14665: Returns either 1 or undef
                   14666: 
                   14667: 1 if the part is to be hidden, undef if it is to be shown
                   14668: 
                   14669: Arguments are:
                   14670: 
                   14671: $id the id of the part to be checked
                   14672: $symb, optional the symb of the resource to check
                   14673: $udom, optional the domain of the user to check for
                   14674: $uname, optional the username of the user to check for
                   14675: 
                   14676: =cut
1.84      albertel 14677: 
                   14678: sub check_if_partid_hidden {
                   14679:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14680:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14681: 					 $symb,$udom,$uname);
1.141     albertel 14682:     my $truth=1;
                   14683:     #if the string starts with !, then the list is the list to show not hide
                   14684:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14685:     my @hiddenlist=split(/,/,$hiddenparts);
                   14686:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14687: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14688:     }
1.141     albertel 14689:     return !$truth;
1.84      albertel 14690: }
1.127     matthew  14691: 
1.138     matthew  14692: 
                   14693: ############################################################
                   14694: ############################################################
                   14695: 
                   14696: =pod
                   14697: 
1.157     matthew  14698: =back 
                   14699: 
1.138     matthew  14700: =head1 cgi-bin script and graphing routines
                   14701: 
1.157     matthew  14702: =over 4
                   14703: 
1.648     raeburn  14704: =item * &get_cgi_id()
1.138     matthew  14705: 
                   14706: Inputs: none
                   14707: 
                   14708: Returns an id which can be used to pass environment variables
                   14709: to various cgi-bin scripts.  These environment variables will
                   14710: be removed from the users environment after a given time by
                   14711: the routine &Apache::lonnet::transfer_profile_to_env.
                   14712: 
                   14713: =cut
                   14714: 
                   14715: ############################################################
                   14716: ############################################################
1.152     albertel 14717: my $uniq=0;
1.136     matthew  14718: sub get_cgi_id {
1.154     albertel 14719:     $uniq=($uniq+1)%100000;
1.280     albertel 14720:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14721: }
                   14722: 
1.127     matthew  14723: ############################################################
                   14724: ############################################################
                   14725: 
                   14726: =pod
                   14727: 
1.648     raeburn  14728: =item * &DrawBarGraph()
1.127     matthew  14729: 
1.138     matthew  14730: Facilitates the plotting of data in a (stacked) bar graph.
                   14731: Puts plot definition data into the users environment in order for 
                   14732: graph.png to plot it.  Returns an <img> tag for the plot.
                   14733: The bars on the plot are labeled '1','2',...,'n'.
                   14734: 
                   14735: Inputs:
                   14736: 
                   14737: =over 4
                   14738: 
                   14739: =item $Title: string, the title of the plot
                   14740: 
                   14741: =item $xlabel: string, text describing the X-axis of the plot
                   14742: 
                   14743: =item $ylabel: string, text describing the Y-axis of the plot
                   14744: 
                   14745: =item $Max: scalar, the maximum Y value to use in the plot
                   14746: If $Max is < any data point, the graph will not be rendered.
                   14747: 
1.140     matthew  14748: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14749: they are plotted.  If undefined, default values will be used.
                   14750: 
1.178     matthew  14751: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14752: 
1.138     matthew  14753: =item @Values: An array of array references.  Each array reference holds data
                   14754: to be plotted in a stacked bar chart.
                   14755: 
1.239     matthew  14756: =item If the final element of @Values is a hash reference the key/value
                   14757: pairs will be added to the graph definition.
                   14758: 
1.138     matthew  14759: =back
                   14760: 
                   14761: Returns:
                   14762: 
                   14763: An <img> tag which references graph.png and the appropriate identifying
                   14764: information for the plot.
                   14765: 
1.127     matthew  14766: =cut
                   14767: 
                   14768: ############################################################
                   14769: ############################################################
1.134     matthew  14770: sub DrawBarGraph {
1.178     matthew  14771:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14772:     #
                   14773:     if (! defined($colors)) {
                   14774:         $colors = ['#33ff00', 
                   14775:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14776:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14777:                   ]; 
                   14778:     }
1.228     matthew  14779:     my $extra_settings = {};
                   14780:     if (ref($Values[-1]) eq 'HASH') {
                   14781:         $extra_settings = pop(@Values);
                   14782:     }
1.127     matthew  14783:     #
1.136     matthew  14784:     my $identifier = &get_cgi_id();
                   14785:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14786:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14787:         return '';
                   14788:     }
1.225     matthew  14789:     #
                   14790:     my @Labels;
                   14791:     if (defined($labels)) {
                   14792:         @Labels = @$labels;
                   14793:     } else {
                   14794:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14795:             push(@Labels,$i+1);
1.225     matthew  14796:         }
                   14797:     }
                   14798:     #
1.129     matthew  14799:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14800:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14801:     my %ValuesHash;
                   14802:     my $NumSets=1;
                   14803:     foreach my $array (@Values) {
                   14804:         next if (! ref($array));
1.136     matthew  14805:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14806:             join(',',@$array);
1.129     matthew  14807:     }
1.127     matthew  14808:     #
1.136     matthew  14809:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14810:     if ($NumBars < 3) {
                   14811:         $width = 120+$NumBars*32;
1.220     matthew  14812:         $xskip = 1;
1.225     matthew  14813:         $bar_width = 30;
                   14814:     } elsif ($NumBars < 5) {
                   14815:         $width = 120+$NumBars*20;
                   14816:         $xskip = 1;
                   14817:         $bar_width = 20;
1.220     matthew  14818:     } elsif ($NumBars < 10) {
1.136     matthew  14819:         $width = 120+$NumBars*15;
                   14820:         $xskip = 1;
                   14821:         $bar_width = 15;
                   14822:     } elsif ($NumBars <= 25) {
                   14823:         $width = 120+$NumBars*11;
                   14824:         $xskip = 5;
                   14825:         $bar_width = 8;
                   14826:     } elsif ($NumBars <= 50) {
                   14827:         $width = 120+$NumBars*8;
                   14828:         $xskip = 5;
                   14829:         $bar_width = 4;
                   14830:     } else {
                   14831:         $width = 120+$NumBars*8;
                   14832:         $xskip = 5;
                   14833:         $bar_width = 4;
                   14834:     }
                   14835:     #
1.137     matthew  14836:     $Max = 1 if ($Max < 1);
                   14837:     if ( int($Max) < $Max ) {
                   14838:         $Max++;
                   14839:         $Max = int($Max);
                   14840:     }
1.127     matthew  14841:     $Title  = '' if (! defined($Title));
                   14842:     $xlabel = '' if (! defined($xlabel));
                   14843:     $ylabel = '' if (! defined($ylabel));
1.369     www      14844:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14845:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14846:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14847:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14848:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14849:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14850:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14851:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14852:     $ValuesHash{$id.'.height'}   = $height;
                   14853:     $ValuesHash{$id.'.width'}    = $width;
                   14854:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14855:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14856:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14857:     #
1.228     matthew  14858:     # Deal with other parameters
                   14859:     while (my ($key,$value) = each(%$extra_settings)) {
                   14860:         $ValuesHash{$id.'.'.$key} = $value;
                   14861:     }
                   14862:     #
1.646     raeburn  14863:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14864:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14865: }
                   14866: 
                   14867: ############################################################
                   14868: ############################################################
                   14869: 
                   14870: =pod
                   14871: 
1.648     raeburn  14872: =item * &DrawXYGraph()
1.137     matthew  14873: 
1.138     matthew  14874: Facilitates the plotting of data in an XY graph.
                   14875: Puts plot definition data into the users environment in order for 
                   14876: graph.png to plot it.  Returns an <img> tag for the plot.
                   14877: 
                   14878: Inputs:
                   14879: 
                   14880: =over 4
                   14881: 
                   14882: =item $Title: string, the title of the plot
                   14883: 
                   14884: =item $xlabel: string, text describing the X-axis of the plot
                   14885: 
                   14886: =item $ylabel: string, text describing the Y-axis of the plot
                   14887: 
                   14888: =item $Max: scalar, the maximum Y value to use in the plot
                   14889: If $Max is < any data point, the graph will not be rendered.
                   14890: 
                   14891: =item $colors: Array ref containing the hex color codes for the data to be 
                   14892: plotted in.  If undefined, default values will be used.
                   14893: 
                   14894: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14895: 
                   14896: =item $Ydata: Array ref containing Array refs.  
1.185     www      14897: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14898: 
                   14899: =item %Values: hash indicating or overriding any default values which are 
                   14900: passed to graph.png.  
                   14901: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14902: 
                   14903: =back
                   14904: 
                   14905: Returns:
                   14906: 
                   14907: An <img> tag which references graph.png and the appropriate identifying
                   14908: information for the plot.
                   14909: 
1.137     matthew  14910: =cut
                   14911: 
                   14912: ############################################################
                   14913: ############################################################
                   14914: sub DrawXYGraph {
                   14915:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14916:     #
                   14917:     # Create the identifier for the graph
                   14918:     my $identifier = &get_cgi_id();
                   14919:     my $id = 'cgi.'.$identifier;
                   14920:     #
                   14921:     $Title  = '' if (! defined($Title));
                   14922:     $xlabel = '' if (! defined($xlabel));
                   14923:     $ylabel = '' if (! defined($ylabel));
                   14924:     my %ValuesHash = 
                   14925:         (
1.369     www      14926:          $id.'.title'  => &escape($Title),
                   14927:          $id.'.xlabel' => &escape($xlabel),
                   14928:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14929:          $id.'.y_max_value'=> $Max,
                   14930:          $id.'.labels'     => join(',',@$Xlabels),
                   14931:          $id.'.PlotType'   => 'XY',
                   14932:          );
                   14933:     #
                   14934:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14935:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14936:     }
                   14937:     #
                   14938:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14939:         return '';
                   14940:     }
                   14941:     my $NumSets=1;
1.138     matthew  14942:     foreach my $array (@{$Ydata}){
1.137     matthew  14943:         next if (! ref($array));
                   14944:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14945:     }
1.138     matthew  14946:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14947:     #
                   14948:     # Deal with other parameters
                   14949:     while (my ($key,$value) = each(%Values)) {
                   14950:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14951:     }
                   14952:     #
1.646     raeburn  14953:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14954:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14955: }
                   14956: 
                   14957: ############################################################
                   14958: ############################################################
                   14959: 
                   14960: =pod
                   14961: 
1.648     raeburn  14962: =item * &DrawXYYGraph()
1.138     matthew  14963: 
                   14964: Facilitates the plotting of data in an XY graph with two Y axes.
                   14965: Puts plot definition data into the users environment in order for 
                   14966: graph.png to plot it.  Returns an <img> tag for the plot.
                   14967: 
                   14968: Inputs:
                   14969: 
                   14970: =over 4
                   14971: 
                   14972: =item $Title: string, the title of the plot
                   14973: 
                   14974: =item $xlabel: string, text describing the X-axis of the plot
                   14975: 
                   14976: =item $ylabel: string, text describing the Y-axis of the plot
                   14977: 
                   14978: =item $colors: Array ref containing the hex color codes for the data to be 
                   14979: plotted in.  If undefined, default values will be used.
                   14980: 
                   14981: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14982: 
                   14983: =item $Ydata1: The first data set
                   14984: 
                   14985: =item $Min1: The minimum value of the left Y-axis
                   14986: 
                   14987: =item $Max1: The maximum value of the left Y-axis
                   14988: 
                   14989: =item $Ydata2: The second data set
                   14990: 
                   14991: =item $Min2: The minimum value of the right Y-axis
                   14992: 
                   14993: =item $Max2: The maximum value of the left Y-axis
                   14994: 
                   14995: =item %Values: hash indicating or overriding any default values which are 
                   14996: passed to graph.png.  
                   14997: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14998: 
                   14999: =back
                   15000: 
                   15001: Returns:
                   15002: 
                   15003: An <img> tag which references graph.png and the appropriate identifying
                   15004: information for the plot.
1.136     matthew  15005: 
                   15006: =cut
                   15007: 
                   15008: ############################################################
                   15009: ############################################################
1.137     matthew  15010: sub DrawXYYGraph {
                   15011:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15012:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15013:     #
                   15014:     # Create the identifier for the graph
                   15015:     my $identifier = &get_cgi_id();
                   15016:     my $id = 'cgi.'.$identifier;
                   15017:     #
                   15018:     $Title  = '' if (! defined($Title));
                   15019:     $xlabel = '' if (! defined($xlabel));
                   15020:     $ylabel = '' if (! defined($ylabel));
                   15021:     my %ValuesHash = 
                   15022:         (
1.369     www      15023:          $id.'.title'  => &escape($Title),
                   15024:          $id.'.xlabel' => &escape($xlabel),
                   15025:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15026:          $id.'.labels' => join(',',@$Xlabels),
                   15027:          $id.'.PlotType' => 'XY',
                   15028:          $id.'.NumSets' => 2,
1.137     matthew  15029:          $id.'.two_axes' => 1,
                   15030:          $id.'.y1_max_value' => $Max1,
                   15031:          $id.'.y1_min_value' => $Min1,
                   15032:          $id.'.y2_max_value' => $Max2,
                   15033:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15034:          );
                   15035:     #
1.137     matthew  15036:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15037:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15038:     }
                   15039:     #
                   15040:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15041:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15042:         return '';
                   15043:     }
                   15044:     my $NumSets=1;
1.137     matthew  15045:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15046:         next if (! ref($array));
                   15047:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15048:     }
                   15049:     #
                   15050:     # Deal with other parameters
                   15051:     while (my ($key,$value) = each(%Values)) {
                   15052:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15053:     }
                   15054:     #
1.646     raeburn  15055:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15056:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15057: }
                   15058: 
                   15059: ############################################################
                   15060: ############################################################
                   15061: 
                   15062: =pod
                   15063: 
1.157     matthew  15064: =back 
                   15065: 
1.139     matthew  15066: =head1 Statistics helper routines?  
                   15067: 
                   15068: Bad place for them but what the hell.
                   15069: 
1.157     matthew  15070: =over 4
                   15071: 
1.648     raeburn  15072: =item * &chartlink()
1.139     matthew  15073: 
                   15074: Returns a link to the chart for a specific student.  
                   15075: 
                   15076: Inputs:
                   15077: 
                   15078: =over 4
                   15079: 
                   15080: =item $linktext: The text of the link
                   15081: 
                   15082: =item $sname: The students username
                   15083: 
                   15084: =item $sdomain: The students domain
                   15085: 
                   15086: =back
                   15087: 
1.157     matthew  15088: =back
                   15089: 
1.139     matthew  15090: =cut
                   15091: 
                   15092: ############################################################
                   15093: ############################################################
                   15094: sub chartlink {
                   15095:     my ($linktext, $sname, $sdomain) = @_;
                   15096:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15097:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15098:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15099:        '">'.$linktext.'</a>';
1.153     matthew  15100: }
                   15101: 
                   15102: #######################################################
                   15103: #######################################################
                   15104: 
                   15105: =pod
                   15106: 
                   15107: =head1 Course Environment Routines
1.157     matthew  15108: 
                   15109: =over 4
1.153     matthew  15110: 
1.648     raeburn  15111: =item * &restore_course_settings()
1.153     matthew  15112: 
1.648     raeburn  15113: =item * &store_course_settings()
1.153     matthew  15114: 
                   15115: Restores/Store indicated form parameters from the course environment.
                   15116: Will not overwrite existing values of the form parameters.
                   15117: 
                   15118: Inputs: 
                   15119: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15120: 
                   15121: a hash ref describing the data to be stored.  For example:
                   15122:    
                   15123: %Save_Parameters = ('Status' => 'scalar',
                   15124:     'chartoutputmode' => 'scalar',
                   15125:     'chartoutputdata' => 'scalar',
                   15126:     'Section' => 'array',
1.373     raeburn  15127:     'Group' => 'array',
1.153     matthew  15128:     'StudentData' => 'array',
                   15129:     'Maps' => 'array');
                   15130: 
                   15131: Returns: both routines return nothing
                   15132: 
1.631     raeburn  15133: =back
                   15134: 
1.153     matthew  15135: =cut
                   15136: 
                   15137: #######################################################
                   15138: #######################################################
                   15139: sub store_course_settings {
1.496     albertel 15140:     return &store_settings($env{'request.course.id'},@_);
                   15141: }
                   15142: 
                   15143: sub store_settings {
1.153     matthew  15144:     # save to the environment
                   15145:     # appenv the same items, just to be safe
1.300     albertel 15146:     my $udom  = $env{'user.domain'};
                   15147:     my $uname = $env{'user.name'};
1.496     albertel 15148:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15149:     my %SaveHash;
                   15150:     my %AppHash;
                   15151:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15152:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15153:         my $envname = 'environment.'.$basename;
1.258     albertel 15154:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15155:             # Save this value away
                   15156:             if ($type eq 'scalar' &&
1.258     albertel 15157:                 (! exists($env{$envname}) || 
                   15158:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15159:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15160:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15161:             } elsif ($type eq 'array') {
                   15162:                 my $stored_form;
1.258     albertel 15163:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15164:                     $stored_form = join(',',
                   15165:                                         map {
1.369     www      15166:                                             &escape($_);
1.258     albertel 15167:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15168:                 } else {
                   15169:                     $stored_form = 
1.369     www      15170:                         &escape($env{'form.'.$setting});
1.153     matthew  15171:                 }
                   15172:                 # Determine if the array contents are the same.
1.258     albertel 15173:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15174:                     $SaveHash{$basename} = $stored_form;
                   15175:                     $AppHash{$envname}   = $stored_form;
                   15176:                 }
                   15177:             }
                   15178:         }
                   15179:     }
                   15180:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15181:                                           $udom,$uname);
1.153     matthew  15182:     if ($put_result !~ /^(ok|delayed)/) {
                   15183:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15184:                                  'got error:'.$put_result);
                   15185:     }
                   15186:     # Make sure these settings stick around in this session, too
1.646     raeburn  15187:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15188:     return;
                   15189: }
                   15190: 
                   15191: sub restore_course_settings {
1.499     albertel 15192:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15193: }
                   15194: 
                   15195: sub restore_settings {
                   15196:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15197:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15198:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15199:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15200:             '.'.$setting;
1.258     albertel 15201:         if (exists($env{$envname})) {
1.153     matthew  15202:             if ($type eq 'scalar') {
1.258     albertel 15203:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15204:             } elsif ($type eq 'array') {
1.258     albertel 15205:                 $env{'form.'.$setting} = [ 
1.153     matthew  15206:                                            map { 
1.369     www      15207:                                                &unescape($_); 
1.258     albertel 15208:                                            } split(',',$env{$envname})
1.153     matthew  15209:                                            ];
                   15210:             }
                   15211:         }
                   15212:     }
1.127     matthew  15213: }
                   15214: 
1.618     raeburn  15215: #######################################################
                   15216: #######################################################
                   15217: 
                   15218: =pod
                   15219: 
                   15220: =head1 Domain E-mail Routines  
                   15221: 
                   15222: =over 4
                   15223: 
1.648     raeburn  15224: =item * &build_recipient_list()
1.618     raeburn  15225: 
1.1144    raeburn  15226: Build recipient lists for following types of e-mail:
1.766     raeburn  15227: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15228: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15229: module change checking, student/employee ID conflict checks, as
                   15230: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15231: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15232: 
                   15233: Inputs:
1.619     raeburn  15234: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15235: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15236: requestsmail, updatesmail, or idconflictsmail).
                   15237: 
1.619     raeburn  15238: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15239: 
1.619     raeburn  15240: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15241: i.e., predates configuration by DC via domainprefs.pm
                   15242: 
                   15243: $requname username of requester (if mailing type is helpdeskmail)
                   15244: 
                   15245: $requdom domain of requester (if mailing type is helpdeskmail)
                   15246: 
                   15247: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15248: 
1.618     raeburn  15249: 
1.655     raeburn  15250: Returns: comma separated list of addresses to which to send e-mail.
                   15251: 
                   15252: =back
1.618     raeburn  15253: 
                   15254: =cut
                   15255: 
                   15256: ############################################################
                   15257: ############################################################
                   15258: sub build_recipient_list {
1.1297    raeburn  15259:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15260:     my @recipients;
1.1270    raeburn  15261:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15262:     my %domconfig =
1.1270    raeburn  15263:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15264:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15265:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15266:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15267:                 my @contacts = ('adminemail','supportemail');
                   15268:                 foreach my $item (@contacts) {
                   15269:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15270:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15271:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15272:                             push(@recipients,$addr);
                   15273:                         }
1.619     raeburn  15274:                     }
1.1270    raeburn  15275:                 }
                   15276:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15277:                 if ($mailing eq 'helpdeskmail') {
                   15278:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15279:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15280:                         my @ok_bccs;
                   15281:                         foreach my $bcc (@bccs) {
                   15282:                             $bcc =~ s/^\s+//g;
                   15283:                             $bcc =~ s/\s+$//g;
                   15284:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15285:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15286:                                     push(@ok_bccs,$bcc);
                   15287:                                 }
                   15288:                             }
                   15289:                         }
                   15290:                         if (@ok_bccs > 0) {
                   15291:                             $allbcc = join(', ',@ok_bccs);
                   15292:                         }
                   15293:                     }
                   15294:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15295:                 }
                   15296:             }
1.766     raeburn  15297:         } elsif ($origmail ne '') {
1.1270    raeburn  15298:             $lastresort = $origmail;
1.618     raeburn  15299:         }
1.1297    raeburn  15300:         if ($mailing eq 'helpdeskmail') {
                   15301:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15302:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15303:                 my ($inststatus,$inststatus_checked);
                   15304:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15305:                     ($env{'user.domain'} ne 'public')) {
                   15306:                     $inststatus_checked = 1;
                   15307:                     $inststatus = $env{'environment.inststatus'};
                   15308:                 }
                   15309:                 unless ($inststatus_checked) {
                   15310:                     if (($requname ne '') && ($requdom ne '')) {
                   15311:                         if (($requname =~ /^$match_username$/) &&
                   15312:                             ($requdom =~ /^$match_domain$/) &&
                   15313:                             (&Apache::lonnet::domain($requdom))) {
                   15314:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15315:                                                                       $requdom);
                   15316:                             unless ($requhome eq 'no_host') {
                   15317:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15318:                                 $inststatus = $userenv{'inststatus'};
                   15319:                                 $inststatus_checked = 1;
                   15320:                             }
                   15321:                         }
                   15322:                     }
                   15323:                 }
                   15324:                 unless ($inststatus_checked) {
                   15325:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15326:                         my %srch = (srchby     => 'email',
                   15327:                                     srchdomain => $defdom,
                   15328:                                     srchterm   => $reqemail,
                   15329:                                     srchtype   => 'exact');
                   15330:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15331:                         foreach my $uname (keys(%srch_results)) {
                   15332:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15333:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15334:                                 $inststatus_checked = 1;
                   15335:                                 last;
                   15336:                             }
                   15337:                         }
                   15338:                         unless ($inststatus_checked) {
                   15339:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15340:                             if ($dirsrchres eq 'ok') {
                   15341:                                 foreach my $uname (keys(%srch_results)) {
                   15342:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15343:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15344:                                         $inststatus_checked = 1;
                   15345:                                         last;
                   15346:                                     }
                   15347:                                 }
                   15348:                             }
                   15349:                         }
                   15350:                     }
                   15351:                 }
                   15352:                 if ($inststatus ne '') {
                   15353:                     foreach my $status (split(/\:/,$inststatus)) {
                   15354:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15355:                             my @contacts = ('adminemail','supportemail');
                   15356:                             foreach my $item (@contacts) {
                   15357:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15358:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15359:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15360:                                         push(@recipients,$addr);
                   15361:                                     }
                   15362:                                 }
                   15363:                             }
                   15364:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15365:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15366:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15367:                                 my @ok_bccs;
                   15368:                                 foreach my $bcc (@bccs) {
                   15369:                                     $bcc =~ s/^\s+//g;
                   15370:                                     $bcc =~ s/\s+$//g;
                   15371:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15372:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15373:                                             push(@ok_bccs,$bcc);
                   15374:                                         }
                   15375:                                     }
                   15376:                                 }
                   15377:                                 if (@ok_bccs > 0) {
                   15378:                                     $allbcc = join(', ',@ok_bccs);
                   15379:                                 }
                   15380:                             }
                   15381:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15382:                             last;
                   15383:                         }
                   15384:                     }
                   15385:                 }
                   15386:             }
                   15387:         }
1.619     raeburn  15388:     } elsif ($origmail ne '') {
1.1270    raeburn  15389:         $lastresort = $origmail;
                   15390:     }
1.1297    raeburn  15391:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15392:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15393:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15394:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15395:             my %what = (
                   15396:                           perlvar => 1,
                   15397:                        );
                   15398:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15399:             if ($primary) {
                   15400:                 my $gotaddr;
                   15401:                 my ($result,$returnhash) =
                   15402:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15403:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15404:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15405:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15406:                         $gotaddr = 1;
                   15407:                     }
                   15408:                 }
                   15409:                 unless ($gotaddr) {
                   15410:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15411:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15412:                     unless ($uintdom eq $intdom) {
                   15413:                         my %domconfig =
                   15414:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15415:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15416:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15417:                                 my @contacts = ('adminemail','supportemail');
                   15418:                                 foreach my $item (@contacts) {
                   15419:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15420:                                         my $addr = $domconfig{'contacts'}{$item};
                   15421:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15422:                                             push(@recipients,$addr);
                   15423:                                         }
                   15424:                                     }
                   15425:                                 }
                   15426:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15427:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15428:                                 }
                   15429:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15430:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15431:                                     my @ok_bccs;
                   15432:                                     foreach my $bcc (@bccs) {
                   15433:                                         $bcc =~ s/^\s+//g;
                   15434:                                         $bcc =~ s/\s+$//g;
                   15435:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15436:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15437:                                                 push(@ok_bccs,$bcc);
                   15438:                                             }
                   15439:                                         }
                   15440:                                     }
                   15441:                                     if (@ok_bccs > 0) {
                   15442:                                         $allbcc = join(', ',@ok_bccs);
                   15443:                                     }
                   15444:                                 }
                   15445:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15446:                             }
                   15447:                         }
                   15448:                     }
                   15449:                 }
                   15450:             }
                   15451:         }
1.618     raeburn  15452:     }
1.688     raeburn  15453:     if (defined($defmail)) {
                   15454:         if ($defmail ne '') {
                   15455:             push(@recipients,$defmail);
                   15456:         }
1.618     raeburn  15457:     }
                   15458:     if ($otheremails) {
1.619     raeburn  15459:         my @others;
                   15460:         if ($otheremails =~ /,/) {
                   15461:             @others = split(/,/,$otheremails);
1.618     raeburn  15462:         } else {
1.619     raeburn  15463:             push(@others,$otheremails);
                   15464:         }
                   15465:         foreach my $addr (@others) {
                   15466:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15467:                 push(@recipients,$addr);
                   15468:             }
1.618     raeburn  15469:         }
                   15470:     }
1.1298    raeburn  15471:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15472:         if ((!@recipients) && ($lastresort ne '')) {
                   15473:             push(@recipients,$lastresort);
                   15474:         }
                   15475:     } elsif ($lastresort ne '') {
                   15476:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15477:             push(@recipients,$lastresort);
                   15478:         }
                   15479:     }
1.1271    raeburn  15480:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15481:     if (wantarray) {
                   15482:         return ($recipientlist,$allbcc,$addtext);
                   15483:     } else {
                   15484:         return $recipientlist;
                   15485:     }
1.618     raeburn  15486: }
                   15487: 
1.127     matthew  15488: ############################################################
                   15489: ############################################################
1.154     albertel 15490: 
1.655     raeburn  15491: =pod
                   15492: 
1.1224    musolffc 15493: =over 4
                   15494: 
1.1223    musolffc 15495: =item * &mime_email()
                   15496: 
                   15497: Sends an email with a possible attachment
                   15498: 
                   15499: Inputs:
                   15500: 
                   15501: =over 4
                   15502: 
                   15503: from -              Sender's email address
                   15504: 
1.1343    raeburn  15505: replyto -           Reply-To email address
                   15506: 
1.1223    musolffc 15507: to -                Email address of recipient
                   15508: 
                   15509: subject -           Subject of email
                   15510: 
                   15511: body -              Body of email
                   15512: 
                   15513: cc_string -         Carbon copy email address
                   15514: 
                   15515: bcc -               Blind carbon copy email address
                   15516: 
                   15517: attachment_path -   Path of file to be attached
                   15518: 
                   15519: file_name -         Name of file to be attached
                   15520: 
                   15521: attachment_text -   The body of an attachment of type "TEXT"
                   15522: 
                   15523: =back
                   15524: 
                   15525: =back
                   15526: 
                   15527: =cut
                   15528: 
                   15529: ############################################################
                   15530: ############################################################
                   15531: 
                   15532: sub mime_email {
1.1343    raeburn  15533:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15534:         $file_name,$attachment_text) = @_;
                   15535:  
1.1223    musolffc 15536:     my $msg = MIME::Lite->new(
                   15537:              From    => $from,
                   15538:              To      => $to,
                   15539:              Subject => $subject,
                   15540:              Type    =>'TEXT',
                   15541:              Data    => $body,
                   15542:              );
1.1343    raeburn  15543:     if ($replyto ne '') {
                   15544:         $msg->add("Reply-To" => $replyto);
                   15545:     }
1.1223    musolffc 15546:     if ($cc_string ne '') {
                   15547:         $msg->add("Cc" => $cc_string);
                   15548:     }
                   15549:     if ($bcc ne '') {
                   15550:         $msg->add("Bcc" => $bcc);
                   15551:     }
                   15552:     $msg->attr("content-type"         => "text/plain");
                   15553:     $msg->attr("content-type.charset" => "UTF-8");
                   15554:     # Attach file if given
                   15555:     if ($attachment_path) {
                   15556:         unless ($file_name) {
                   15557:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15558:         }
                   15559:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15560:         $msg->attach(Type     => $type,
                   15561:                      Path     => $attachment_path,
                   15562:                      Filename => $file_name
                   15563:                      );
                   15564:     # Otherwise attach text if given
                   15565:     } elsif ($attachment_text) {
                   15566:         $msg->attach(Type => 'TEXT',
                   15567:                      Data => $attachment_text);
                   15568:     }
                   15569:     # Send it
                   15570:     $msg->send('sendmail');
                   15571: }
                   15572: 
                   15573: ############################################################
                   15574: ############################################################
                   15575: 
                   15576: =pod
                   15577: 
1.655     raeburn  15578: =head1 Course Catalog Routines
                   15579: 
                   15580: =over 4
                   15581: 
                   15582: =item * &gather_categories()
                   15583: 
                   15584: Converts category definitions - keys of categories hash stored in  
                   15585: coursecategories in configuration.db on the primary library server in a 
                   15586: domain - to an array.  Also generates javascript and idx hash used to 
                   15587: generate Domain Coordinator interface for editing Course Categories.
                   15588: 
                   15589: Inputs:
1.663     raeburn  15590: 
1.655     raeburn  15591: categories (reference to hash of category definitions).
1.663     raeburn  15592: 
1.655     raeburn  15593: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15594:       categories and subcategories).
1.663     raeburn  15595: 
1.655     raeburn  15596: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15597:       editing Course Categories).
1.663     raeburn  15598: 
1.655     raeburn  15599: jsarray (reference to array of categories used to create Javascript arrays for
                   15600:          Domain Coordinator interface for editing Course Categories).
                   15601: 
                   15602: Returns: nothing
                   15603: 
                   15604: Side effects: populates cats, idx and jsarray. 
                   15605: 
                   15606: =cut
                   15607: 
                   15608: sub gather_categories {
                   15609:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15610:     my %counters;
                   15611:     my $num = 0;
                   15612:     foreach my $item (keys(%{$categories})) {
                   15613:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15614:         if ($container eq '' && $depth == 0) {
                   15615:             $cats->[$depth][$categories->{$item}] = $cat;
                   15616:         } else {
                   15617:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15618:         }
                   15619:         my ($escitem,$tail) = split(/:/,$item,2);
                   15620:         if ($counters{$tail} eq '') {
                   15621:             $counters{$tail} = $num;
                   15622:             $num ++;
                   15623:         }
                   15624:         if (ref($idx) eq 'HASH') {
                   15625:             $idx->{$item} = $counters{$tail};
                   15626:         }
                   15627:         if (ref($jsarray) eq 'ARRAY') {
                   15628:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15629:         }
                   15630:     }
                   15631:     return;
                   15632: }
                   15633: 
                   15634: =pod
                   15635: 
                   15636: =item * &extract_categories()
                   15637: 
                   15638: Used to generate breadcrumb trails for course categories.
                   15639: 
                   15640: Inputs:
1.663     raeburn  15641: 
1.655     raeburn  15642: categories (reference to hash of category definitions).
1.663     raeburn  15643: 
1.655     raeburn  15644: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15645:       categories and subcategories).
1.663     raeburn  15646: 
1.655     raeburn  15647: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15648: 
1.655     raeburn  15649: allitems (reference to hash - key is category key 
                   15650:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15651: 
1.655     raeburn  15652: idx (reference to hash of counters used in Domain Coordinator interface for
                   15653:       editing Course Categories).
1.663     raeburn  15654: 
1.655     raeburn  15655: jsarray (reference to array of categories used to create Javascript arrays for
                   15656:          Domain Coordinator interface for editing Course Categories).
                   15657: 
1.665     raeburn  15658: subcats (reference to hash of arrays containing all subcategories within each 
                   15659:          category, -recursive)
                   15660: 
1.1321    raeburn  15661: maxd (reference to hash used to hold max depth for all top-level categories).
                   15662: 
1.655     raeburn  15663: Returns: nothing
                   15664: 
                   15665: Side effects: populates trails and allitems hash references.
                   15666: 
                   15667: =cut
                   15668: 
                   15669: sub extract_categories {
1.1321    raeburn  15670:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15671:     if (ref($categories) eq 'HASH') {
                   15672:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15673:         if (ref($cats->[0]) eq 'ARRAY') {
                   15674:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15675:                 my $name = $cats->[0][$i];
                   15676:                 my $item = &escape($name).'::0';
                   15677:                 my $trailstr;
                   15678:                 if ($name eq 'instcode') {
                   15679:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15680:                 } elsif ($name eq 'communities') {
                   15681:                     $trailstr = &mt('Communities');
1.1239    raeburn  15682:                 } elsif ($name eq 'placement') {
                   15683:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15684:                 } else {
                   15685:                     $trailstr = $name;
                   15686:                 }
                   15687:                 if ($allitems->{$item} eq '') {
                   15688:                     push(@{$trails},$trailstr);
                   15689:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15690:                 }
                   15691:                 my @parents = ($name);
                   15692:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15693:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15694:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15695:                         if (ref($subcats) eq 'HASH') {
                   15696:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15697:                         }
1.1321    raeburn  15698:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15699:                     }
                   15700:                 } else {
                   15701:                     if (ref($subcats) eq 'HASH') {
                   15702:                         $subcats->{$item} = [];
1.655     raeburn  15703:                     }
1.1321    raeburn  15704:                     if (ref($maxd) eq 'HASH') {
                   15705:                         $maxd->{$name} = 1;
                   15706:                     }
1.655     raeburn  15707:                 }
                   15708:             }
                   15709:         }
                   15710:     }
                   15711:     return;
                   15712: }
                   15713: 
                   15714: =pod
                   15715: 
1.1162    raeburn  15716: =item * &recurse_categories()
1.655     raeburn  15717: 
                   15718: Recursively used to generate breadcrumb trails for course categories.
                   15719: 
                   15720: Inputs:
1.663     raeburn  15721: 
1.655     raeburn  15722: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15723:       categories and subcategories).
1.663     raeburn  15724: 
1.655     raeburn  15725: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15726: 
                   15727: category (current course category, for which breadcrumb trail is being generated).
                   15728: 
                   15729: trails (reference to array of breadcrumb trails for each category).
                   15730: 
1.655     raeburn  15731: allitems (reference to hash - key is category key
                   15732:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15733: 
1.655     raeburn  15734: parents (array containing containers directories for current category, 
                   15735:          back to top level). 
                   15736: 
                   15737: Returns: nothing
                   15738: 
                   15739: Side effects: populates trails and allitems hash references
                   15740: 
                   15741: =cut
                   15742: 
                   15743: sub recurse_categories {
1.1321    raeburn  15744:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15745:     my $shallower = $depth - 1;
                   15746:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15747:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15748:             my $name = $cats->[$depth]{$category}[$k];
                   15749:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15750:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15751:             if ($allitems->{$item} eq '') {
                   15752:                 push(@{$trails},$trailstr);
                   15753:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15754:             }
                   15755:             my $deeper = $depth+1;
                   15756:             push(@{$parents},$category);
1.665     raeburn  15757:             if (ref($subcats) eq 'HASH') {
                   15758:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15759:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15760:                     my $higher;
                   15761:                     if ($j > 0) {
                   15762:                         $higher = &escape($parents->[$j]).':'.
                   15763:                                   &escape($parents->[$j-1]).':'.$j;
                   15764:                     } else {
                   15765:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15766:                     }
                   15767:                     push(@{$subcats->{$higher}},$subcat);
                   15768:                 }
                   15769:             }
                   15770:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15771:                                 $subcats,$maxd);
1.655     raeburn  15772:             pop(@{$parents});
                   15773:         }
                   15774:     } else {
                   15775:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15776:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15777:         if ($allitems->{$item} eq '') {
                   15778:             push(@{$trails},$trailstr);
                   15779:             $allitems->{$item} = scalar(@{$trails})-1;
                   15780:         }
1.1321    raeburn  15781:         if (ref($maxd) eq 'HASH') {
                   15782:             if ($depth > $maxd->{$parents->[0]}) {
                   15783:                 $maxd->{$parents->[0]} = $depth;
                   15784:             }
                   15785:         }
1.655     raeburn  15786:     }
                   15787:     return;
                   15788: }
                   15789: 
1.663     raeburn  15790: =pod
                   15791: 
1.1162    raeburn  15792: =item * &assign_categories_table()
1.663     raeburn  15793: 
                   15794: Create a datatable for display of hierarchical categories in a domain,
                   15795: with checkboxes to allow a course to be categorized. 
                   15796: 
                   15797: Inputs:
                   15798: 
                   15799: cathash - reference to hash of categories defined for the domain (from
                   15800:           configuration.db)
                   15801: 
                   15802: currcat - scalar with an & separated list of categories assigned to a course. 
                   15803: 
1.919     raeburn  15804: type    - scalar contains course type (Course or Community).
                   15805: 
1.1260    raeburn  15806: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15807:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15808: 
1.663     raeburn  15809: Returns: $output (markup to be displayed) 
                   15810: 
                   15811: =cut
                   15812: 
                   15813: sub assign_categories_table {
1.1259    raeburn  15814:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15815:     my $output;
                   15816:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15817:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15818:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15819:         $maxdepth = scalar(@cats);
                   15820:         if (@cats > 0) {
                   15821:             my $itemcount = 0;
                   15822:             if (ref($cats[0]) eq 'ARRAY') {
                   15823:                 my @currcategories;
                   15824:                 if ($currcat ne '') {
                   15825:                     @currcategories = split('&',$currcat);
                   15826:                 }
1.919     raeburn  15827:                 my $table;
1.663     raeburn  15828:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15829:                     my $parent = $cats[0][$i];
1.919     raeburn  15830:                     next if ($parent eq 'instcode');
                   15831:                     if ($type eq 'Community') {
                   15832:                         next unless ($parent eq 'communities');
1.1239    raeburn  15833:                     } elsif ($type eq 'Placement') {
                   15834:                         next unless ($parent eq 'placement');
1.919     raeburn  15835:                     } else {
1.1239    raeburn  15836:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15837:                     }
1.663     raeburn  15838:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15839:                     my $item = &escape($parent).'::0';
                   15840:                     my $checked = '';
                   15841:                     if (@currcategories > 0) {
                   15842:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15843:                             $checked = ' checked="checked"';
1.663     raeburn  15844:                         }
                   15845:                     }
1.919     raeburn  15846:                     my $parent_title = $parent;
                   15847:                     if ($parent eq 'communities') {
                   15848:                         $parent_title = &mt('Communities');
1.1239    raeburn  15849:                     } elsif ($parent eq 'placement') {
                   15850:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15851:                     }
                   15852:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15853:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15854:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15855:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15856:                     my $depth = 1;
                   15857:                     push(@path,$parent);
1.1259    raeburn  15858:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15859:                     pop(@path);
1.919     raeburn  15860:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15861:                     $itemcount ++;
                   15862:                 }
1.919     raeburn  15863:                 if ($itemcount) {
                   15864:                     $output = &Apache::loncommon::start_data_table().
                   15865:                               $table.
                   15866:                               &Apache::loncommon::end_data_table();
                   15867:                 }
1.663     raeburn  15868:             }
                   15869:         }
                   15870:     }
                   15871:     return $output;
                   15872: }
                   15873: 
                   15874: =pod
                   15875: 
1.1162    raeburn  15876: =item * &assign_category_rows()
1.663     raeburn  15877: 
                   15878: Create a datatable row for display of nested categories in a domain,
                   15879: with checkboxes to allow a course to be categorized,called recursively.
                   15880: 
                   15881: Inputs:
                   15882: 
                   15883: itemcount - track row number for alternating colors
                   15884: 
                   15885: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15886:       categories and subcategories.
                   15887: 
                   15888: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15889: 
                   15890: parent - parent of current category item
                   15891: 
                   15892: path - Array containing all categories back up through the hierarchy from the
                   15893:        current category to the top level.
                   15894: 
                   15895: currcategories - reference to array of current categories assigned to the course
                   15896: 
1.1260    raeburn  15897: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15898:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15899: 
1.663     raeburn  15900: Returns: $output (markup to be displayed).
                   15901: 
                   15902: =cut
                   15903: 
                   15904: sub assign_category_rows {
1.1259    raeburn  15905:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15906:     my ($text,$name,$item,$chgstr);
                   15907:     if (ref($cats) eq 'ARRAY') {
                   15908:         my $maxdepth = scalar(@{$cats});
                   15909:         if (ref($cats->[$depth]) eq 'HASH') {
                   15910:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15911:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15912:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15913:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15914:                 for (my $j=0; $j<$numchildren; $j++) {
                   15915:                     $name = $cats->[$depth]{$parent}[$j];
                   15916:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15917:                     my $deeper = $depth+1;
                   15918:                     my $checked = '';
                   15919:                     if (ref($currcategories) eq 'ARRAY') {
                   15920:                         if (@{$currcategories} > 0) {
                   15921:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15922:                                 $checked = ' checked="checked"';
1.663     raeburn  15923:                             }
                   15924:                         }
                   15925:                     }
1.664     raeburn  15926:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15927:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15928:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15929:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15930:                              '</td><td>';
1.663     raeburn  15931:                     if (ref($path) eq 'ARRAY') {
                   15932:                         push(@{$path},$name);
1.1259    raeburn  15933:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15934:                         pop(@{$path});
                   15935:                     }
                   15936:                     $text .= '</td></tr>';
                   15937:                 }
                   15938:                 $text .= '</table></td>';
                   15939:             }
                   15940:         }
                   15941:     }
                   15942:     return $text;
                   15943: }
                   15944: 
1.1181    raeburn  15945: =pod
                   15946: 
                   15947: =back
                   15948: 
                   15949: =cut
                   15950: 
1.655     raeburn  15951: ############################################################
                   15952: ############################################################
                   15953: 
                   15954: 
1.443     albertel 15955: sub commit_customrole {
1.664     raeburn  15956:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15957:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15958:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15959:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15960:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15961:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15962:                  '</b><br />';
                   15963:     return $output;
                   15964: }
                   15965: 
                   15966: sub commit_standardrole {
1.1116    raeburn  15967:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15968:     my ($output,$logmsg,$linefeed);
                   15969:     if ($context eq 'auto') {
                   15970:         $linefeed = "\n";
                   15971:     } else {
                   15972:         $linefeed = "<br />\n";
                   15973:     }  
1.443     albertel 15974:     if ($three eq 'st') {
1.541     raeburn  15975:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15976:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15977:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15978:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15979:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15980:         } else {
1.541     raeburn  15981:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15982:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15983:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15984:             if ($context eq 'auto') {
                   15985:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15986:             } else {
                   15987:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15988:                &mt('Add to classlist').': <b>ok</b>';
                   15989:             }
                   15990:             $output .= $linefeed;
1.443     albertel 15991:         }
                   15992:     } else {
                   15993:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15994:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15995:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15996:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15997:         if ($context eq 'auto') {
                   15998:             $output .= $result.$linefeed;
                   15999:         } else {
                   16000:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16001:         }
1.443     albertel 16002:     }
                   16003:     return $output;
                   16004: }
                   16005: 
                   16006: sub commit_studentrole {
1.1116    raeburn  16007:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16008:         $credits) = @_;
1.626     raeburn  16009:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16010:     if ($context eq 'auto') {
                   16011:         $linefeed = "\n";
                   16012:     } else {
                   16013:         $linefeed = '<br />'."\n";
                   16014:     }
1.443     albertel 16015:     if (defined($one) && defined($two)) {
                   16016:         my $cid=$one.'_'.$two;
                   16017:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16018:         my $secchange = 0;
                   16019:         my $expire_role_result;
                   16020:         my $modify_section_result;
1.628     raeburn  16021:         if ($oldsec ne '-1') { 
                   16022:             if ($oldsec ne $sec) {
1.443     albertel 16023:                 $secchange = 1;
1.628     raeburn  16024:                 my $now = time;
1.443     albertel 16025:                 my $uurl='/'.$cid;
                   16026:                 $uurl=~s/\_/\//g;
                   16027:                 if ($oldsec) {
                   16028:                     $uurl.='/'.$oldsec;
                   16029:                 }
1.626     raeburn  16030:                 $oldsecurl = $uurl;
1.628     raeburn  16031:                 $expire_role_result = 
1.652     raeburn  16032:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16033:                 if ($env{'request.course.sec'} ne '') { 
                   16034:                     if ($expire_role_result eq 'refused') {
                   16035:                         my @roles = ('st');
                   16036:                         my @statuses = ('previous');
                   16037:                         my @roledoms = ($one);
                   16038:                         my $withsec = 1;
                   16039:                         my %roleshash = 
                   16040:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16041:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16042:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16043:                             my ($oldstart,$oldend) = 
                   16044:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16045:                             if ($oldend > 0 && $oldend <= $now) {
                   16046:                                 $expire_role_result = 'ok';
                   16047:                             }
                   16048:                         }
                   16049:                     }
                   16050:                 }
1.443     albertel 16051:                 $result = $expire_role_result;
                   16052:             }
                   16053:         }
                   16054:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16055:             $modify_section_result = 
                   16056:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16057:                                                            undef,undef,undef,$sec,
                   16058:                                                            $end,$start,'','',$cid,
                   16059:                                                            '',$context,$credits);
1.443     albertel 16060:             if ($modify_section_result =~ /^ok/) {
                   16061:                 if ($secchange == 1) {
1.628     raeburn  16062:                     if ($sec eq '') {
                   16063:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16064:                     } else {
                   16065:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16066:                     }
1.443     albertel 16067:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16068:                     if ($sec eq '') {
                   16069:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16070:                     } else {
                   16071:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16072:                     }
1.443     albertel 16073:                 } else {
1.628     raeburn  16074:                     if ($sec eq '') {
                   16075:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16076:                     } else {
                   16077:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16078:                     }
1.443     albertel 16079:                 }
                   16080:             } else {
1.1115    raeburn  16081:                 if ($secchange) { 
1.628     raeburn  16082:                     $$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;
                   16083:                 } else {
                   16084:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16085:                 }
1.443     albertel 16086:             }
                   16087:             $result = $modify_section_result;
                   16088:         } elsif ($secchange == 1) {
1.628     raeburn  16089:             if ($oldsec eq '') {
1.1103    raeburn  16090:                 $$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  16091:             } else {
                   16092:                 $$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;
                   16093:             }
1.626     raeburn  16094:             if ($expire_role_result eq 'refused') {
                   16095:                 my $newsecurl = '/'.$cid;
                   16096:                 $newsecurl =~ s/\_/\//g;
                   16097:                 if ($sec ne '') {
                   16098:                     $newsecurl.='/'.$sec;
                   16099:                 }
                   16100:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16101:                     if ($sec eq '') {
                   16102:                         $$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;
                   16103:                     } else {
                   16104:                         $$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;
                   16105:                     }
                   16106:                 }
                   16107:             }
1.443     albertel 16108:         }
                   16109:     } else {
1.626     raeburn  16110:         $$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 16111:         $result = "error: incomplete course id\n";
                   16112:     }
                   16113:     return $result;
                   16114: }
                   16115: 
1.1108    raeburn  16116: sub show_role_extent {
                   16117:     my ($scope,$context,$role) = @_;
                   16118:     $scope =~ s{^/}{};
                   16119:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16120:     push(@courseroles,'co');
                   16121:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16122:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16123:         $scope =~ s{/}{_};
                   16124:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16125:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16126:         my ($audom,$auname) = split(/\//,$scope);
                   16127:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16128:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16129:     } else {
                   16130:         $scope =~ s{/$}{};
                   16131:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16132:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16133:     }
                   16134: }
                   16135: 
1.443     albertel 16136: ############################################################
                   16137: ############################################################
                   16138: 
1.566     albertel 16139: sub check_clone {
1.578     raeburn  16140:     my ($args,$linefeed) = @_;
1.566     albertel 16141:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16142:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16143:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16144:     my $clonetitle;
                   16145:     my @clonemsg;
1.566     albertel 16146:     my $can_clone = 0;
1.944     raeburn  16147:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16148:     if ($lctype ne 'community') {
                   16149:         $lctype = 'course';
                   16150:     }
1.566     albertel 16151:     if ($clonehome eq 'no_host') {
1.944     raeburn  16152:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16153:             push(@clonemsg,({
                   16154:                               mt => 'No new community created.',
                   16155:                               args => [],
                   16156:                             },
                   16157:                             {
                   16158:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16159:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16160:                             }));
1.908     raeburn  16161:         } else {
1.1344    raeburn  16162:             push(@clonemsg,({
                   16163:                               mt => 'No new course created.',
                   16164:                               args => [],
                   16165:                             },
                   16166:                             {
                   16167:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16168:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16169:                             }));
                   16170:         }
1.566     albertel 16171:     } else {
                   16172: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16173:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16174:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16175:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16176:                 push(@clonemsg,({
                   16177:                                   mt => 'No new community created.',
                   16178:                                   args => [],
                   16179:                                 },
                   16180:                                 {
                   16181:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16182:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16183:                                 }));
                   16184:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16185:             }
                   16186:         }
1.1262    raeburn  16187: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16188:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16189: 	    $can_clone = 1;
                   16190: 	} else {
1.1221    raeburn  16191: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16192: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16193:             if ($clonehash{'cloners'} eq '') {
                   16194:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16195:                 if ($domdefs{'canclone'}) {
                   16196:                     unless ($domdefs{'canclone'} eq 'none') {
                   16197:                         if ($domdefs{'canclone'} eq 'domain') {
                   16198:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16199:                                 $can_clone = 1;
                   16200:                             }
                   16201:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16202:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16203:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16204:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16205:                                 $can_clone = 1;
                   16206:                             }
                   16207:                         }
                   16208:                     }
                   16209:                 }
1.578     raeburn  16210:             } else {
1.1221    raeburn  16211: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16212:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16213:                     $can_clone = 1;
1.1221    raeburn  16214:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16215:                     $can_clone = 1;
1.1225    raeburn  16216:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16217:                     $can_clone = 1;
1.1221    raeburn  16218:                 }
                   16219:                 unless ($can_clone) {
1.1225    raeburn  16220:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16221:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16222:                         my (%gotdomdefaults,%gotcodedefaults);
                   16223:                         foreach my $cloner (@cloners) {
                   16224:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16225:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16226:                                 my (%codedefaults,@code_order);
                   16227:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16228:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16229:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16230:                                     }
                   16231:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16232:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16233:                                     }
                   16234:                                 } else {
                   16235:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16236:                                                                             \%codedefaults,
                   16237:                                                                             \@code_order);
                   16238:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16239:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16240:                                 }
                   16241:                                 if (@code_order > 0) {
                   16242:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16243:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16244:                                                                                 $args->{'crscode'})) {
                   16245:                                         $can_clone = 1;
                   16246:                                         last;
                   16247:                                     }
                   16248:                                 }
                   16249:                             }
                   16250:                         }
                   16251:                     }
1.1225    raeburn  16252:                 }
                   16253:             }
                   16254:             unless ($can_clone) {
                   16255:                 my $ccrole = 'cc';
                   16256:                 if ($args->{'crstype'} eq 'Community') {
                   16257:                     $ccrole = 'co';
                   16258:                 }
                   16259: 	        my %roleshash =
                   16260: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16261: 					          $args->{'ccdomain'},
                   16262:                                                   'userroles',['active'],[$ccrole],
                   16263: 					          [$args->{'clonedomain'}]);
                   16264: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16265:                     $can_clone = 1;
                   16266:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16267:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16268:                     $can_clone = 1;
1.1221    raeburn  16269:                 }
                   16270:             }
                   16271:             unless ($can_clone) {
                   16272:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16273:                     push(@clonemsg,({
                   16274:                                       mt => 'No new community created.',
                   16275:                                       args => [],
                   16276:                                     },
                   16277:                                     {
                   16278:                                       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]).',
                   16279:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16280:                                     }));
1.942     raeburn  16281:                 } else {
1.1344    raeburn  16282:                     push(@clonemsg,({
                   16283:                                       mt => 'No new course created.',
                   16284:                                       args => [],
                   16285:                                     },
                   16286:                                     {
                   16287:                                       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]).',
                   16288:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16289:                                     }));
1.1221    raeburn  16290:                 }
1.566     albertel 16291: 	    }
1.578     raeburn  16292:         }
1.566     albertel 16293:     }
1.1344    raeburn  16294:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16295: }
                   16296: 
1.444     albertel 16297: sub construct_course {
1.1262    raeburn  16298:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16299:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16300:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16301:     my $linefeed =  '<br />'."\n";
                   16302:     if ($context eq 'auto') {
                   16303:         $linefeed = "\n";
                   16304:     }
1.566     albertel 16305: 
                   16306: #
                   16307: # Are we cloning?
                   16308: #
1.1344    raeburn  16309:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16310:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16311: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16312:         if (!$can_clone) {
1.1344    raeburn  16313: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16314: 	}
                   16315:     }
                   16316: 
1.444     albertel 16317: #
                   16318: # Open course
                   16319: #
1.1239    raeburn  16320:     my $showncrstype;
                   16321:     if ($args->{'crstype'} eq 'Placement') {
                   16322:         $showncrstype = 'placement test'; 
                   16323:     } else {  
                   16324:         $showncrstype = lc($args->{'crstype'});
                   16325:     }
1.444     albertel 16326:     my %cenv=();
                   16327:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16328:                                              $args->{'cdescr'},
                   16329:                                              $args->{'curl'},
                   16330:                                              $args->{'course_home'},
                   16331:                                              $args->{'nonstandard'},
                   16332:                                              $args->{'crscode'},
                   16333:                                              $args->{'ccuname'}.':'.
                   16334:                                              $args->{'ccdomain'},
1.882     raeburn  16335:                                              $args->{'crstype'},
1.1344    raeburn  16336:                                              $cnum,$context,$category,
                   16337:                                              $callercontext);
1.444     albertel 16338: 
                   16339:     # Note: The testing routines depend on this being output; see 
                   16340:     # Utils::Course. This needs to at least be output as a comment
                   16341:     # if anyone ever decides to not show this, and Utils::Course::new
                   16342:     # will need to be suitably modified.
1.1344    raeburn  16343:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16344:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16345:     } else {
                   16346:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16347:     }
1.943     raeburn  16348:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16349:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16350:     }
                   16351: 
1.444     albertel 16352: #
                   16353: # Check if created correctly
                   16354: #
1.479     albertel 16355:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16356:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16357:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16358:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16359:             $outcome .= &mt_user($user_lh,
                   16360:                             'Course creation failed, unrecognized course home server.');
                   16361:         } else {
                   16362:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16363:         }
                   16364:         $outcome .= $linefeed;
                   16365:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16366:     }
1.541     raeburn  16367:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16368: 
1.444     albertel 16369: #
1.566     albertel 16370: # Do the cloning
                   16371: #   
1.1344    raeburn  16372:     my @clonemsg;
1.566     albertel 16373:     if ($can_clone && $cloneid) {
1.1344    raeburn  16374:         push(@clonemsg,
                   16375:                       {
                   16376:                           mt => 'Created [_1] by cloning from [_2]',
                   16377:                           args => [$showncrstype,$clonetitle],
                   16378:                       });
1.566     albertel 16379: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16380: # Copy all files
1.1344    raeburn  16381:         my @info =
                   16382: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16383: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16384:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16385:                                                      $args->{'tinyurls'});
                   16386:         if (@info) {
                   16387:             push(@clonemsg,@info);
                   16388:         }
1.444     albertel 16389: # Restore URL
1.566     albertel 16390: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16391: # Restore title
1.566     albertel 16392: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16393: # Restore creation date, creator and creation context.
                   16394:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16395:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16396:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16397: # Mark as cloned
1.566     albertel 16398: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16399: # Need to clone grading mode
                   16400:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16401:         $cenv{'grading'}=$newenv{'grading'};
                   16402: # Do not clone these environment entries
                   16403:         &Apache::lonnet::del('environment',
                   16404:                   ['default_enrollment_start_date',
                   16405:                    'default_enrollment_end_date',
                   16406:                    'question.email',
                   16407:                    'policy.email',
                   16408:                    'comment.email',
                   16409:                    'pch.users.denied',
1.725     raeburn  16410:                    'plc.users.denied',
                   16411:                    'hidefromcat',
1.1121    raeburn  16412:                    'checkforpriv',
1.1355    raeburn  16413:                    'categories'],
1.638     www      16414:                    $$crsudom,$$crsunum);
1.1170    raeburn  16415:         if ($args->{'textbook'}) {
                   16416:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16417:         }
1.444     albertel 16418:     }
1.566     albertel 16419: 
1.444     albertel 16420: #
                   16421: # Set environment (will override cloned, if existing)
                   16422: #
                   16423:     my @sections = ();
                   16424:     my @xlists = ();
                   16425:     if ($args->{'crstype'}) {
                   16426:         $cenv{'type'}=$args->{'crstype'};
                   16427:     }
                   16428:     if ($args->{'crsid'}) {
                   16429:         $cenv{'courseid'}=$args->{'crsid'};
                   16430:     }
                   16431:     if ($args->{'crscode'}) {
                   16432:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16433:     }
                   16434:     if ($args->{'crsquota'} ne '') {
                   16435:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16436:     } else {
                   16437:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16438:     }
                   16439:     if ($args->{'ccuname'}) {
                   16440:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16441:                                         ':'.$args->{'ccdomain'};
                   16442:     } else {
                   16443:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16444:     }
1.1116    raeburn  16445:     if ($args->{'defaultcredits'}) {
                   16446:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16447:     }
1.444     albertel 16448:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16449:     if ($args->{'crssections'}) {
                   16450:         $cenv{'internal.sectionnums'} = '';
                   16451:         if ($args->{'crssections'} =~ m/,/) {
                   16452:             @sections = split/,/,$args->{'crssections'};
                   16453:         } else {
                   16454:             $sections[0] = $args->{'crssections'};
                   16455:         }
                   16456:         if (@sections > 0) {
                   16457:             foreach my $item (@sections) {
                   16458:                 my ($sec,$gp) = split/:/,$item;
                   16459:                 my $class = $args->{'crscode'}.$sec;
                   16460:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16461:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16462:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16463:                     push(@badclasses,$class);
1.444     albertel 16464:                 }
                   16465:             }
                   16466:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16467:         }
                   16468:     }
                   16469: # do not hide course coordinator from staff listing, 
                   16470: # even if privileged
                   16471:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16472: # add course coordinator's domain to domains to check for privileged users
                   16473: # if different to course domain
                   16474:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16475:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16476:     }
1.444     albertel 16477: # add crosslistings
                   16478:     if ($args->{'crsxlist'}) {
                   16479:         $cenv{'internal.crosslistings'}='';
                   16480:         if ($args->{'crsxlist'} =~ m/,/) {
                   16481:             @xlists = split/,/,$args->{'crsxlist'};
                   16482:         } else {
                   16483:             $xlists[0] = $args->{'crsxlist'};
                   16484:         }
                   16485:         if (@xlists > 0) {
                   16486:             foreach my $item (@xlists) {
                   16487:                 my ($xl,$gp) = split/:/,$item;
                   16488:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16489:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16490:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16491:                     push(@badclasses,$xl);
1.444     albertel 16492:                 }
                   16493:             }
                   16494:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16495:         }
                   16496:     }
                   16497:     if ($args->{'autoadds'}) {
                   16498:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16499:     }
                   16500:     if ($args->{'autodrops'}) {
                   16501:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16502:     }
                   16503: # check for notification of enrollment changes
                   16504:     my @notified = ();
                   16505:     if ($args->{'notify_owner'}) {
                   16506:         if ($args->{'ccuname'} ne '') {
                   16507:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16508:         }
                   16509:     }
                   16510:     if ($args->{'notify_dc'}) {
                   16511:         if ($uname ne '') { 
1.630     raeburn  16512:             push(@notified,$uname.':'.$udom);
1.444     albertel 16513:         }
                   16514:     }
                   16515:     if (@notified > 0) {
                   16516:         my $notifylist;
                   16517:         if (@notified > 1) {
                   16518:             $notifylist = join(',',@notified);
                   16519:         } else {
                   16520:             $notifylist = $notified[0];
                   16521:         }
                   16522:         $cenv{'internal.notifylist'} = $notifylist;
                   16523:     }
                   16524:     if (@badclasses > 0) {
                   16525:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16526:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16527:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16528:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16529:         );
1.1264    raeburn  16530:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16531:                            &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  16532:         if ($context eq 'auto') {
                   16533:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16534:         } else {
1.566     albertel 16535:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16536:         }
                   16537:         foreach my $item (@badclasses) {
1.541     raeburn  16538:             if ($context eq 'auto') {
1.1261    raeburn  16539:                 $outcome .= " - $item\n";
1.541     raeburn  16540:             } else {
1.1261    raeburn  16541:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16542:             }
1.1261    raeburn  16543:         }
                   16544:         if ($context eq 'auto') {
                   16545:             $outcome .= $linefeed;
                   16546:         } else {
                   16547:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16548:         } 
1.444     albertel 16549:     }
                   16550:     if ($args->{'no_end_date'}) {
                   16551:         $args->{'endaccess'} = 0;
                   16552:     }
                   16553:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16554:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16555:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16556:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16557:     if ($args->{'showphotos'}) {
                   16558:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16559:     }
                   16560:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16561:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16562:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16563:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16564:             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'); 
                   16565:             if ($context eq 'auto') {
                   16566:                 $outcome .= $krb_msg;
                   16567:             } else {
1.566     albertel 16568:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16569:             }
                   16570:             $outcome .= $linefeed;
1.444     albertel 16571:         }
                   16572:     }
                   16573:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16574:        if ($args->{'setpolicy'}) {
                   16575:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16576:        }
                   16577:        if ($args->{'setcontent'}) {
                   16578:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16579:        }
1.1251    raeburn  16580:        if ($args->{'setcomment'}) {
                   16581:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16582:        }
1.444     albertel 16583:     }
                   16584:     if ($args->{'reshome'}) {
                   16585: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16586: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16587:     }
                   16588: #
                   16589: # course has keyed access
                   16590: #
                   16591:     if ($args->{'setkeys'}) {
                   16592:        $cenv{'keyaccess'}='yes';
                   16593:     }
                   16594: # if specified, key authority is not course, but user
                   16595: # only active if keyaccess is yes
                   16596:     if ($args->{'keyauth'}) {
1.487     albertel 16597: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16598: 	$user = &LONCAPA::clean_username($user);
                   16599: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16600: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16601: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16602: 	}
                   16603:     }
                   16604: 
1.1166    raeburn  16605: #
1.1167    raeburn  16606: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16607: #
                   16608:     if ($args->{'uniquecode'}) {
                   16609:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16610:         if ($code) {
                   16611:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16612:             my %crsinfo =
                   16613:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16614:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16615:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16616:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16617:             } 
1.1166    raeburn  16618:             if (ref($coderef)) {
                   16619:                 $$coderef = $code;
                   16620:             }
                   16621:         }
                   16622:     }
                   16623: 
1.444     albertel 16624:     if ($args->{'disresdis'}) {
                   16625:         $cenv{'pch.roles.denied'}='st';
                   16626:     }
                   16627:     if ($args->{'disablechat'}) {
                   16628:         $cenv{'plc.roles.denied'}='st';
                   16629:     }
                   16630: 
                   16631:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16632:     # course
                   16633:     $cenv{'course.helper.not.run'} = 1;
                   16634:     #
                   16635:     # Use new Randomseed
                   16636:     #
                   16637:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16638:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16639:     #
                   16640:     # The encryption code and receipt prefix for this course
                   16641:     #
                   16642:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16643:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16644:     #
                   16645:     # By default, use standard grading
                   16646:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16647: 
1.541     raeburn  16648:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16649:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16650: #
                   16651: # Open all assignments
                   16652: #
                   16653:     if ($args->{'openall'}) {
1.1341    raeburn  16654:        my $opendate = time;
                   16655:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16656:            $opendate = $args->{'openallfrom'};
                   16657:        }
1.444     albertel 16658:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16659:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16660:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16661:        $outcome .= &mt('All assignments open starting [_1]',
                   16662:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16663:                    &Apache::lonnet::cput
                   16664:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16665:    }
                   16666: #
                   16667: # Set first page
                   16668: #
                   16669:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16670: 	    || ($cloneid)) {
1.445     albertel 16671: 	use LONCAPA::map;
1.444     albertel 16672: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16673: 
                   16674: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16675:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16676: 
1.444     albertel 16677:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16678:         my $title; my $url;
                   16679:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16680: 	    $title=&mt('Syllabus');
1.444     albertel 16681:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16682:         } else {
1.963     raeburn  16683:             $title=&mt('Table of Contents');
1.444     albertel 16684:             $url='/adm/navmaps';
                   16685:         }
1.445     albertel 16686: 
                   16687:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16688: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16689: 
                   16690: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16691:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16692:     }
1.566     albertel 16693: 
1.1237    raeburn  16694: # 
                   16695: # Set params for Placement Tests
                   16696: #
1.1239    raeburn  16697:     if ($args->{'crstype'} eq 'Placement') {
                   16698:        my %storecontent; 
                   16699:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16700:        my %defaults = (
                   16701:                         buttonshide   => { value => 'yes',
                   16702:                                            type => 'string_yesno',},
                   16703:                         type          => { value => 'randomizetry',
                   16704:                                            type  => 'string_questiontype',},
                   16705:                         maxtries      => { value => 1,
                   16706:                                            type => 'int_pos',},
                   16707:                         problemstatus => { value => 'no',
                   16708:                                            type  => 'string_problemstatus',},
                   16709:                       );
                   16710:        foreach my $key (keys(%defaults)) {
                   16711:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16712:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16713:        }
1.1237    raeburn  16714:        &Apache::lonnet::cput
                   16715:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16716:     }
                   16717: 
1.1344    raeburn  16718:     return (1,$outcome,\@clonemsg);
1.444     albertel 16719: }
                   16720: 
1.1166    raeburn  16721: sub make_unique_code {
                   16722:     my ($cdom,$cnum) = @_;
                   16723:     # get lock on uniquecodes db
                   16724:     my $lockhash = {
                   16725:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16726:                                                   ':'.$env{'user.domain'},
                   16727:                    };
                   16728:     my $tries = 0;
                   16729:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16730:     my ($code,$error);
                   16731:   
                   16732:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16733:         $tries ++;
                   16734:         sleep 1;
                   16735:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16736:     }
                   16737:     if ($gotlock eq 'ok') {
                   16738:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16739:         my $gotcode;
                   16740:         my $attempts = 0;
                   16741:         while ((!$gotcode) && ($attempts < 100)) {
                   16742:             $code = &generate_code();
                   16743:             if (!exists($currcodes{$code})) {
                   16744:                 $gotcode = 1;
                   16745:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16746:                     $error = 'nostore';
                   16747:                 }
                   16748:             }
                   16749:             $attempts ++;
                   16750:         }
                   16751:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16752:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16753:     } else {
                   16754:         $error = 'nolock';
                   16755:     }
                   16756:     return ($code,$error);
                   16757: }
                   16758: 
                   16759: sub generate_code {
                   16760:     my $code;
                   16761:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16762:     for (my $i=0; $i<6; $i++) {
                   16763:         my $lettnum = int (rand 2);
                   16764:         my $item = '';
                   16765:         if ($lettnum) {
                   16766:             $item = $letts[int( rand(18) )];
                   16767:         } else {
                   16768:             $item = 1+int( rand(8) );
                   16769:         }
                   16770:         $code .= $item;
                   16771:     }
                   16772:     return $code;
                   16773: }
                   16774: 
1.444     albertel 16775: ############################################################
                   16776: ############################################################
                   16777: 
1.1237    raeburn  16778: # Community, Course and Placement Test
1.378     raeburn  16779: sub course_type {
                   16780:     my ($cid) = @_;
                   16781:     if (!defined($cid)) {
                   16782:         $cid = $env{'request.course.id'};
                   16783:     }
1.404     albertel 16784:     if (defined($env{'course.'.$cid.'.type'})) {
                   16785:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16786:     } else {
                   16787:         return 'Course';
1.377     raeburn  16788:     }
                   16789: }
1.156     albertel 16790: 
1.406     raeburn  16791: sub group_term {
                   16792:     my $crstype = &course_type();
                   16793:     my %names = (
                   16794:                   'Course' => 'group',
1.865     raeburn  16795:                   'Community' => 'group',
1.1237    raeburn  16796:                   'Placement' => 'group',
1.406     raeburn  16797:                 );
                   16798:     return $names{$crstype};
                   16799: }
                   16800: 
1.902     raeburn  16801: sub course_types {
1.1310    raeburn  16802:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16803:     my %typename = (
                   16804:                          official   => 'Official course',
                   16805:                          unofficial => 'Unofficial course',
                   16806:                          community  => 'Community',
1.1165    raeburn  16807:                          textbook   => 'Textbook course',
1.1237    raeburn  16808:                          placement  => 'Placement test',
1.1310    raeburn  16809:                          lti        => 'LTI provider',
1.902     raeburn  16810:                    );
                   16811:     return (\@types,\%typename);
                   16812: }
                   16813: 
1.156     albertel 16814: sub icon {
                   16815:     my ($file)=@_;
1.505     albertel 16816:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16817:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16818:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16819:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16820: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16821: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16822: 	            $curfext.".gif") {
                   16823: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16824: 		$curfext.".gif";
                   16825: 	}
                   16826:     }
1.249     albertel 16827:     return &lonhttpdurl($iconname);
1.154     albertel 16828: } 
1.84      albertel 16829: 
1.575     albertel 16830: sub lonhttpdurl {
1.692     www      16831: #
                   16832: # Had been used for "small fry" static images on separate port 8080.
                   16833: # Modify here if lightweight http functionality desired again.
                   16834: # Currently eliminated due to increasing firewall issues.
                   16835: #
1.575     albertel 16836:     my ($url)=@_;
1.692     www      16837:     return $url;
1.215     albertel 16838: }
                   16839: 
1.213     albertel 16840: sub connection_aborted {
                   16841:     my ($r)=@_;
                   16842:     $r->print(" ");$r->rflush();
                   16843:     my $c = $r->connection;
                   16844:     return $c->aborted();
                   16845: }
                   16846: 
1.221     foxr     16847: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16848: #    strings as 'strings'.
                   16849: sub escape_single {
1.221     foxr     16850:     my ($input) = @_;
1.223     albertel 16851:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16852:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16853:     return $input;
                   16854: }
1.223     albertel 16855: 
1.222     foxr     16856: #  Same as escape_single, but escape's "'s  This 
                   16857: #  can be used for  "strings"
                   16858: sub escape_double {
                   16859:     my ($input) = @_;
                   16860:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16861:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16862:     return $input;
                   16863: }
1.223     albertel 16864:  
1.222     foxr     16865: #   Escapes the last element of a full URL.
                   16866: sub escape_url {
                   16867:     my ($url)   = @_;
1.238     raeburn  16868:     my @urlslices = split(/\//, $url,-1);
1.369     www      16869:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16870:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16871: }
1.462     albertel 16872: 
1.820     raeburn  16873: sub compare_arrays {
                   16874:     my ($arrayref1,$arrayref2) = @_;
                   16875:     my (@difference,%count);
                   16876:     @difference = ();
                   16877:     %count = ();
                   16878:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16879:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16880:         foreach my $element (keys(%count)) {
                   16881:             if ($count{$element} == 1) {
                   16882:                 push(@difference,$element);
                   16883:             }
                   16884:         }
                   16885:     }
                   16886:     return @difference;
                   16887: }
                   16888: 
1.1322    raeburn  16889: sub lon_status_items {
                   16890:     my %defaults = (
                   16891:                      E         => 100,
                   16892:                      W         => 4,
                   16893:                      N         => 1,
1.1324    raeburn  16894:                      U         => 5,
1.1322    raeburn  16895:                      threshold => 200,
                   16896:                      sysmail   => 2500,
                   16897:                    );
                   16898:     my %names = (
                   16899:                    E => 'Errors',
                   16900:                    W => 'Warnings',
                   16901:                    N => 'Notices',
1.1324    raeburn  16902:                    U => 'Unsent',
1.1322    raeburn  16903:                 );
                   16904:     return (\%defaults,\%names);
                   16905: }
                   16906: 
1.817     bisitz   16907: # -------------------------------------------------------- Initialize user login
1.462     albertel 16908: sub init_user_environment {
1.463     albertel 16909:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16910:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16911: 
                   16912:     my $public=($username eq 'public' && $domain eq 'public');
                   16913: 
1.1062    raeburn  16914:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16915:     my $now=time;
                   16916: 
                   16917:     if ($public) {
                   16918: 	my $max_public=100;
                   16919: 	my $oldest;
                   16920: 	my $oldest_time=0;
                   16921: 	for(my $next=1;$next<=$max_public;$next++) {
                   16922: 	    if (-e $lonids."/publicuser_$next.id") {
                   16923: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16924: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16925: 		    $oldest_time=$mtime;
                   16926: 		    $oldest=$next;
                   16927: 		}
                   16928: 	    } else {
                   16929: 		$cookie="publicuser_$next";
                   16930: 		last;
                   16931: 	    }
                   16932: 	}
                   16933: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16934:     } else {
1.1275    raeburn  16935: 	# See if old ID present, if so, remove if this isn't a robot,
                   16936: 	# killing any existing non-robot sessions
1.463     albertel 16937: 	if (!$args->{'robot'}) {
                   16938: 	    opendir(DIR,$lonids);
                   16939: 	    while ($filename=readdir(DIR)) {
                   16940: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16941:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16942:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16943:                         my $linkedfile;
1.1320    raeburn  16944:                         if (exists($oldenv{'user.linkedenv'})) {
                   16945:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16946:                         }
1.1320    raeburn  16947:                         untie(%oldenv);
                   16948:                         if (unlink("$lonids/$filename")) {
                   16949:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16950:                                 if (-l "$lonids/$linkedfile.id") {
                   16951:                                     unlink("$lonids/$linkedfile.id");
                   16952:                                 }
1.1295    raeburn  16953:                             }
                   16954:                         }
                   16955:                     } else {
                   16956:                         unlink($lonids.'/'.$filename);
                   16957:                     }
1.463     albertel 16958: 		}
1.462     albertel 16959: 	    }
1.463     albertel 16960: 	    closedir(DIR);
1.1204    raeburn  16961: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16962:             my $namespace = 'nohist_courseeditor';
                   16963:             my $lockingkey = 'paste'."\0".'locked_num';
                   16964:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16965:                                                 $domain,$username);
                   16966:             if (exists($lockhash{$lockingkey})) {
                   16967:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16968:                 unless ($delresult eq 'ok') {
                   16969:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16970:                 }
                   16971:             }
1.462     albertel 16972: 	}
                   16973: # Give them a new cookie
1.463     albertel 16974: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16975: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16976: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16977:     
                   16978: # Initialize roles
                   16979: 
1.1062    raeburn  16980: 	($userroles,$firstaccenv,$timerintenv) = 
                   16981:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16982:     }
                   16983: # ------------------------------------ Check browser type and MathML capability
                   16984: 
1.1194    raeburn  16985:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16986:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16987: 
                   16988: # ------------------------------------------------------------- Get environment
                   16989: 
                   16990:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16991:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16992:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16993: 	undef(%userenv);
                   16994:     }
                   16995:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16996: 	$form->{'interface'}=$userenv{'interface'};
                   16997:     }
                   16998:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16999: 
                   17000: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17001:     foreach my $option ('interface','localpath','localres') {
                   17002:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17003:     }
                   17004: # --------------------------------------------------------- Write first profile
                   17005: 
                   17006:     {
1.1350    raeburn  17007:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17008: 	my %initial_env = 
                   17009: 	    ("user.name"          => $username,
                   17010: 	     "user.domain"        => $domain,
                   17011: 	     "user.home"          => $authhost,
                   17012: 	     "browser.type"       => $clientbrowser,
                   17013: 	     "browser.version"    => $clientversion,
                   17014: 	     "browser.mathml"     => $clientmathml,
                   17015: 	     "browser.unicode"    => $clientunicode,
                   17016: 	     "browser.os"         => $clientos,
1.1137    raeburn  17017:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17018:              "browser.info"       => $clientinfo,
1.1194    raeburn  17019:              "browser.osversion"  => $clientosversion,
1.462     albertel 17020: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17021: 	     "request.course.fn"  => '',
                   17022: 	     "request.course.uri" => '',
                   17023: 	     "request.course.sec" => '',
                   17024: 	     "request.role"       => 'cm',
                   17025: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17026: 	     "request.host"       => $ip,);
1.462     albertel 17027: 
                   17028:         if ($form->{'localpath'}) {
                   17029: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17030: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17031:         }
                   17032: 	
                   17033: 	if ($form->{'interface'}) {
                   17034: 	    $form->{'interface'}=~s/\W//gs;
                   17035: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17036: 	    $env{'browser.interface'}=$form->{'interface'};
                   17037: 	}
                   17038: 
1.1157    raeburn  17039:         if ($form->{'iptoken'}) {
                   17040:             my $lonhost = $r->dir_config('lonHostID');
                   17041:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17042:             $env{'user.noloadbalance'} = $lonhost;
                   17043:         }
                   17044: 
1.1268    raeburn  17045:         if ($form->{'noloadbalance'}) {
                   17046:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17047:             my $hosthere = $form->{'noloadbalance'};
                   17048:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17049:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17050:                 $env{'user.noloadbalance'} = $hosthere;
                   17051:             }
                   17052:         }
                   17053: 
1.1016    raeburn  17054:         unless ($domain eq 'public') {
1.1273    raeburn  17055:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17056:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17057: 
                   17058:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17059:                 $userenv{'availabletools.'.$tool} = 
                   17060:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17061:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17062:             }
1.980     raeburn  17063: 
1.1311    raeburn  17064:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17065:                 $userenv{'canrequest.'.$crstype} =
                   17066:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17067:                                                       'reload','requestcourses',
                   17068:                                                       \%userenv,\%domdef,\%is_adv);
                   17069:             }
1.724     raeburn  17070: 
1.1273    raeburn  17071:             $userenv{'canrequest.author'} =
                   17072:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17073:                                                   'reload','requestauthor',
1.980     raeburn  17074:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17075:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17076:                                                  $domain,$username);
                   17077:             my $reqstatus = $reqauthor{'author_status'};
                   17078:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17079:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17080:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17081:                                                       $reqauthor{'author'}{'timestamp'};
                   17082:                 }
1.1092    raeburn  17083:             }
1.1287    raeburn  17084:             my ($types,$typename) = &course_types();
                   17085:             if (ref($types) eq 'ARRAY') {
                   17086:                 my @options = ('approval','validate','autolimit');
                   17087:                 my $optregex = join('|',@options);
                   17088:                 my (%willtrust,%trustchecked);
                   17089:                 foreach my $type (@{$types}) {
                   17090:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17091:                     if ($dom_str ne '') {
                   17092:                         my $updatedstr = '';
                   17093:                         my @possdomains = split(',',$dom_str);
                   17094:                         foreach my $entry (@possdomains) {
                   17095:                             my ($extdom,$extopt) = split(':',$entry);
                   17096:                             unless ($trustchecked{$extdom}) {
                   17097:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17098:                                 $trustchecked{$extdom} = 1;
                   17099:                             }
                   17100:                             if ($willtrust{$extdom}) {
                   17101:                                 $updatedstr .= $entry.',';
                   17102:                             }
                   17103:                         }
                   17104:                         $updatedstr =~ s/,$//;
                   17105:                         if ($updatedstr) {
                   17106:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17107:                         } else {
                   17108:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17109:                         }
                   17110:                     }
                   17111:                 }
                   17112:             }
1.1092    raeburn  17113:         }
1.462     albertel 17114: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17115: 
1.462     albertel 17116: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17117: 		 &GDBM_WRCREAT(),0640)) {
                   17118: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17119: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17120: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17121:             if (ref($firstaccenv) eq 'HASH') {
                   17122:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17123:             }
                   17124:             if (ref($timerintenv) eq 'HASH') {
                   17125:                 &_add_to_env(\%disk_env,$timerintenv);
                   17126:             }
1.463     albertel 17127: 	    if (ref($args->{'extra_env'})) {
                   17128: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17129: 	    }
1.462     albertel 17130: 	    untie(%disk_env);
                   17131: 	} else {
1.705     tempelho 17132: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17133: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17134: 	    return 'error: '.$!;
                   17135: 	}
                   17136:     }
                   17137:     $env{'request.role'}='cm';
                   17138:     $env{'request.role.adv'}=$env{'user.adv'};
                   17139:     $env{'browser.type'}=$clientbrowser;
                   17140: 
                   17141:     return $cookie;
                   17142: 
                   17143: }
                   17144: 
                   17145: sub _add_to_env {
                   17146:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17147:     if (ref($env_data) eq 'HASH') {
                   17148:         while (my ($key,$value) = each(%$env_data)) {
                   17149: 	    $idf->{$prefix.$key} = $value;
                   17150: 	    $env{$prefix.$key}   = $value;
                   17151:         }
1.462     albertel 17152:     }
                   17153: }
                   17154: 
1.685     tempelho 17155: # --- Get the symbolic name of a problem and the url
                   17156: sub get_symb {
                   17157:     my ($request,$silent) = @_;
1.726     raeburn  17158:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17160:     if ($symb eq '') {
                   17161:         if (!$silent) {
1.1071    raeburn  17162:             if (ref($request)) { 
                   17163:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17164:             }
1.685     tempelho 17165:             return ();
                   17166:         }
                   17167:     }
                   17168:     &Apache::lonenc::check_decrypt(\$symb);
                   17169:     return ($symb);
                   17170: }
                   17171: 
                   17172: # --------------------------------------------------------------Get annotation
                   17173: 
                   17174: sub get_annotation {
                   17175:     my ($symb,$enc) = @_;
                   17176: 
                   17177:     my $key = $symb;
                   17178:     if (!$enc) {
                   17179:         $key =
                   17180:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17181:     }
                   17182:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17183:     return $annotation{$key};
                   17184: }
                   17185: 
                   17186: sub clean_symb {
1.731     raeburn  17187:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17188: 
                   17189:     &Apache::lonenc::check_decrypt(\$symb);
                   17190:     my $enc = $env{'request.enc'};
1.731     raeburn  17191:     if ($delete_enc) {
1.730     raeburn  17192:         delete($env{'request.enc'});
                   17193:     }
1.685     tempelho 17194: 
                   17195:     return ($symb,$enc);
                   17196: }
1.462     albertel 17197: 
1.1181    raeburn  17198: ############################################################
                   17199: ############################################################
                   17200: 
                   17201: =pod
                   17202: 
                   17203: =head1 Routines for building display used to search for courses
                   17204: 
                   17205: 
                   17206: =over 4
                   17207: 
                   17208: =item * &build_filters()
                   17209: 
                   17210: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17211: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17212: and quotacheck.pl
                   17213: 
1.1181    raeburn  17214: 
                   17215: Inputs:
                   17216: 
                   17217: filterlist - anonymous array of fields to include as potential filters 
                   17218: 
                   17219: crstype - course type
                   17220: 
                   17221: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17222:               to pop-open a course selector (will contain "extra element"). 
                   17223: 
                   17224: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17225: 
                   17226: filter - anonymous hash of criteria and their values
                   17227: 
                   17228: action - form action
                   17229: 
                   17230: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17231: 
1.1182    raeburn  17232: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17233: 
                   17234: cloneruname - username of owner of new course who wants to clone
                   17235: 
                   17236: clonerudom - domain of owner of new course who wants to clone
                   17237: 
                   17238: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17239: 
                   17240: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17241: 
                   17242: codedom - domain
                   17243: 
                   17244: formname - value of form element named "form". 
                   17245: 
                   17246: fixeddom - domain, if fixed.
                   17247: 
                   17248: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17249: 
                   17250: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17251: 
                   17252: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17253: 
                   17254: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17255: 
                   17256: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17257: 
                   17258: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17259: 
                   17260: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17261: 
1.1182    raeburn  17262: 
1.1181    raeburn  17263: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17264: 
1.1182    raeburn  17265: 
1.1181    raeburn  17266: Side Effects: None
                   17267: 
                   17268: =cut
                   17269: 
                   17270: # ---------------------------------------------- search for courses based on last activity etc.
                   17271: 
                   17272: sub build_filters {
                   17273:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17274:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17275:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17276:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17277:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17278:     my ($list,$jscript);
1.1181    raeburn  17279:     my $onchange = 'javascript:updateFilters(this)';
                   17280:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17281:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17282:         $typeselectform,$instcodetitle);
                   17283:     if ($formname eq '') {
                   17284:         $formname = $caller;
                   17285:     }
                   17286:     foreach my $item (@{$filterlist}) {
                   17287:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17288:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17289:             if ($item eq 'domainfilter') {
                   17290:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17291:             } elsif ($item eq 'coursefilter') {
                   17292:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17293:             } elsif ($item eq 'ownerfilter') {
                   17294:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17295:             } elsif ($item eq 'ownerdomfilter') {
                   17296:                 $filter->{'ownerdomfilter'} =
                   17297:                     &LONCAPA::clean_domain($filter->{$item});
                   17298:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17299:                                                        'ownerdomfilter',1);
                   17300:             } elsif ($item eq 'personfilter') {
                   17301:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17302:             } elsif ($item eq 'persondomfilter') {
                   17303:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17304:                                                         'persondomfilter',1);
                   17305:             } else {
                   17306:                 $filter->{$item} =~ s/\W//g;
                   17307:             }
                   17308:             if (!$filter->{$item}) {
                   17309:                 $filter->{$item} = '';
                   17310:             }
                   17311:         }
                   17312:         if ($item eq 'domainfilter') {
                   17313:             my $allow_blank = 1;
                   17314:             if ($formname eq 'portform') {
                   17315:                 $allow_blank=0;
                   17316:             } elsif ($formname eq 'studentform') {
                   17317:                 $allow_blank=0;
                   17318:             }
                   17319:             if ($fixeddom) {
                   17320:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17321:                                     ' value="'.$codedom.'" />'.
                   17322:                                     &Apache::lonnet::domain($codedom,'description');
                   17323:             } else {
                   17324:                 $domainselectform = &select_dom_form($filter->{$item},
                   17325:                                                      'domainfilter',
                   17326:                                                       $allow_blank,'',$onchange);
                   17327:             }
                   17328:         } else {
                   17329:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17330:         }
                   17331:     }
                   17332: 
                   17333:     # last course activity filter and selection
                   17334:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17335: 
                   17336:     # course created filter and selection
                   17337:     if (exists($filter->{'createdfilter'})) {
                   17338:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17339:     }
                   17340: 
1.1239    raeburn  17341:     my $prefix = $crstype;
                   17342:     if ($crstype eq 'Placement') {
                   17343:         $prefix = 'Placement Test'
                   17344:     }
1.1181    raeburn  17345:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17346:                 'cac' => "$prefix Activity",
                   17347:                 'ccr' => "$prefix Created",
                   17348:                 'cde' => "$prefix Title",
                   17349:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17350:                 'ins' => 'Institutional Code',
                   17351:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17352:                 'cow' => "$prefix Owner/Co-owner",
                   17353:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17354:                 'cog' => 'Type',
                   17355:              );
                   17356: 
                   17357:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17358:         my $typeval = 'Course';
                   17359:         if ($crstype eq 'Community') {
                   17360:             $typeval = 'Community';
1.1239    raeburn  17361:         } elsif ($crstype eq 'Placement') {
                   17362:             $typeval = 'Placement';
1.1181    raeburn  17363:         }
                   17364:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17365:     } else {
                   17366:         $typeselectform =  '<select name="type" size="1"';
                   17367:         if ($onchange) {
                   17368:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17369:         }
                   17370:         $typeselectform .= '>'."\n";
1.1237    raeburn  17371:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17372:             my $shown;
                   17373:             if ($posstype eq 'Placement') {
                   17374:                 $shown = &mt('Placement Test');
                   17375:             } else {
                   17376:                 $shown = &mt($posstype);
                   17377:             }
1.1181    raeburn  17378:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17379:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17380:         }
                   17381:         $typeselectform.="</select>";
                   17382:     }
                   17383: 
                   17384:     my ($cloneableonlyform,$cloneabletitle);
                   17385:     if (exists($filter->{'cloneableonly'})) {
                   17386:         my $cloneableon = '';
                   17387:         my $cloneableoff = ' checked="checked"';
                   17388:         if ($filter->{'cloneableonly'}) {
                   17389:             $cloneableon = $cloneableoff;
                   17390:             $cloneableoff = '';
                   17391:         }
                   17392:         $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>';
                   17393:         if ($formname eq 'ccrs') {
1.1187    bisitz   17394:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17395:         } else {
                   17396:             $cloneabletitle = &mt('Cloneable by you');
                   17397:         }
                   17398:     }
                   17399:     my $officialjs;
                   17400:     if ($crstype eq 'Course') {
                   17401:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17402: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17403: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17404:             if ($codedom) { 
1.1181    raeburn  17405:                 $officialjs = 1;
                   17406:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17407:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17408:                                                                   $officialjs,$codetitlesref);
                   17409:                 if ($jscript) {
1.1182    raeburn  17410:                     $jscript = '<script type="text/javascript">'."\n".
                   17411:                                '// <![CDATA['."\n".
                   17412:                                $jscript."\n".
                   17413:                                '// ]]>'."\n".
                   17414:                                '</script>'."\n";
1.1181    raeburn  17415:                 }
                   17416:             }
                   17417:             if ($instcodeform eq '') {
                   17418:                 $instcodeform =
                   17419:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17420:                     $list->{'instcodefilter'}.'" />';
                   17421:                 $instcodetitle = $lt{'ins'};
                   17422:             } else {
                   17423:                 $instcodetitle = $lt{'inc'};
                   17424:             }
                   17425:             if ($fixeddom) {
                   17426:                 $instcodetitle .= '<br />('.$codedom.')';
                   17427:             }
                   17428:         }
                   17429:     }
                   17430:     my $output = qq|
                   17431: <form method="post" name="filterpicker" action="$action">
                   17432: <input type="hidden" name="form" value="$formname" />
                   17433: |;
                   17434:     if ($formname eq 'modifycourse') {
                   17435:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17436:                    '<input type="hidden" name="prevphase" value="'.
                   17437:                    $prevphase.'" />'."\n";
1.1198    musolffc 17438:     } elsif ($formname eq 'quotacheck') {
                   17439:         $output .= qq|
                   17440: <input type="hidden" name="sortby" value="" />
                   17441: <input type="hidden" name="sortorder" value="" />
                   17442: |;
                   17443:     } else {
1.1181    raeburn  17444:         my $name_input;
                   17445:         if ($cnameelement ne '') {
                   17446:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17447:                           $cnameelement.'" />';
                   17448:         }
                   17449:         $output .= qq|
1.1182    raeburn  17450: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17451: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17452: $name_input
                   17453: $roleelement
                   17454: $multelement
                   17455: $typeelement
                   17456: |;
                   17457:         if ($formname eq 'portform') {
                   17458:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17459:         }
                   17460:     }
                   17461:     if ($fixeddom) {
                   17462:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17463:     }
                   17464:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17465:     if ($sincefilterform) {
                   17466:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17467:                   .$sincefilterform
                   17468:                   .&Apache::lonhtmlcommon::row_closure();
                   17469:     }
                   17470:     if ($createdfilterform) {
                   17471:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17472:                   .$createdfilterform
                   17473:                   .&Apache::lonhtmlcommon::row_closure();
                   17474:     }
                   17475:     if ($domainselectform) {
                   17476:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17477:                   .$domainselectform
                   17478:                   .&Apache::lonhtmlcommon::row_closure();
                   17479:     }
                   17480:     if ($typeselectform) {
                   17481:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17482:             $output .= $typeselectform;
                   17483:         } else {
                   17484:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17485:                       .$typeselectform
                   17486:                       .&Apache::lonhtmlcommon::row_closure();
                   17487:         }
                   17488:     }
                   17489:     if ($instcodeform) {
                   17490:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17491:                   .$instcodeform
                   17492:                   .&Apache::lonhtmlcommon::row_closure();
                   17493:     }
                   17494:     if (exists($filter->{'ownerfilter'})) {
                   17495:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17496:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17497:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17498:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17499:                    $ownerdomselectform.'</td></tr></table>'.
                   17500:                    &Apache::lonhtmlcommon::row_closure();
                   17501:     }
                   17502:     if (exists($filter->{'personfilter'})) {
                   17503:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17504:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17505:                    '<input type="text" name="personfilter" size="20" value="'.
                   17506:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17507:                    $persondomselectform.'</td></tr></table>'.
                   17508:                    &Apache::lonhtmlcommon::row_closure();
                   17509:     }
                   17510:     if (exists($filter->{'coursefilter'})) {
                   17511:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17512:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17513:                   .$list->{'coursefilter'}.'" />'
                   17514:                   .&Apache::lonhtmlcommon::row_closure();
                   17515:     }
                   17516:     if ($cloneableonlyform) {
                   17517:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17518:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17519:     }
                   17520:     if (exists($filter->{'descriptfilter'})) {
                   17521:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17522:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17523:                   .$list->{'descriptfilter'}.'" />'
                   17524:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17525:     }
                   17526:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17527:                '<input type="hidden" name="updater" value="" />'."\n".
                   17528:                '<input type="submit" name="gosearch" value="'.
                   17529:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17530:     return $jscript.$clonewarning.$output;
                   17531: }
                   17532: 
                   17533: =pod 
                   17534: 
                   17535: =item * &timebased_select_form()
                   17536: 
1.1182    raeburn  17537: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17538: filter e.g., Course Activity, Course Created, when searching for courses
                   17539: or communities
                   17540: 
                   17541: Inputs:
                   17542: 
                   17543: item - name of form element (sincefilter or createdfilter)
                   17544: 
                   17545: filter - anonymous hash of criteria and their values
                   17546: 
                   17547: Returns: HTML for a select box contained a blank, then six time selections,
                   17548:          with value set in incoming form variables currently selected. 
                   17549: 
                   17550: Side Effects: None
                   17551: 
                   17552: =cut
                   17553: 
                   17554: sub timebased_select_form {
                   17555:     my ($item,$filter) = @_;
                   17556:     if (ref($filter) eq 'HASH') {
                   17557:         $filter->{$item} =~ s/[^\d-]//g;
                   17558:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17559:         return &select_form(
                   17560:                             $filter->{$item},
                   17561:                             $item,
                   17562:                             {      '-1' => '',
                   17563:                                 '86400' => &mt('today'),
                   17564:                                '604800' => &mt('last week'),
                   17565:                               '2592000' => &mt('last month'),
                   17566:                               '7776000' => &mt('last three months'),
                   17567:                              '15552000' => &mt('last six months'),
                   17568:                              '31104000' => &mt('last year'),
                   17569:                     'select_form_order' =>
                   17570:                            ['-1','86400','604800','2592000','7776000',
                   17571:                             '15552000','31104000']});
                   17572:     }
                   17573: }
                   17574: 
                   17575: =pod
                   17576: 
                   17577: =item * &js_changer()
                   17578: 
                   17579: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17580: when course type or domain is changed, and also to hide 'Searching ...' on
                   17581: page load completion for page showing search result.
1.1181    raeburn  17582: 
                   17583: Inputs: None
                   17584: 
1.1183    raeburn  17585: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17586: 
                   17587: Side Effects: None
                   17588: 
                   17589: =cut
                   17590: 
                   17591: sub js_changer {
                   17592:     return <<ENDJS;
                   17593: <script type="text/javascript">
                   17594: // <![CDATA[
                   17595: function updateFilters(caller) {
                   17596:     if (typeof(caller) != "undefined") {
                   17597:         document.filterpicker.updater.value = caller.name;
                   17598:     }
                   17599:     document.filterpicker.submit();
                   17600: }
1.1183    raeburn  17601: 
                   17602: function hideSearching() {
                   17603:     if (document.getElementById('searching')) {
                   17604:         document.getElementById('searching').style.display = 'none';
                   17605:     }
                   17606:     return;
                   17607: }
                   17608: 
1.1181    raeburn  17609: // ]]>
                   17610: </script>
                   17611: 
                   17612: ENDJS
                   17613: }
                   17614: 
                   17615: =pod
                   17616: 
1.1182    raeburn  17617: =item * &search_courses()
                   17618: 
                   17619: Process selected filters form course search form and pass to lonnet::courseiddump
                   17620: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17621: 
                   17622: Inputs:
                   17623: 
                   17624: dom - domain being searched 
                   17625: 
                   17626: type - course type ('Course' or 'Community' or '.' if any).
                   17627: 
                   17628: filter - anonymous hash of criteria and their values
                   17629: 
                   17630: numtitles - for institutional codes - number of categories
                   17631: 
                   17632: cloneruname - optional username of new course owner
                   17633: 
                   17634: clonerudom - optional domain of new course owner
                   17635: 
1.1221    raeburn  17636: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17637:             (used when DC is using course creation form)
                   17638: 
                   17639: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17640: 
1.1221    raeburn  17641: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17642:            (and so can clone automatically)
                   17643: 
                   17644: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17645: 
                   17646: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17647:               courses to clone 
1.1182    raeburn  17648: 
                   17649: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17650: 
                   17651: 
                   17652: Side Effects: None
                   17653: 
                   17654: =cut
                   17655: 
                   17656: 
                   17657: sub search_courses {
1.1221    raeburn  17658:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17659:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17660:     my (%courses,%showcourses,$cloner);
                   17661:     if (($filter->{'ownerfilter'} ne '') ||
                   17662:         ($filter->{'ownerdomfilter'} ne '')) {
                   17663:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17664:                                        $filter->{'ownerdomfilter'};
                   17665:     }
                   17666:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17667:         if (!$filter->{$item}) {
                   17668:             $filter->{$item}='.';
                   17669:         }
                   17670:     }
                   17671:     my $now = time;
                   17672:     my $timefilter =
                   17673:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17674:     my ($createdbefore,$createdafter);
                   17675:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17676:         $createdbefore = $now;
                   17677:         $createdafter = $now-$filter->{'createdfilter'};
                   17678:     }
                   17679:     my ($instcodefilter,$regexpok);
                   17680:     if ($numtitles) {
                   17681:         if ($env{'form.official'} eq 'on') {
                   17682:             $instcodefilter =
                   17683:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17684:             $regexpok = 1;
                   17685:         } elsif ($env{'form.official'} eq 'off') {
                   17686:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17687:             unless ($instcodefilter eq '') {
                   17688:                 $regexpok = -1;
                   17689:             }
                   17690:         }
                   17691:     } else {
                   17692:         $instcodefilter = $filter->{'instcodefilter'};
                   17693:     }
                   17694:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17695:     if ($type eq '') { $type = '.'; }
                   17696: 
                   17697:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17698:         $cloner = $cloneruname.':'.$clonerudom;
                   17699:     }
                   17700:     %courses = &Apache::lonnet::courseiddump($dom,
                   17701:                                              $filter->{'descriptfilter'},
                   17702:                                              $timefilter,
                   17703:                                              $instcodefilter,
                   17704:                                              $filter->{'combownerfilter'},
                   17705:                                              $filter->{'coursefilter'},
                   17706:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17707:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17708:                                              $filter->{'cloneableonly'},
                   17709:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17710:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17711:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17712:         my $ccrole;
                   17713:         if ($type eq 'Community') {
                   17714:             $ccrole = 'co';
                   17715:         } else {
                   17716:             $ccrole = 'cc';
                   17717:         }
                   17718:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17719:                                                      $filter->{'persondomfilter'},
                   17720:                                                      'userroles',undef,
                   17721:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17722:                                                      $dom);
                   17723:         foreach my $role (keys(%rolehash)) {
                   17724:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17725:             my $cid = $cdom.'_'.$cnum;
                   17726:             if (exists($courses{$cid})) {
                   17727:                 if (ref($courses{$cid}) eq 'HASH') {
                   17728:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17729:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17730:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17731:                         }
                   17732:                     } else {
                   17733:                         $courses{$cid}{roles} = [$courserole];
                   17734:                     }
                   17735:                     $showcourses{$cid} = $courses{$cid};
                   17736:                 }
                   17737:             }
                   17738:         }
                   17739:         %courses = %showcourses;
                   17740:     }
                   17741:     return %courses;
                   17742: }
                   17743: 
                   17744: =pod
                   17745: 
1.1181    raeburn  17746: =back
                   17747: 
1.1207    raeburn  17748: =head1 Routines for version requirements for current course.
                   17749: 
                   17750: =over 4
                   17751: 
                   17752: =item * &check_release_required()
                   17753: 
                   17754: Compares required LON-CAPA version with version on server, and
                   17755: if required version is newer looks for a server with the required version.
                   17756: 
                   17757: Looks first at servers in user's owen domain; if none suitable, looks at
                   17758: servers in course's domain are permitted to host sessions for user's domain.
                   17759: 
                   17760: Inputs:
                   17761: 
                   17762: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17763: 
                   17764: $courseid - Course ID of current course
                   17765: 
                   17766: $rolecode - User's current role in course (for switchserver query string).
                   17767: 
                   17768: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17769: 
                   17770: 
                   17771: Returns:
                   17772: 
                   17773: $switchserver - query string tp append to /adm/switchserver call (if 
                   17774:                 current server's LON-CAPA version is too old. 
                   17775: 
                   17776: $warning - Message is displayed if no suitable server could be found.
                   17777: 
                   17778: =cut
                   17779: 
                   17780: sub check_release_required {
                   17781:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17782:     my ($switchserver,$warning);
                   17783:     if ($required ne '') {
                   17784:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17785:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17786:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17787:             my $otherserver;
                   17788:             if (($major eq '' && $minor eq '') ||
                   17789:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17790:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17791:                 my $switchlcrev =
                   17792:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17793:                                                            $userdomserver);
                   17794:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17795:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17796:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17797:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17798:                     if ($cdom ne $env{'user.domain'}) {
                   17799:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17800:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17801:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17802:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17803:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17804:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17805:                         my $canhost =
                   17806:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17807:                                                               $coursedomserver,
                   17808:                                                               $remoterev,
                   17809:                                                               $udomdefaults{'remotesessions'},
                   17810:                                                               $defdomdefaults{'hostedsessions'});
                   17811: 
                   17812:                         if ($canhost) {
                   17813:                             $otherserver = $coursedomserver;
                   17814:                         } else {
                   17815:                             $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.");
                   17816:                         }
                   17817:                     } else {
                   17818:                         $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).");
                   17819:                     }
                   17820:                 } else {
                   17821:                     $otherserver = $userdomserver;
                   17822:                 }
                   17823:             }
                   17824:             if ($otherserver ne '') {
                   17825:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17826:             }
                   17827:         }
                   17828:     }
                   17829:     return ($switchserver,$warning);
                   17830: }
                   17831: 
                   17832: =pod
                   17833: 
                   17834: =item * &check_release_result()
                   17835: 
                   17836: Inputs:
                   17837: 
                   17838: $switchwarning - Warning message if no suitable server found to host session.
                   17839: 
                   17840: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17841:                 and current role.
                   17842: 
                   17843: Returns: HTML to display with information about requirement to switch server.
                   17844:          Either displaying warning with link to Roles/Courses screen or
                   17845:          display link to switchserver.
                   17846: 
1.1181    raeburn  17847: =cut
                   17848: 
1.1207    raeburn  17849: sub check_release_result {
                   17850:     my ($switchwarning,$switchserver) = @_;
                   17851:     my $output = &start_page('Selected course unavailable on this server').
                   17852:                  '<p class="LC_warning">';
                   17853:     if ($switchwarning) {
                   17854:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17855:         if (&show_course()) {
                   17856:             $output .= &mt('Display courses');
                   17857:         } else {
                   17858:             $output .= &mt('Display roles');
                   17859:         }
                   17860:         $output .= '</a>';
                   17861:     } elsif ($switchserver) {
                   17862:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17863:                    '<br />'.
                   17864:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17865:                    &mt('Switch Server').
                   17866:                    '</a>';
                   17867:     }
                   17868:     $output .= '</p>'.&end_page();
                   17869:     return $output;
                   17870: }
                   17871: 
                   17872: =pod
                   17873: 
                   17874: =item * &needs_coursereinit()
                   17875: 
                   17876: Determine if course contents stored for user's session needs to be
                   17877: refreshed, because content has changed since "Big Hash" last tied.
                   17878: 
                   17879: Check for change is made if time last checked is more than 10 minutes ago
                   17880: (by default).
                   17881: 
                   17882: Inputs:
                   17883: 
                   17884: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17885: 
                   17886: $interval (optional) - Time which may elapse (in s) between last check for content
                   17887:                        change in current course. (default: 600 s).  
                   17888: 
                   17889: Returns: an array; first element is:
                   17890: 
                   17891: =over 4
                   17892: 
                   17893: 'switch' - if content updates mean user's session
                   17894:            needs to be switched to a server running a newer LON-CAPA version
                   17895:  
                   17896: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17897:            on current server hosting user's session                
                   17898: 
                   17899: ''       - if no action required.
                   17900: 
                   17901: =back
                   17902: 
                   17903: If first item element is 'switch':
                   17904: 
                   17905: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17906: 
                   17907: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17908:                               and current role. 
                   17909: 
                   17910: otherwise: no other elements returned.
                   17911: 
                   17912: =back
                   17913: 
                   17914: =cut
                   17915: 
                   17916: sub needs_coursereinit {
                   17917:     my ($loncaparev,$interval) = @_;
                   17918:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17919:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17920:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17921:     my $now = time;
                   17922:     if ($interval eq '') {
                   17923:         $interval = 600;
                   17924:     }
                   17925:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17926:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17927:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17928:         if ($blocked) {
                   17929:             return ();
                   17930:         }
1.1207    raeburn  17931:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17932:         if ($lastchange > $env{'request.course.tied'}) {
                   17933:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17934:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17935:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17936:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17937:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17938:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17939:                     my ($switchserver,$switchwarning) =
                   17940:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17941:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17942:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17943:                         return ('switch',$switchwarning,$switchserver);
                   17944:                     }
                   17945:                 }
                   17946:             }
                   17947:             return ('update');
                   17948:         }
                   17949:     }
                   17950:     return ();
                   17951: }
1.1181    raeburn  17952: 
1.1083    raeburn  17953: sub update_content_constraints {
1.1326    raeburn  17954:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17955:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17956:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17957:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17958:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17959:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17960:         if ($item eq 'resourcetag') {
                   17961:             if ($name eq 'responsetype') {
                   17962:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17963:             }
1.1307    raeburn  17964:         } elsif ($item eq 'course') {
                   17965:             if ($name eq 'courserestype') {
                   17966:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17967:             }
1.1083    raeburn  17968:         }
                   17969:     }
                   17970:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17971:     if (defined($navmap)) {
1.1307    raeburn  17972:         my (%allresponses,%allcrsrestypes);
                   17973:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17974:             if ($res->is_tool()) {
                   17975:                 if ($allcrsrestypes{'exttool'}) {
                   17976:                     $allcrsrestypes{'exttool'} ++;
                   17977:                 } else {
                   17978:                     $allcrsrestypes{'exttool'} = 1;
                   17979:                 }
                   17980:                 next;
                   17981:             }
1.1083    raeburn  17982:             my %responses = $res->responseTypes();
                   17983:             foreach my $key (keys(%responses)) {
                   17984:                 next unless(exists($checkresponsetypes{$key}));
                   17985:                 $allresponses{$key} += $responses{$key};
                   17986:             }
                   17987:         }
                   17988:         foreach my $key (keys(%allresponses)) {
                   17989:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17990:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17991:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17992:             }
                   17993:         }
1.1307    raeburn  17994:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17995:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17996:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17997:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17998:             }
                   17999:         }
1.1083    raeburn  18000:         undef($navmap);
                   18001:     }
1.1326    raeburn  18002:     my (@resources,@order,@resparms,@zombies);
                   18003:     if ($keeporder) {
                   18004:         use LONCAPA::map;
                   18005:         @resources = @LONCAPA::map::resources;
                   18006:         @order = @LONCAPA::map::order;
                   18007:         @resparms = @LONCAPA::map::resparms;
                   18008:         @zombies = @LONCAPA::map::zombies;
                   18009:     }
1.1308    raeburn  18010:     my $suppmap = 'supplemental.sequence';
                   18011:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18012:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18013:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18014:     if ($keeporder) {
                   18015:         @LONCAPA::map::resources = @resources;
                   18016:         @LONCAPA::map::order = @order;
                   18017:         @LONCAPA::map::resparms = @resparms;
                   18018:         @LONCAPA::map::zombies = @zombies;
                   18019:     }
1.1308    raeburn  18020:     if ($supptools) {
                   18021:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18022:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18023:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18024:         }
                   18025:     }
1.1083    raeburn  18026:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18027:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18028:     }
                   18029:     return;
                   18030: }
                   18031: 
1.1110    raeburn  18032: sub allmaps_incourse {
                   18033:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18034:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18035:         $cid = $env{'request.course.id'};
                   18036:         $cdom = $env{'course.'.$cid.'.domain'};
                   18037:         $cnum = $env{'course.'.$cid.'.num'};
                   18038:         $chome = $env{'course.'.$cid.'.home'};
                   18039:     }
                   18040:     my %allmaps = ();
                   18041:     my $lastchange =
                   18042:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18043:     if ($lastchange > $env{'request.course.tied'}) {
                   18044:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18045:         unless ($ferr) {
1.1326    raeburn  18046:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18047:         }
                   18048:     }
                   18049:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18050:     if (defined($navmap)) {
                   18051:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18052:             $allmaps{$res->src()} = 1;
                   18053:         }
                   18054:     }
                   18055:     return \%allmaps;
                   18056: }
                   18057: 
1.1083    raeburn  18058: sub parse_supplemental_title {
                   18059:     my ($title) = @_;
                   18060: 
                   18061:     my ($foldertitle,$renametitle);
                   18062:     if ($title =~ /&amp;&amp;&amp;/) {
                   18063:         $title = &HTML::Entites::decode($title);
                   18064:     }
                   18065:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18066:         $renametitle=$4;
                   18067:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18068:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18069:         my $name =  &plainname($uname,$udom);
                   18070:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18071:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18072:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18073:             $name.': <br />'.$foldertitle;
                   18074:     }
                   18075:     if (wantarray) {
                   18076:         return ($title,$foldertitle,$renametitle);
                   18077:     }
                   18078:     return $title;
                   18079: }
                   18080: 
1.1143    raeburn  18081: sub recurse_supplemental {
1.1308    raeburn  18082:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18083:     if ($suppmap) {
                   18084:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18085:         if ($fatal) {
                   18086:             $errors ++;
                   18087:         } else {
                   18088:             if ($#LONCAPA::map::resources > 0) {
                   18089:                 foreach my $res (@LONCAPA::map::resources) {
                   18090:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18091:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18092:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18093:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18094:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18095:                         } else {
1.1308    raeburn  18096:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18097:                                 $numexttools ++;
                   18098:                             }
1.1143    raeburn  18099:                             $numfiles ++;
                   18100:                         }
                   18101:                     }
                   18102:                 }
                   18103:             }
                   18104:         }
                   18105:     }
1.1308    raeburn  18106:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18107: }
                   18108: 
1.1101    raeburn  18109: sub symb_to_docspath {
1.1267    raeburn  18110:     my ($symb,$navmapref) = @_;
                   18111:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18112:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18113:     if ($resurl=~/\.(sequence|page)$/) {
                   18114:         $mapurl=$resurl;
                   18115:     } elsif ($resurl eq 'adm/navmaps') {
                   18116:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18117:     }
                   18118:     my $mapresobj;
1.1267    raeburn  18119:     unless (ref($$navmapref)) {
                   18120:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18121:     }
                   18122:     if (ref($$navmapref)) {
                   18123:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18124:     }
                   18125:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18126:     my $type=$2;
                   18127:     my $path;
                   18128:     if (ref($mapresobj)) {
                   18129:         my $pcslist = $mapresobj->map_hierarchy();
                   18130:         if ($pcslist ne '') {
                   18131:             foreach my $pc (split(/,/,$pcslist)) {
                   18132:                 next if ($pc <= 1);
1.1267    raeburn  18133:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18134:                 if (ref($res)) {
                   18135:                     my $thisurl = $res->src();
                   18136:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18137:                     my $thistitle = $res->title();
                   18138:                     $path .= '&'.
                   18139:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18140:                              &escape($thistitle).
1.1101    raeburn  18141:                              ':'.$res->randompick().
                   18142:                              ':'.$res->randomout().
                   18143:                              ':'.$res->encrypted().
                   18144:                              ':'.$res->randomorder().
                   18145:                              ':'.$res->is_page();
                   18146:                 }
                   18147:             }
                   18148:         }
                   18149:         $path =~ s/^\&//;
                   18150:         my $maptitle = $mapresobj->title();
                   18151:         if ($mapurl eq 'default') {
1.1129    raeburn  18152:             $maptitle = 'Main Content';
1.1101    raeburn  18153:         }
                   18154:         $path .= (($path ne '')? '&' : '').
                   18155:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18156:                  &escape($maptitle).
1.1101    raeburn  18157:                  ':'.$mapresobj->randompick().
                   18158:                  ':'.$mapresobj->randomout().
                   18159:                  ':'.$mapresobj->encrypted().
                   18160:                  ':'.$mapresobj->randomorder().
                   18161:                  ':'.$mapresobj->is_page();
                   18162:     } else {
                   18163:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18164:         my $ispage = (($type eq 'page')? 1 : '');
                   18165:         if ($mapurl eq 'default') {
1.1129    raeburn  18166:             $maptitle = 'Main Content';
1.1101    raeburn  18167:         }
                   18168:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18169:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18170:     }
                   18171:     unless ($mapurl eq 'default') {
                   18172:         $path = 'default&'.
1.1146    raeburn  18173:                 &escape('Main Content').
1.1101    raeburn  18174:                 ':::::&'.$path;
                   18175:     }
                   18176:     return $path;
                   18177: }
                   18178: 
1.1094    raeburn  18179: sub captcha_display {
1.1327    raeburn  18180:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18181:     my ($output,$error);
1.1234    raeburn  18182:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18183:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18184:     if ($captcha eq 'original') {
1.1094    raeburn  18185:         $output = &create_captcha();
                   18186:         unless ($output) {
1.1172    raeburn  18187:             $error = 'captcha';
1.1094    raeburn  18188:         }
                   18189:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18190:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18191:         unless ($output) {
1.1172    raeburn  18192:             $error = 'recaptcha';
1.1094    raeburn  18193:         }
                   18194:     }
1.1234    raeburn  18195:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18196: }
                   18197: 
                   18198: sub captcha_response {
1.1327    raeburn  18199:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18200:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18201:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18202:     if ($captcha eq 'original') {
1.1094    raeburn  18203:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18204:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18205:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18206:     } else {
                   18207:         $captcha_chk = 1;
                   18208:     }
                   18209:     return ($captcha_chk,$captcha_error);
                   18210: }
                   18211: 
                   18212: sub get_captcha_config {
1.1327    raeburn  18213:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18214:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18215:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18216:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18217:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18218:     if ($context eq 'usercreation') {
                   18219:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18220:         if (ref($domconfig{$context}) eq 'HASH') {
                   18221:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18222:             if (ref($hashtocheck) eq 'HASH') {
                   18223:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18224:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18225:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18226:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18227:                     }
                   18228:                     if ($privkey && $pubkey) {
                   18229:                         $captcha = 'recaptcha';
1.1234    raeburn  18230:                         $version = $hashtocheck->{'recaptchaversion'};
                   18231:                         if ($version ne '2') {
                   18232:                             $version = 1;
                   18233:                         }
1.1095    raeburn  18234:                     } else {
                   18235:                         $captcha = 'original';
                   18236:                     }
                   18237:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18238:                     $captcha = 'original';
                   18239:                 }
1.1094    raeburn  18240:             }
1.1095    raeburn  18241:         } else {
                   18242:             $captcha = 'captcha';
                   18243:         }
                   18244:     } elsif ($context eq 'login') {
                   18245:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18246:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18247:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18248:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18249:             if ($privkey && $pubkey) {
                   18250:                 $captcha = 'recaptcha';
1.1234    raeburn  18251:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18252:                 if ($version ne '2') {
                   18253:                     $version = 1; 
                   18254:                 }
1.1095    raeburn  18255:             } else {
                   18256:                 $captcha = 'original';
1.1094    raeburn  18257:             }
1.1095    raeburn  18258:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18259:             $captcha = 'original';
1.1094    raeburn  18260:         }
1.1327    raeburn  18261:     } elsif ($context eq 'passwords') {
                   18262:         if ($dom_in_effect) {
                   18263:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18264:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18265:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18266:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18267:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18268:                 }
                   18269:                 if ($privkey && $pubkey) {
                   18270:                     $captcha = 'recaptcha';
                   18271:                     $version = $passwdconf{'recaptchaversion'};
                   18272:                     if ($version ne '2') {
                   18273:                         $version = 1;
                   18274:                     }
                   18275:                 } else {
                   18276:                     $captcha = 'original';
                   18277:                 }
                   18278:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18279:                 $captcha = 'original';
                   18280:             }
                   18281:         }
                   18282:     } 
1.1234    raeburn  18283:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18284: }
                   18285: 
                   18286: sub create_captcha {
                   18287:     my %captcha_params = &captcha_settings();
                   18288:     my ($output,$maxtries,$tries) = ('',10,0);
                   18289:     while ($tries < $maxtries) {
                   18290:         $tries ++;
                   18291:         my $captcha = Authen::Captcha->new (
                   18292:                                            output_folder => $captcha_params{'output_dir'},
                   18293:                                            data_folder   => $captcha_params{'db_dir'},
                   18294:                                           );
                   18295:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18296: 
                   18297:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18298:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   18299:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18300:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   18301:                       '<br />'.
                   18302:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18303:             last;
                   18304:         }
                   18305:     }
1.1323    raeburn  18306:     if ($output eq '') {
                   18307:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18308:     }
1.1094    raeburn  18309:     return $output;
                   18310: }
                   18311: 
                   18312: sub captcha_settings {
                   18313:     my %captcha_params = (
                   18314:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18315:                            www_output_dir => "/captchaspool",
                   18316:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18317:                            numchars       => '5',
                   18318:                          );
                   18319:     return %captcha_params;
                   18320: }
                   18321: 
                   18322: sub check_captcha {
                   18323:     my ($captcha_chk,$captcha_error);
                   18324:     my $code = $env{'form.code'};
                   18325:     my $md5sum = $env{'form.crypt'};
                   18326:     my %captcha_params = &captcha_settings();
                   18327:     my $captcha = Authen::Captcha->new(
                   18328:                       output_folder => $captcha_params{'output_dir'},
                   18329:                       data_folder   => $captcha_params{'db_dir'},
                   18330:                   );
1.1109    raeburn  18331:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18332:     my %captcha_hash = (
                   18333:                         0       => 'Code not checked (file error)',
                   18334:                        -1      => 'Failed: code expired',
                   18335:                        -2      => 'Failed: invalid code (not in database)',
                   18336:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18337:     );
                   18338:     if ($captcha_chk != 1) {
                   18339:         $captcha_error = $captcha_hash{$captcha_chk}
                   18340:     }
                   18341:     return ($captcha_chk,$captcha_error);
                   18342: }
                   18343: 
                   18344: sub create_recaptcha {
1.1234    raeburn  18345:     my ($pubkey,$version) = @_;
                   18346:     if ($version >= 2) {
                   18347:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   18348:     } else {
                   18349:         my $use_ssl;
                   18350:         if ($ENV{'SERVER_PORT'} == 443) {
                   18351:             $use_ssl = 1;
                   18352:         }
                   18353:         my $captcha = Captcha::reCAPTCHA->new;
                   18354:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18355:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18356:                &mt('If the text is hard to read, [_1] will replace them.',
                   18357:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18358:                '<br /><br />';
                   18359:     }
1.1094    raeburn  18360: }
                   18361: 
                   18362: sub check_recaptcha {
1.1234    raeburn  18363:     my ($privkey,$version) = @_;
1.1094    raeburn  18364:     my $captcha_chk;
1.1350    raeburn  18365:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18366:     if ($version >= 2) {
                   18367:         my %info = (
                   18368:                      secret   => $privkey, 
                   18369:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18370:                      remoteip => $ip,
1.1234    raeburn  18371:                    );
1.1280    raeburn  18372:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18373:         $request->content(join('&',map {
                   18374:                          my $name = escape($_);
                   18375:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18376:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18377:                          : &escape($info{$_}) );
                   18378:         } keys(%info)));
                   18379:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18380:         if ($response->is_success)  {
                   18381:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18382:             if (ref($data) eq 'HASH') {
                   18383:                 if ($data->{'success'}) {
                   18384:                     $captcha_chk = 1;
                   18385:                 }
                   18386:             }
                   18387:         }
                   18388:     } else {
                   18389:         my $captcha = Captcha::reCAPTCHA->new;
                   18390:         my $captcha_result =
                   18391:             $captcha->check_answer(
                   18392:                                     $privkey,
1.1350    raeburn  18393:                                     $ip,
1.1234    raeburn  18394:                                     $env{'form.recaptcha_challenge_field'},
                   18395:                                     $env{'form.recaptcha_response_field'},
                   18396:                                   );
                   18397:         if ($captcha_result->{is_valid}) {
                   18398:             $captcha_chk = 1;
                   18399:         }
1.1094    raeburn  18400:     }
                   18401:     return $captcha_chk;
                   18402: }
                   18403: 
1.1174    raeburn  18404: sub emailusername_info {
1.1244    raeburn  18405:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18406:     my %titles = &Apache::lonlocal::texthash (
                   18407:                      lastname      => 'Last Name',
                   18408:                      firstname     => 'First Name',
                   18409:                      institution   => 'School/college/university',
                   18410:                      location      => "School's city, state/province, country",
                   18411:                      web           => "School's web address",
                   18412:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18413:                      id            => 'Student/Employee ID',
1.1174    raeburn  18414:                  );
                   18415:     return (\@fields,\%titles);
                   18416: }
                   18417: 
1.1161    raeburn  18418: sub cleanup_html {
                   18419:     my ($incoming) = @_;
                   18420:     my $outgoing;
                   18421:     if ($incoming ne '') {
                   18422:         $outgoing = $incoming;
                   18423:         $outgoing =~ s/;/&#059;/g;
                   18424:         $outgoing =~ s/\#/&#035;/g;
                   18425:         $outgoing =~ s/\&/&#038;/g;
                   18426:         $outgoing =~ s/</&#060;/g;
                   18427:         $outgoing =~ s/>/&#062;/g;
                   18428:         $outgoing =~ s/\(/&#040/g;
                   18429:         $outgoing =~ s/\)/&#041;/g;
                   18430:         $outgoing =~ s/"/&#034;/g;
                   18431:         $outgoing =~ s/'/&#039;/g;
                   18432:         $outgoing =~ s/\$/&#036;/g;
                   18433:         $outgoing =~ s{/}{&#047;}g;
                   18434:         $outgoing =~ s/=/&#061;/g;
                   18435:         $outgoing =~ s/\\/&#092;/g
                   18436:     }
                   18437:     return $outgoing;
                   18438: }
                   18439: 
1.1190    musolffc 18440: # Checks for critical messages and returns a redirect url if one exists.
                   18441: # $interval indicates how often to check for messages.
1.1282    raeburn  18442: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18443: sub critical_redirect {
1.1282    raeburn  18444:     my ($interval,$context) = @_;
1.1356    raeburn  18445:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18446:         return ();
                   18447:     }
1.1190    musolffc 18448:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18449:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18450:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18451:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18452:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18453:             if ($blocked) {
                   18454:                 my $checkrole = "cm./$cdom/$cnum";
                   18455:                 if ($env{'request.course.sec'} ne '') {
                   18456:                     $checkrole .= "/$env{'request.course.sec'}";
                   18457:                 }
                   18458:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18459:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18460:                     return;
                   18461:                 }
                   18462:             }
                   18463:         }
1.1190    musolffc 18464:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18465:                                         $env{'user.name'});
                   18466:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18467:         my $redirecturl;
1.1190    musolffc 18468:         if ($what[0]) {
1.1356    raeburn  18469: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18470: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18471: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18472:                 return (1, $url);
1.1190    musolffc 18473:             }
1.1191    raeburn  18474:         }
                   18475:     } 
                   18476:     return ();
1.1190    musolffc 18477: }
                   18478: 
1.1174    raeburn  18479: # Use:
                   18480: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18481: #
                   18482: ##################################################
                   18483: #          password associated functions         #
                   18484: ##################################################
                   18485: sub des_keys {
                   18486:     # Make a new key for DES encryption.
                   18487:     # Each key has two parts which are returned separately.
                   18488:     # Please note:  Each key must be passed through the &hex function
                   18489:     # before it is output to the web browser.  The hex versions cannot
                   18490:     # be used to decrypt.
                   18491:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18492:                 '8','9','a','b','c','d','e','f');
                   18493:     my $lkey='';
                   18494:     for (0..7) {
                   18495:         $lkey.=$hexstr[rand(15)];
                   18496:     }
                   18497:     my $ukey='';
                   18498:     for (0..7) {
                   18499:         $ukey.=$hexstr[rand(15)];
                   18500:     }
                   18501:     return ($lkey,$ukey);
                   18502: }
                   18503: 
                   18504: sub des_decrypt {
                   18505:     my ($key,$cyphertext) = @_;
                   18506:     my $keybin=pack("H16",$key);
                   18507:     my $cypher;
                   18508:     if ($Crypt::DES::VERSION>=2.03) {
                   18509:         $cypher=new Crypt::DES $keybin;
                   18510:     } else {
                   18511:         $cypher=new DES $keybin;
                   18512:     }
1.1233    raeburn  18513:     my $plaintext='';
                   18514:     my $cypherlength = length($cyphertext);
                   18515:     my $numchunks = int($cypherlength/32);
                   18516:     for (my $j=0; $j<$numchunks; $j++) {
                   18517:         my $start = $j*32;
                   18518:         my $cypherblock = substr($cyphertext,$start,32);
                   18519:         my $chunk =
                   18520:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18521:         $chunk .=
                   18522:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18523:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18524:         $plaintext .= $chunk;
                   18525:     }
1.1174    raeburn  18526:     return $plaintext;
                   18527: }
                   18528: 
1.1344    raeburn  18529: sub get_requested_shorturls {
1.1309    raeburn  18530:     my ($cdom,$cnum,$navmap) = @_;
                   18531:     return unless (ref($navmap));
1.1344    raeburn  18532:     my ($numnew,$errors);
1.1309    raeburn  18533:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18534:     if (@toshorten) {
                   18535:         my (%maps,%resources,%titles);
                   18536:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18537:                                                                'shorturls',$cdom,$cnum);
                   18538:         if (keys(%resources)) {
1.1344    raeburn  18539:             my %tocreate;
1.1309    raeburn  18540:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18541:                 my $symb = $resources{$item};
                   18542:                 if ($symb) {
                   18543:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18544:                 }
                   18545:             }
1.1344    raeburn  18546:             if (keys(%tocreate)) {
                   18547:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18548:                                                       \%tocreate);
                   18549:             }
1.1309    raeburn  18550:         }
1.1344    raeburn  18551:     }
                   18552:     return ($numnew,$errors);
                   18553: }
                   18554: 
                   18555: sub make_short_symbs {
                   18556:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18557:     my ($numnew,@errors);
                   18558:     if (ref($tocreateref) eq 'HASH') {
                   18559:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18560:         if (keys(%tocreate)) {
                   18561:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18562:             my $su = Short::URL->new(no_vowels => 1);
                   18563:             my $init = '';
                   18564:             my (%newunique,%addcourse,%courseonly,%failed);
                   18565:             # get lock on tiny db
                   18566:             my $now = time;
1.1344    raeburn  18567:             if ($lockuser eq '') {
                   18568:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18569:             }
1.1309    raeburn  18570:             my $lockhash = {
1.1344    raeburn  18571:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18572:                             };
                   18573:             my $tries = 0;
                   18574:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18575:             my ($code,$error);
                   18576:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18577:                 $tries ++;
                   18578:                 sleep 1;
1.1319    raeburn  18579:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18580:             }
                   18581:             if ($gotlock eq 'ok') {
                   18582:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18583:                                        \%addcourse,\%courseonly,\%failed);
                   18584:                 if (keys(%failed)) {
                   18585:                     my $numfailed = scalar(keys(%failed));
                   18586:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18587:                 }
                   18588:                 if (keys(%newunique)) {
                   18589:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18590:                     if ($putres eq 'ok') {
                   18591:                         $numnew = scalar(keys(%newunique));
                   18592:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18593:                         unless ($newputres eq 'ok') {
                   18594:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18595:                         }
                   18596:                     } else {
                   18597:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18598:                     }
                   18599:                 }
                   18600:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18601:                 unless ($dellockres eq 'ok') {
                   18602:                     push(@errors,&mt('error: could not release lockfile'));
                   18603:                 }
                   18604:             } else {
                   18605:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18606:             }
                   18607:             if (keys(%courseonly)) {
                   18608:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18609:                 if ($result ne 'ok') {
                   18610:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18611:                 }
                   18612:             }
                   18613:         }
                   18614:     }
                   18615:     return ($numnew,\@errors);
                   18616: }
                   18617: 
                   18618: sub shorten_symbs {
                   18619:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18620:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18621:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18622:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18623:     my (%possibles,%collisions);
                   18624:     foreach my $key (keys(%{$tocreate})) {
                   18625:         my $num = String::CRC32::crc32($key);
                   18626:         my $tiny = $su->encode($num,$init);
                   18627:         if ($tiny) {
                   18628:             $possibles{$tiny} = $key;
                   18629:         }
                   18630:     }
                   18631:     if (!$init) {
                   18632:         $init = 1;
                   18633:     } else {
                   18634:         $init ++;
                   18635:     }
                   18636:     if (keys(%possibles)) {
                   18637:         my @posstiny = keys(%possibles);
                   18638:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18639:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18640:         if (keys(%currtiny)) {
                   18641:             foreach my $key (keys(%currtiny)) {
                   18642:                 next if ($currtiny{$key} eq '');
                   18643:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18644:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18645:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18646:                         $courseonly->{$tsymb} = $key;
                   18647:                     }
                   18648:                 } else {
                   18649:                     $collisions{$possibles{$key}} = 1;
                   18650:                 }
                   18651:                 delete($possibles{$key});
                   18652:             }
                   18653:         }
                   18654:         foreach my $key (keys(%possibles)) {
                   18655:             $newunique->{$key} = $possibles{$key};
                   18656:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18657:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18658:                 $addcourse->{$tsymb} = $key;
                   18659:             }
                   18660:         }
                   18661:     }
                   18662:     if (keys(%collisions)) {
                   18663:         if ($init <5) {
                   18664:             if (!$init) {
                   18665:                 $init = 1;
                   18666:             } else {
                   18667:                 $init ++;
                   18668:             }
                   18669:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18670:                                    $newunique,$addcourse,$courseonly,$failed);
                   18671:         } else {
                   18672:             foreach my $key (keys(%collisions)) {
                   18673:                 $failed->{$key} = 1;
                   18674:             }
                   18675:         }
                   18676:     }
                   18677:     return $init;
                   18678: }
                   18679: 
1.1328    raeburn  18680: sub is_nonframeable {
1.1329    raeburn  18681:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18682:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18683:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18684: 
                   18685:     $remprotocol = lc($remprotocol);
                   18686:     $remhost = lc($remhost);
                   18687:     my $remport = 80;
                   18688:     if ($remprotocol eq 'https') {
                   18689:         $remport = 443;
                   18690:     }
1.1330    raeburn  18691:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18692:     if ($cached) {
                   18693:         unless ($nocache) {
                   18694:             if ($result) {
                   18695:                 return 1;
                   18696:             } else {
                   18697:                 return 0;
                   18698:             }
                   18699:         }
                   18700:     }
1.1328    raeburn  18701:     my $uselink;
                   18702:     my $request = new HTTP::Request('HEAD',$url);
                   18703:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18704:     if ($response->is_success()) {
                   18705:         my $secpolicy = lc($response->header('content-security-policy'));
                   18706:         my $xframeop = lc($response->header('x-frame-options'));
                   18707:         $secpolicy =~ s/^\s+|\s+$//g;
                   18708:         $xframeop =~ s/^\s+|\s+$//g;
                   18709:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18710:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18711:             my ($origin,$protocol,$port);
                   18712:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18713:                 $port = $ENV{'SERVER_PORT'};
                   18714:             } else {
                   18715:                 $port = 80;
                   18716:             }
                   18717:             if ($absolute eq '') {
                   18718:                 $protocol = 'http:';
                   18719:                 if ($port == 443) {
                   18720:                     $protocol = 'https:';
                   18721:                 }
                   18722:                 $origin = $protocol.'//'.lc($hostname);
                   18723:             } else {
                   18724:                 $origin = lc($absolute);
                   18725:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18726:             }
                   18727:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18728:                 my $framepolicy = $1;
                   18729:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18730:                 my @policies = split(/\s+/,$framepolicy);
                   18731:                 if (@policies) {
                   18732:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18733:                         $uselink = 1;
                   18734:                     } else {
                   18735:                         $uselink = 1;
                   18736:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18737:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18738:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18739:                             undef($uselink);
                   18740:                         }
                   18741:                         if ($uselink) {
                   18742:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18743:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18744:                                     undef($uselink);
                   18745:                                 }
                   18746:                             }
                   18747:                         }
                   18748:                         if ($uselink) {
                   18749:                             my @possok;
                   18750:                             if ($ip ne '') {
                   18751:                                 push(@possok,$ip);
                   18752:                             }
                   18753:                             my $hoststr = '';
                   18754:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18755:                                 if ($hoststr eq '') {
                   18756:                                     $hoststr = $part;
                   18757:                                 } else {
                   18758:                                     $hoststr = "$part.$hoststr";
                   18759:                                 }
                   18760:                                 if ($hoststr eq $hostname) {
                   18761:                                     push(@possok,$hostname);
                   18762:                                 } else {
                   18763:                                     push(@possok,"*.$hoststr");
                   18764:                                 }
                   18765:                             }
                   18766:                             if (@possok) {
                   18767:                                 foreach my $poss (@possok) {
                   18768:                                     last if (!$uselink);
                   18769:                                     foreach my $policy (@policies) {
                   18770:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18771:                                             undef($uselink);
                   18772:                                             last;
                   18773:                                         }
                   18774:                                     }
                   18775:                                 }
                   18776:                             }
                   18777:                         }
                   18778:                     }
                   18779:                 }
                   18780:             } elsif ($xframeop ne '') {
                   18781:                 $uselink = 1;
                   18782:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18783:                 if (@policies) {
                   18784:                     unless (grep(/^deny$/,@policies)) {
                   18785:                         if ($origin ne '') {
                   18786:                             if (grep(/^sameorigin$/,@policies)) {
                   18787:                                 if ($remotehost eq $origin) {
                   18788:                                     undef($uselink);
                   18789:                                 }
                   18790:                             }
                   18791:                             if ($uselink) {
                   18792:                                 foreach my $policy (@policies) {
                   18793:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18794:                                         my $allowfrom = $1;
                   18795:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18796:                                             undef($uselink);
                   18797:                                             last;
                   18798:                                         }
                   18799:                                     }
                   18800:                                 }
                   18801:                             }
                   18802:                         }
                   18803:                     }
                   18804:                 }
                   18805:             }
                   18806:         }
                   18807:     }
1.1329    raeburn  18808:     if ($nocache) {
                   18809:         if ($cached) {
                   18810:             my $devalidate;
                   18811:             if ($uselink && !$result) {
                   18812:                 $devalidate = 1;
                   18813:             } elsif (!$uselink && $result) {
                   18814:                 $devalidate = 1;
                   18815:             }
                   18816:             if ($devalidate) {
                   18817:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18818:             }
                   18819:         }
                   18820:     } else {
                   18821:         if ($uselink) {
                   18822:             $result = 1;
                   18823:         } else {
                   18824:             $result = 0;
                   18825:         }
                   18826:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18827:     }
1.1328    raeburn  18828:     return $uselink;
                   18829: }
                   18830: 
1.1359    raeburn  18831: sub page_menu {
                   18832:     my ($menucolls,$menunum) = @_;
                   18833:     my %menu;
                   18834:     foreach my $item (split(/;/,$menucolls)) {
                   18835:         my ($num,$value) = split(/\%/,$item);
                   18836:         if ($num eq $menunum) {
                   18837:             my @entries = split(/\&/,$value);
                   18838:             foreach my $entry (@entries) {
                   18839:                 my ($name,$fields) = split(/=/,$entry);
                   18840:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'main')) {
                   18841:                     $menu{$name} = $fields;
                   18842:                 } else {
                   18843:                     my @shown;
                   18844:                     if ($fields =~ /,/) {
                   18845:                         @shown = split(/,/,$fields);
                   18846:                     } else {
                   18847:                         @shown = ($fields);
                   18848:                     }
                   18849:                     if (@shown) {
                   18850:                         foreach my $field (@shown) {
                   18851:                             next if ($field eq '');
                   18852:                             $menu{$field} = 1;
                   18853:                         }
                   18854:                     }
                   18855:                 }
                   18856:             }
                   18857:         }
                   18858:     }
                   18859:     return %menu;
                   18860: }
                   18861: 
1.112     bowersj2 18862: 1;
                   18863: __END__;
1.41      ng       18864: 

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