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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.161.  .18(raeb    4:-23): # $Id: loncommon.pm,v 1.1075.2.161.2.17 2023/07/09 17:36:51 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.1075.2.161.  .7(raebu   64:22): use Apache::lonnavmaps();
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.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.161.  .13(raeb   74:-23): use LONCAPA::map();
1.1075.2.135  raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1075.2.102  raeburn    77: use DateTime::Locale;
1.1075.2.94  raeburn    78: use Encode();
1.1075.2.14  raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1075.2.64  raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    85: use File::Copy();
                     86: use File::Path();
1.1075.2.161.  .1(raebu   87:21): use String::CRC32();
                     88:21): use Short::URL();
1.117     www        89: 
1.517     raeburn    90: # ---------------------------------------------- Designs
                     91: use vars qw(%defaultdesign);
                     92: 
1.22      www        93: my $readit;
                     94: 
1.517     raeburn    95: 
1.157     matthew    96: ##
                     97: ## Global Variables
                     98: ##
1.46      matthew    99: 
1.643     foxr      100: 
                    101: # ----------------------------------------------- SSI with retries:
                    102: #
                    103: 
                    104: =pod
                    105: 
1.648     raeburn   106: =head1 Server Side include with retries:
1.643     foxr      107: 
                    108: =over 4
                    109: 
1.648     raeburn   110: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      111: 
                    112: Performs an ssi with some number of retries.  Retries continue either
                    113: until the result is ok or until the retry count supplied by the
                    114: caller is exhausted.  
                    115: 
                    116: Inputs:
1.648     raeburn   117: 
                    118: =over 4
                    119: 
1.643     foxr      120: resource   - Identifies the resource to insert.
1.648     raeburn   121: 
1.643     foxr      122: retries    - Count of the number of retries allowed.
1.648     raeburn   123: 
1.643     foxr      124: form       - Hash that identifies the rendering options.
                    125: 
1.648     raeburn   126: =back
                    127: 
                    128: Returns:
                    129: 
                    130: =over 4
                    131: 
1.643     foxr      132: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   133: 
1.643     foxr      134: response   - The response from the last attempt (which may or may not have been successful.
                    135: 
1.648     raeburn   136: =back
                    137: 
                    138: =back
                    139: 
1.643     foxr      140: =cut
                    141: 
                    142: sub ssi_with_retries {
                    143:     my ($resource, $retries, %form) = @_;
                    144: 
                    145: 
                    146:     my $ok = 0;			# True if we got a good response.
                    147:     my $content;
                    148:     my $response;
                    149: 
                    150:     # Try to get the ssi done. within the retries count:
                    151: 
                    152:     do {
                    153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    154: 	$ok      = $response->is_success;
1.650     www       155:         if (!$ok) {
                    156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    157:         }
1.643     foxr      158: 	$retries--;
                    159:     } while (!$ok && ($retries > 0));
                    160: 
                    161:     if (!$ok) {
                    162: 	$content = '';		# On error return an empty content.
                    163:     }
                    164:     return ($content, $response);
                    165: 
                    166: }
                    167: 
                    168: 
                    169: 
1.20      www       170: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  171: my %language;
1.124     www       172: my %supported_language;
1.1048    foxr      173: my %latex_language;		# For choosing hyphenation in <transl..>
                    174: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  175: my %cprtag;
1.192     taceyjo1  176: my %scprtag;
1.351     www       177: my %fe; my %fd; my %fm;
1.41      ng        178: my %category_extensions;
1.12      harris41  179: 
1.46      matthew   180: # ---------------------------------------------- Thesaurus variables
1.144     matthew   181: #
                    182: # %Keywords:
                    183: #      A hash used by &keyword to determine if a word is considered a keyword.
                    184: # $thesaurus_db_file 
                    185: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   186: 
                    187: my %Keywords;
                    188: my $thesaurus_db_file;
                    189: 
1.144     matthew   190: #
                    191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    192: # thesaurus.tab, and filecategories.tab.
                    193: #
1.18      www       194: BEGIN {
1.46      matthew   195:     # Variable initialization
                    196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    197:     #
1.22      www       198:     unless ($readit) {
1.12      harris41  199: # ------------------------------------------------------------------- languages
                    200:     {
1.158     raeburn   201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    202:                                    '/language.tab';
1.1075.2.128  raeburn   203:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  204:             while (my $line = <$fh>) {
                    205:                 next if ($line=~/^\#/);
                    206:                 chomp($line);
1.1048    foxr      207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   208:                 $language{$key}=$val.' - '.$enc;
                    209:                 if ($sup) {
                    210:                     $supported_language{$key}=$sup;
                    211:                 }
1.1048    foxr      212: 		if ($latex) {
                    213: 		    $latex_language_bykey{$key} = $latex;
                    214: 		    $latex_language{$two} = $latex;
                    215: 		}
1.158     raeburn   216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
                    220: # ------------------------------------------------------------------ copyrights
                    221:     {
1.158     raeburn   222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/copyright.tab';
1.1075.2.128  raeburn   224:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line=~/^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   229:                 $cprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
1.12      harris41  233:     }
1.351     www       234: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  235:     {
                    236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    237:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  239:             while (my $line = <$fh>) {
                    240:                 next if ($line =~ /^\#/);
                    241:                 chomp($line);
                    242:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  243:                 $scprtag{$key}=$val;
                    244:             }
                    245:             close($fh);
                    246:         }
                    247:     }
1.63      www       248: 
1.517     raeburn   249: # -------------------------------------------------------------- default domain designs
1.63      www       250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   251:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   252:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   253:         while (my $line = <$fh>) {
                    254:             next if ($line =~ /^\#/);
                    255:             chomp($line);
                    256:             my ($key,$val)=(split(/\=/,$line));
                    257:             if ($val) { $defaultdesign{$key}=$val; }
                    258:         }
                    259:         close($fh);
1.63      www       260:     }
                    261: 
1.15      harris41  262: # ------------------------------------------------------------- file categories
                    263:     {
1.158     raeburn   264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    265:                                   '/filecategories.tab';
1.1075.2.128  raeburn   266:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  267: 	    while (my $line = <$fh>) {
                    268: 		next if ($line =~ /^\#/);
                    269: 		chomp($line);
                    270:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   271:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   272:             }
                    273:             close($fh);
                    274:         }
                    275: 
1.15      harris41  276:     }
1.12      harris41  277: # ------------------------------------------------------------------ file types
                    278:     {
1.158     raeburn   279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    280:                '/filetypes.tab';
1.1075.2.128  raeburn   281:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  282:             while (my $line = <$fh>) {
                    283: 		next if ($line =~ /^\#/);
                    284: 		chomp($line);
                    285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   286:                 if ($descr ne '') {
                    287:                     $fe{$ending}=lc($emb);
                    288:                     $fd{$ending}=$descr;
1.351     www       289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   290:                 }
                    291:             }
                    292:             close($fh);
                    293:         }
1.12      harris41  294:     }
1.22      www       295:     &Apache::lonnet::logthis(
1.705     tempelho  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       297:     $readit=1;
1.46      matthew   298:     }  # end of unless($readit) 
1.32      matthew   299:     
                    300: }
1.112     bowersj2  301: 
1.42      matthew   302: ###############################################################
                    303: ##           HTML and Javascript Helper Functions            ##
                    304: ###############################################################
                    305: 
                    306: =pod 
                    307: 
1.112     bowersj2  308: =head1 HTML and Javascript Functions
1.42      matthew   309: 
1.112     bowersj2  310: =over 4
                    311: 
1.648     raeburn   312: =item * &browser_and_searcher_javascript()
1.112     bowersj2  313: 
                    314: X<browsing, javascript>X<searching, javascript>Returns a string
                    315: containing javascript with two functions, C<openbrowser> and
                    316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    317: tags.
1.42      matthew   318: 
1.648     raeburn   319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   320: 
                    321: inputs: formname, elementname, only, omit
                    322: 
                    323: formname and elementname indicate the name of the html form and name of
                    324: the element that the results of the browsing selection are to be placed in. 
                    325: 
                    326: Specifying 'only' will restrict the browser to displaying only files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
                    329: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       330: with the given extension.  Can be a comma separated list.
1.42      matthew   331: 
1.648     raeburn   332: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   333: 
                    334: Inputs: formname, elementname
                    335: 
                    336: formname and elementname specify the name of the html form and the name
                    337: of the element the selection from the search results will be placed in.
1.542     raeburn   338: 
1.42      matthew   339: =cut
                    340: 
                    341: sub browser_and_searcher_javascript {
1.199     albertel  342:     my ($mode)=@_;
                    343:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  344:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   345:     return <<END;
1.219     albertel  346: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   347:     var editbrowser = null;
1.135     albertel  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       349:         var url = '$resurl/?';
1.42      matthew   350:         if (editbrowser == null) {
                    351:             url += 'launch=1&';
                    352:         }
                    353:         url += 'catalogmode=interactive&';
1.199     albertel  354:         url += 'mode=$mode&';
1.611     albertel  355:         url += 'inhibitmenu=yes&';
1.42      matthew   356:         url += 'form=' + formname + '&';
                    357:         if (only != null) {
                    358:             url += 'only=' + only + '&';
1.217     albertel  359:         } else {
                    360:             url += 'only=&';
                    361: 	}
1.42      matthew   362:         if (omit != null) {
                    363:             url += 'omit=' + omit + '&';
1.217     albertel  364:         } else {
                    365:             url += 'omit=&';
                    366: 	}
1.135     albertel  367:         if (titleelement != null) {
                    368:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  369:         } else {
                    370: 	    url += 'titleelement=&';
                    371: 	}
1.42      matthew   372:         url += 'element=' + elementname + '';
                    373:         var title = 'Browser';
1.435     albertel  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   375:         options += ',width=700,height=600';
                    376:         editbrowser = open(url,title,options,'1');
                    377:         editbrowser.focus();
                    378:     }
                    379:     var editsearcher;
1.135     albertel  380:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   381:         var url = '/adm/searchcat?';
                    382:         if (editsearcher == null) {
                    383:             url += 'launch=1&';
                    384:         }
                    385:         url += 'catalogmode=interactive&';
1.199     albertel  386:         url += 'mode=$mode&';
1.42      matthew   387:         url += 'form=' + formname + '&';
1.135     albertel  388:         if (titleelement != null) {
                    389:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  390:         } else {
                    391: 	    url += 'titleelement=&';
                    392: 	}
1.42      matthew   393:         url += 'element=' + elementname + '';
                    394:         var title = 'Search';
1.435     albertel  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   396:         options += ',width=700,height=600';
                    397:         editsearcher = open(url,title,options,'1');
                    398:         editsearcher.focus();
                    399:     }
1.219     albertel  400: // END LON-CAPA Internal -->
1.42      matthew   401: END
1.170     www       402: }
                    403: 
                    404: sub lastresurl {
1.258     albertel  405:     if ($env{'environment.lastresurl'}) {
                    406: 	return $env{'environment.lastresurl'}
1.170     www       407:     } else {
                    408: 	return '/res';
                    409:     }
                    410: }
                    411: 
                    412: sub storeresurl {
                    413:     my $resurl=&Apache::lonnet::clutter(shift);
                    414:     unless ($resurl=~/^\/res/) { return 0; }
                    415:     $resurl=~s/\/$//;
                    416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       418:     return 1;
1.42      matthew   419: }
                    420: 
1.74      www       421: sub studentbrowser_javascript {
1.111     www       422:    unless (
1.258     albertel  423:             (($env{'request.course.id'}) && 
1.302     albertel  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    426: 					  '/'.$env{'request.course.sec'})
                    427: 	      ))
1.258     albertel  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       429:           ) { return ''; }  
1.74      www       430:    return (<<'ENDSTDBRW');
1.776     bisitz    431: <script type="text/javascript" language="Javascript">
1.824     bisitz    432: // <![CDATA[
1.74      www       433:     var stdeditbrowser;
1.1075.2.143  raeburn   434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       435:         var url = '/adm/pickstudent?';
                    436:         var filter;
1.558     albertel  437: 	if (!ignorefilter) {
                    438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    439: 	}
1.74      www       440:         if (filter != null) {
                    441:            if (filter != '') {
                    442:                url += 'filter='+filter+'&';
                    443: 	   }
                    444:         }
                    445:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       446:                                     '&udomelement='+udom+
                    447:                                     '&clicker='+clicker;
1.111     www       448: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   449:         if (courseadv == 'condition') {
                    450:             if (document.getElementById('courseadv')) {
                    451:                 courseadv = document.getElementById('courseadv').value;
                    452:             }
                    453:         }
                    454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       455:         var title = 'Student_Browser';
1.74      www       456:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    457:         options += ',width=700,height=600';
                    458:         stdeditbrowser = open(url,title,options,'1');
                    459:         stdeditbrowser.focus();
                    460:     }
1.824     bisitz    461: // ]]>
1.74      www       462: </script>
                    463: ENDSTDBRW
                    464: }
1.42      matthew   465: 
1.1003    www       466: sub resourcebrowser_javascript {
                    467:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       468:    return (<<'ENDRESBRW');
1.1003    www       469: <script type="text/javascript" language="Javascript">
                    470: // <![CDATA[
                    471:     var reseditbrowser;
1.1004    www       472:     function openresbrowser(formname,reslink) {
1.1005    www       473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       474:         var title = 'Resource_Browser';
                    475:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       476:         options += ',width=700,height=500';
1.1004    www       477:         reseditbrowser = open(url,title,options,'1');
                    478:         reseditbrowser.focus();
1.1003    www       479:     }
                    480: // ]]>
                    481: </script>
1.1004    www       482: ENDRESBRW
1.1003    www       483: }
                    484: 
1.74      www       485: sub selectstudent_link {
1.1075.2.143  raeburn   486:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  490:    if ($env{'request.course.id'}) {  
1.302     albertel  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    493: 					'/'.$env{'request.course.sec'})) {
1.111     www       494: 	   return '';
                    495:        }
1.999     www       496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   497:        if ($courseadv eq 'only') {
                    498:            $callargs .= ",'',1,'$courseadv'";
                    499:        } elsif ($courseadv eq 'none') {
                    500:            $callargs .= ",'','','$courseadv'";
                    501:        } elsif ($courseadv eq 'condition') {
                    502:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   503:        }
                    504:        return '<span class="LC_nobreak">'.
                    505:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    506:               &mt('Select User').'</a></span>';
1.74      www       507:    }
1.258     albertel  508:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       509:        $callargs .= ",'',1"; 
1.793     raeburn   510:        return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    512:               &mt('Select User').'</a></span>';
1.111     www       513:    }
                    514:    return '';
1.91      www       515: }
                    516: 
1.1004    www       517: sub selectresource_link {
                    518:    my ($form,$reslink,$arg)=@_;
                    519:    
                    520:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    521:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    522:    unless ($env{'request.course.id'}) { return $arg; }
                    523:    return '<span class="LC_nobreak">'.
                    524:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    525:               $arg.'</a></span>';
                    526: }
                    527: 
                    528: 
                    529: 
1.653     raeburn   530: sub authorbrowser_javascript {
                    531:     return <<"ENDAUTHORBRW";
1.776     bisitz    532: <script type="text/javascript" language="JavaScript">
1.824     bisitz    533: // <![CDATA[
1.653     raeburn   534: var stdeditbrowser;
                    535: 
                    536: function openauthorbrowser(formname,udom) {
                    537:     var url = '/adm/pickauthor?';
                    538:     url += 'form='+formname+'&roledom='+udom;
                    539:     var title = 'Author_Browser';
                    540:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    541:     options += ',width=700,height=600';
                    542:     stdeditbrowser = open(url,title,options,'1');
                    543:     stdeditbrowser.focus();
                    544: }
                    545: 
1.824     bisitz    546: // ]]>
1.653     raeburn   547: </script>
                    548: ENDAUTHORBRW
                    549: }
                    550: 
1.91      www       551: sub coursebrowser_javascript {
1.1075.2.31  raeburn   552:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   553:         $credits_element,$instcode) = @_;
1.932     raeburn   554:     my $wintitle = 'Course_Browser';
1.931     raeburn   555:     if ($crstype eq 'Community') {
1.932     raeburn   556:         $wintitle = 'Community_Browser';
1.909     raeburn   557:     }
1.876     raeburn   558:     my $id_functions = &javascript_index_functions();
                    559:     my $output = '
1.776     bisitz    560: <script type="text/javascript" language="JavaScript">
1.824     bisitz    561: // <![CDATA[
1.468     raeburn   562:     var stdeditbrowser;'."\n";
1.876     raeburn   563: 
                    564:     $output .= <<"ENDSTDBRW";
1.909     raeburn   565:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       566:         var url = '/adm/pickcourse?';
1.895     raeburn   567:         var formid = getFormIdByName(formname);
1.876     raeburn   568:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  569:         if (domainfilter != null) {
                    570:            if (domainfilter != '') {
                    571:                url += 'domainfilter='+domainfilter+'&';
                    572: 	   }
                    573:         }
1.91      www       574:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  575: 	                            '&cdomelement='+udom+
                    576:                                     '&cnameelement='+desc;
1.468     raeburn   577:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   578:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   579:                 url += '&roleelement='+extra_element;
                    580:                 if (domainfilter == null || domainfilter == '') {
                    581:                     url += '&domainfilter='+extra_element;
                    582:                 }
1.234     raeburn   583:             }
1.468     raeburn   584:             else {
                    585:                 if (formname == 'portform') {
                    586:                     url += '&setroles='+extra_element;
1.800     raeburn   587:                 } else {
                    588:                     if (formname == 'rules') {
                    589:                         url += '&fixeddom='+extra_element; 
                    590:                     }
1.468     raeburn   591:                 }
                    592:             }     
1.230     raeburn   593:         }
1.909     raeburn   594:         if (type != null && type != '') {
                    595:             url += '&type='+type;
                    596:         }
                    597:         if (type_elem != null && type_elem != '') {
                    598:             url += '&typeelement='+type_elem;
                    599:         }
1.872     raeburn   600:         if (formname == 'ccrs') {
                    601:             var ownername = document.forms[formid].ccuname.value;
                    602:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   603:             url += '&cloner='+ownername+':'+ownerdom;
                    604:             if (type == 'Course') {
                    605:                 url += '&crscode='+document.forms[formid].crscode.value;
                    606:             }
1.1075.2.95  raeburn   607:         }
                    608:         if (formname == 'requestcrs') {
                    609:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   610:         }
1.293     raeburn   611:         if (multflag !=null && multflag != '') {
                    612:             url += '&multiple='+multflag;
                    613:         }
1.909     raeburn   614:         var title = '$wintitle';
1.91      www       615:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    616:         options += ',width=700,height=600';
                    617:         stdeditbrowser = open(url,title,options,'1');
                    618:         stdeditbrowser.focus();
                    619:     }
1.876     raeburn   620: $id_functions
                    621: ENDSTDBRW
1.1075.2.31  raeburn   622:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    623:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    624:                                       $credits_element);
1.876     raeburn   625:     }
                    626:     $output .= '
                    627: // ]]>
                    628: </script>';
                    629:     return $output;
                    630: }
                    631: 
                    632: sub javascript_index_functions {
                    633:     return <<"ENDJS";
                    634: 
                    635: function getFormIdByName(formname) {
                    636:     for (var i=0;i<document.forms.length;i++) {
                    637:         if (document.forms[i].name == formname) {
                    638:             return i;
                    639:         }
                    640:     }
                    641:     return -1;
                    642: }
                    643: 
                    644: function getIndexByName(formid,item) {
                    645:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    646:         if (document.forms[formid].elements[i].name == item) {
                    647:             return i;
                    648:         }
                    649:     }
                    650:     return -1;
                    651: }
1.468     raeburn   652: 
1.876     raeburn   653: function getDomainFromSelectbox(formname,udom) {
                    654:     var userdom;
                    655:     var formid = getFormIdByName(formname);
                    656:     if (formid > -1) {
                    657:         var domid = getIndexByName(formid,udom);
                    658:         if (domid > -1) {
                    659:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    660:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    661:             }
                    662:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    663:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   664:             }
                    665:         }
                    666:     }
1.876     raeburn   667:     return userdom;
                    668: }
                    669: 
                    670: ENDJS
1.468     raeburn   671: 
1.876     raeburn   672: }
                    673: 
1.1017    raeburn   674: sub javascript_array_indexof {
1.1018    raeburn   675:     return <<ENDJS;
1.1017    raeburn   676: <script type="text/javascript" language="JavaScript">
                    677: // <![CDATA[
                    678: 
                    679: if (!Array.prototype.indexOf) {
                    680:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    681:         "use strict";
                    682:         if (this === void 0 || this === null) {
                    683:             throw new TypeError();
                    684:         }
                    685:         var t = Object(this);
                    686:         var len = t.length >>> 0;
                    687:         if (len === 0) {
                    688:             return -1;
                    689:         }
                    690:         var n = 0;
                    691:         if (arguments.length > 0) {
                    692:             n = Number(arguments[1]);
                    693:             if (n !== n) { // shortcut for verifying if it's NaN
                    694:                 n = 0;
                    695:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    696:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    697:             }
                    698:         }
                    699:         if (n >= len) {
                    700:             return -1;
                    701:         }
                    702:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    703:         for (; k < len; k++) {
                    704:             if (k in t && t[k] === searchElement) {
                    705:                 return k;
                    706:             }
                    707:         }
                    708:         return -1;
                    709:     }
                    710: }
                    711: 
                    712: // ]]>
                    713: </script>
                    714: 
                    715: ENDJS
                    716: 
                    717: }
                    718: 
1.876     raeburn   719: sub userbrowser_javascript {
                    720:     my $id_functions = &javascript_index_functions();
                    721:     return <<"ENDUSERBRW";
                    722: 
1.888     raeburn   723: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   724:     var url = '/adm/pickuser?';
                    725:     var userdom = getDomainFromSelectbox(formname,udom);
                    726:     if (userdom != null) {
                    727:        if (userdom != '') {
                    728:            url += 'srchdom='+userdom+'&';
                    729:        }
                    730:     }
                    731:     url += 'form=' + formname + '&unameelement='+uname+
                    732:                                 '&udomelement='+udom+
                    733:                                 '&ulastelement='+ulast+
                    734:                                 '&ufirstelement='+ufirst+
                    735:                                 '&uemailelement='+uemail+
1.881     raeburn   736:                                 '&hideudomelement='+hideudom+
                    737:                                 '&coursedom='+crsdom;
1.888     raeburn   738:     if ((caller != null) && (caller != undefined)) {
                    739:         url += '&caller='+caller;
                    740:     }
1.876     raeburn   741:     var title = 'User_Browser';
                    742:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    743:     options += ',width=700,height=600';
                    744:     var stdeditbrowser = open(url,title,options,'1');
                    745:     stdeditbrowser.focus();
                    746: }
                    747: 
1.888     raeburn   748: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   749:     var formid = getFormIdByName(formname);
                    750:     if (formid > -1) {
1.888     raeburn   751:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   752:         var domid = getIndexByName(formid,udom);
                    753:         var hidedomid = getIndexByName(formid,origdom);
                    754:         if (hidedomid > -1) {
                    755:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   756:             var unameval = document.forms[formid].elements[unameid].value;
                    757:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    758:                 if (domid > -1) {
                    759:                     var slct = document.forms[formid].elements[domid];
                    760:                     if (slct.type == 'select-one') {
                    761:                         var i;
                    762:                         for (i=0;i<slct.length;i++) {
                    763:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    764:                         }
                    765:                     }
                    766:                     if (slct.type == 'hidden') {
                    767:                         slct.value = fixeddom;
1.876     raeburn   768:                     }
                    769:                 }
1.468     raeburn   770:             }
                    771:         }
                    772:     }
1.876     raeburn   773:     return;
                    774: }
                    775: 
                    776: $id_functions
                    777: ENDUSERBRW
1.468     raeburn   778: }
                    779: 
                    780: sub setsec_javascript {
1.1075.2.31  raeburn   781:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   782:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    783:         $communityrolestr);
                    784:     if ($role_element ne '') {
                    785:         my @allroles = ('st','ta','ep','in','ad');
                    786:         foreach my $crstype ('Course','Community') {
                    787:             if ($crstype eq 'Community') {
                    788:                 foreach my $role (@allroles) {
                    789:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    790:                 }
                    791:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    792:             } else {
                    793:                 foreach my $role (@allroles) {
                    794:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    795:                 }
                    796:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    797:             }
                    798:         }
                    799:         $rolestr = '"'.join('","',@allroles).'"';
                    800:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    801:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    802:     }
1.468     raeburn   803:     my $setsections = qq|
                    804: function setSect(sectionlist) {
1.629     raeburn   805:     var sectionsArray = new Array();
                    806:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    807:         sectionsArray = sectionlist.split(",");
                    808:     }
1.468     raeburn   809:     var numSections = sectionsArray.length;
                    810:     document.$formname.$sec_element.length = 0;
                    811:     if (numSections == 0) {
                    812:         document.$formname.$sec_element.multiple=false;
                    813:         document.$formname.$sec_element.size=1;
                    814:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    815:     } else {
                    816:         if (numSections == 1) {
                    817:             document.$formname.$sec_element.multiple=false;
                    818:             document.$formname.$sec_element.size=1;
                    819:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    820:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    821:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    822:         } else {
                    823:             for (var i=0; i<numSections; i++) {
                    824:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    825:             }
                    826:             document.$formname.$sec_element.multiple=true
                    827:             if (numSections < 3) {
                    828:                 document.$formname.$sec_element.size=numSections;
                    829:             } else {
                    830:                 document.$formname.$sec_element.size=3;
                    831:             }
                    832:             document.$formname.$sec_element.options[0].selected = false
                    833:         }
                    834:     }
1.91      www       835: }
1.905     raeburn   836: 
                    837: function setRole(crstype) {
1.468     raeburn   838: |;
1.905     raeburn   839:     if ($role_element eq '') {
                    840:         $setsections .= '    return;
                    841: }
                    842: ';
                    843:     } else {
                    844:         $setsections .= qq|
                    845:     var elementLength = document.$formname.$role_element.length;
                    846:     var allroles = Array($rolestr);
                    847:     var courserolenames = Array($courserolestr);
                    848:     var communityrolenames = Array($communityrolestr);
                    849:     if (elementLength != undefined) {
                    850:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    851:             if (crstype == 'Course') {
                    852:                 return;
                    853:             } else {
                    854:                 allroles[5] = 'co';
                    855:                 for (var i=0; i<6; i++) {
                    856:                     document.$formname.$role_element.options[i].value = allroles[i];
                    857:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    858:                 }
                    859:             }
                    860:         } else {
                    861:             if (crstype == 'Community') {
                    862:                 return;
                    863:             } else {
                    864:                 allroles[5] = 'cc';
                    865:                 for (var i=0; i<6; i++) {
                    866:                     document.$formname.$role_element.options[i].value = allroles[i];
                    867:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    868:                 }
                    869:             }
                    870:         }
                    871:     }
                    872:     return;
                    873: }
                    874: |;
                    875:     }
1.1075.2.31  raeburn   876:     if ($credits_element) {
                    877:         $setsections .= qq|
                    878: function setCredits(defaultcredits) {
                    879:     document.$formname.$credits_element.value = defaultcredits;
                    880:     return;
                    881: }
                    882: |;
                    883:     }
1.468     raeburn   884:     return $setsections;
                    885: }
                    886: 
1.91      www       887: sub selectcourse_link {
1.909     raeburn   888:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    889:        $typeelement) = @_;
                    890:    my $type = $selecttype;
1.871     raeburn   891:    my $linktext = &mt('Select Course');
                    892:    if ($selecttype eq 'Community') {
1.909     raeburn   893:        $linktext = &mt('Select Community');
1.906     raeburn   894:    } elsif ($selecttype eq 'Course/Community') {
                    895:        $linktext = &mt('Select Course/Community');
1.909     raeburn   896:        $type = '';
1.1019    raeburn   897:    } elsif ($selecttype eq 'Select') {
                    898:        $linktext = &mt('Select');
                    899:        $type = '';
1.871     raeburn   900:    }
1.787     bisitz    901:    return '<span class="LC_nobreak">'
                    902:          ."<a href='"
                    903:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    904:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   905:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   906:          ."'>".$linktext.'</a>'
1.787     bisitz    907:          .'</span>';
1.74      www       908: }
1.42      matthew   909: 
1.653     raeburn   910: sub selectauthor_link {
                    911:    my ($form,$udom)=@_;
                    912:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    913:           &mt('Select Author').'</a>';
                    914: }
                    915: 
1.876     raeburn   916: sub selectuser_link {
1.881     raeburn   917:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   918:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   919:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   920:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   921:            ');">'.$linktext.'</a>';
1.876     raeburn   922: }
                    923: 
1.273     raeburn   924: sub check_uncheck_jscript {
                    925:     my $jscript = <<"ENDSCRT";
                    926: function checkAll(field) {
                    927:     if (field.length > 0) {
                    928:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   929:             if (!field[i].disabled) {
                    930:                 field[i].checked = true;
                    931:             }
1.273     raeburn   932:         }
                    933:     } else {
1.1075.2.14  raeburn   934:         if (!field.disabled) {
                    935:             field.checked = true;
                    936:         }
1.273     raeburn   937:     }
                    938: }
                    939:  
                    940: function uncheckAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
                    943:             field[i].checked = false ;
1.543     albertel  944:         }
                    945:     } else {
1.273     raeburn   946:         field.checked = false ;
                    947:     }
                    948: }
                    949: ENDSCRT
                    950:     return $jscript;
                    951: }
                    952: 
1.656     www       953: sub select_timezone {
1.1075.2.161.  .10(raeb  954:-22):    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    955:-22):    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   956:    if ($includeempty) {
                    957:        $output .= '<option value=""';
                    958:        if (($selected eq '') || ($selected eq 'local')) {
                    959:            $output .= ' selected="selected" ';
                    960:        }
                    961:        $output .= '> </option>';
                    962:    }
1.657     raeburn   963:    my @timezones = DateTime::TimeZone->all_names;
                    964:    foreach my $tzone (@timezones) {
                    965:        $output.= '<option value="'.$tzone.'"';
                    966:        if ($tzone eq $selected) {
                    967:            $output.=' selected="selected"';
                    968:        }
                    969:        $output.=">$tzone</option>\n";
1.656     www       970:    }
                    971:    $output.="</select>";
                    972:    return $output;
                    973: }
1.273     raeburn   974: 
1.687     raeburn   975: sub select_datelocale {
1.1075.2.115  raeburn   976:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    977:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   978:     if ($includeempty) {
                    979:         $output .= '<option value=""';
                    980:         if ($selected eq '') {
                    981:             $output .= ' selected="selected" ';
                    982:         }
                    983:         $output .= '> </option>';
                    984:     }
1.1075.2.102  raeburn   985:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   986:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   987:     my @locales = DateTime::Locale->ids();
                    988:     foreach my $id (@locales) {
                    989:         if ($id ne '') {
                    990:             my ($en_terr,$native_terr);
                    991:             my $loc = DateTime::Locale->load($id);
                    992:             if (ref($loc)) {
                    993:                 $en_terr = $loc->name();
                    994:                 $native_terr = $loc->native_name();
1.687     raeburn   995:                 if (grep(/^en$/,@languages) || !@languages) {
                    996:                     if ($en_terr ne '') {
                    997:                         $locale_names{$id} = '('.$en_terr.')';
                    998:                     } elsif ($native_terr ne '') {
                    999:                         $locale_names{$id} = $native_terr;
                   1000:                     }
                   1001:                 } else {
                   1002:                     if ($native_terr ne '') {
                   1003:                         $locale_names{$id} = $native_terr.' ';
                   1004:                     } elsif ($en_terr ne '') {
                   1005:                         $locale_names{$id} = '('.$en_terr.')';
                   1006:                     }
                   1007:                 }
1.1075.2.94  raeburn  1008:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1009:                 push(@possibles,$id);
1.687     raeburn  1010:             }
                   1011:         }
                   1012:     }
                   1013:     foreach my $item (sort(@possibles)) {
                   1014:         $output.= '<option value="'.$item.'"';
                   1015:         if ($item eq $selected) {
                   1016:             $output.=' selected="selected"';
                   1017:         }
                   1018:         $output.=">$item";
                   1019:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1020:             $output.='  '.$locale_names{$item};
1.687     raeburn  1021:         }
                   1022:         $output.="</option>\n";
                   1023:     }
                   1024:     $output.="</select>";
                   1025:     return $output;
                   1026: }
                   1027: 
1.792     raeburn  1028: sub select_language {
1.1075.2.115  raeburn  1029:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1030:     my %langchoices;
                   1031:     if ($includeempty) {
1.1075.2.32  raeburn  1032:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1033:     }
                   1034:     foreach my $id (&languageids()) {
                   1035:         my $code = &supportedlanguagecode($id);
                   1036:         if ($code) {
                   1037:             $langchoices{$code} = &plainlanguagedescription($id);
                   1038:         }
                   1039:     }
1.1075.2.32  raeburn  1040:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1041:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1042: }
                   1043: 
1.42      matthew  1044: =pod
1.36      matthew  1045: 
1.648     raeburn  1046: =item * &linked_select_forms(...)
1.36      matthew  1047: 
                   1048: linked_select_forms returns a string containing a <script></script> block
                   1049: and html for two <select> menus.  The select menus will be linked in that
                   1050: changing the value of the first menu will result in new values being placed
                   1051: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1052: order unless a defined order is provided.
1.36      matthew  1053: 
                   1054: linked_select_forms takes the following ordered inputs:
                   1055: 
                   1056: =over 4
                   1057: 
1.112     bowersj2 1058: =item * $formname, the name of the <form> tag
1.36      matthew  1059: 
1.112     bowersj2 1060: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1061: 
1.112     bowersj2 1062: =item * $firstdefault, the default value for the first menu
1.36      matthew  1063: 
1.112     bowersj2 1064: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1069: 
1.609     raeburn  1070: =item * $menuorder, the order of values in the first menu
                   1071: 
1.1075.2.31  raeburn  1072: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1073:         event for the first <select> tag
                   1074: 
                   1075: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1076:         event for the second <select> tag
                   1077: 
1.41      ng       1078: =back 
                   1079: 
1.36      matthew  1080: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1081: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1082: values for the first select menu.  The text that coincides with the 
1.41      ng       1083: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1084: and text for the second menu are given in the hash pointed to by 
                   1085: $menu{$choice1}->{'select2'}.  
                   1086: 
1.112     bowersj2 1087:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1088:                        default => "B3",
                   1089:                        select2 => { 
                   1090:                            B1 => "Choice B1",
                   1091:                            B2 => "Choice B2",
                   1092:                            B3 => "Choice B3",
                   1093:                            B4 => "Choice B4"
1.609     raeburn  1094:                            },
                   1095:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1096:                    },
                   1097:                A2 => { text =>"Choice A2" ,
                   1098:                        default => "C2",
                   1099:                        select2 => { 
                   1100:                            C1 => "Choice C1",
                   1101:                            C2 => "Choice C2",
                   1102:                            C3 => "Choice C3"
1.609     raeburn  1103:                            },
                   1104:                        order => ['C2','C1','C3'],
1.112     bowersj2 1105:                    },
                   1106:                A3 => { text =>"Choice A3" ,
                   1107:                        default => "D6",
                   1108:                        select2 => { 
                   1109:                            D1 => "Choice D1",
                   1110:                            D2 => "Choice D2",
                   1111:                            D3 => "Choice D3",
                   1112:                            D4 => "Choice D4",
                   1113:                            D5 => "Choice D5",
                   1114:                            D6 => "Choice D6",
                   1115:                            D7 => "Choice D7"
1.609     raeburn  1116:                            },
                   1117:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1118:                    }
                   1119:                );
1.36      matthew  1120: 
                   1121: =cut
                   1122: 
                   1123: sub linked_select_forms {
                   1124:     my ($formname,
                   1125:         $middletext,
                   1126:         $firstdefault,
                   1127:         $firstselectname,
                   1128:         $secondselectname, 
1.609     raeburn  1129:         $hashref,
                   1130:         $menuorder,
1.1075.2.31  raeburn  1131:         $onchangefirst,
                   1132:         $onchangesecond
1.36      matthew  1133:         ) = @_;
                   1134:     my $second = "document.$formname.$secondselectname";
                   1135:     my $first = "document.$formname.$firstselectname";
                   1136:     # output the javascript to do the changing
                   1137:     my $result = '';
1.776     bisitz   1138:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1139:     $result.="// <![CDATA[\n";
1.36      matthew  1140:     $result.="var select2data = new Object();\n";
                   1141:     $" = '","';
                   1142:     my $debug = '';
                   1143:     foreach my $s1 (sort(keys(%$hashref))) {
                   1144:         $result.="select2data.d_$s1 = new Object();\n";        
                   1145:         $result.="select2data.d_$s1.def = new String('".
                   1146:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1147:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1148:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1149:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1150:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1151:         }
1.36      matthew  1152:         $result.="\"@s2values\");\n";
                   1153:         $result.="select2data.d_$s1.texts = new Array(";        
                   1154:         my @s2texts;
                   1155:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1156:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1157:         }
                   1158:         $result.="\"@s2texts\");\n";
                   1159:     }
                   1160:     $"=' ';
                   1161:     $result.= <<"END";
                   1162: 
                   1163: function select1_changed() {
                   1164:     // Determine new choice
                   1165:     var newvalue = "d_" + $first.value;
                   1166:     // update select2
                   1167:     var values     = select2data[newvalue].values;
                   1168:     var texts      = select2data[newvalue].texts;
                   1169:     var select2def = select2data[newvalue].def;
                   1170:     var i;
                   1171:     // out with the old
                   1172:     for (i = 0; i < $second.options.length; i++) {
                   1173:         $second.options[i] = null;
                   1174:     }
                   1175:     // in with the nuclear
                   1176:     for (i=0;i<values.length; i++) {
                   1177:         $second.options[i] = new Option(values[i]);
1.143     matthew  1178:         $second.options[i].value = values[i];
1.36      matthew  1179:         $second.options[i].text = texts[i];
                   1180:         if (values[i] == select2def) {
                   1181:             $second.options[i].selected = true;
                   1182:         }
                   1183:     }
                   1184: }
1.824     bisitz   1185: // ]]>
1.36      matthew  1186: </script>
                   1187: END
                   1188:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1189:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1190:     my @order = sort(keys(%{$hashref}));
                   1191:     if (ref($menuorder) eq 'ARRAY') {
                   1192:         @order = @{$menuorder};
                   1193:     }
                   1194:     foreach my $value (@order) {
1.36      matthew  1195:         $result.="    <option value=\"$value\" ";
1.253     albertel 1196:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1197:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1198:     }
                   1199:     $result .= "</select>\n";
                   1200:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1201:     $result .= $middletext;
1.1075.2.31  raeburn  1202:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1203:     if ($onchangesecond) {
                   1204:         $result .= ' onchange="'.$onchangesecond.'"';
                   1205:     }
                   1206:     $result .= ">\n";
1.36      matthew  1207:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1208:     
                   1209:     my @secondorder = sort(keys(%select2));
                   1210:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1211:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1212:     }
                   1213:     foreach my $value (@secondorder) {
1.36      matthew  1214:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1215:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1216:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1217:     }
                   1218:     $result .= "</select>\n";
                   1219:     #    return $debug;
                   1220:     return $result;
                   1221: }   #  end of sub linked_select_forms {
                   1222: 
1.45      matthew  1223: =pod
1.44      bowersj2 1224: 
1.1075.2.161.  .6(raebu 1225:22): =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1226: 
1.112     bowersj2 1227: Returns a string corresponding to an HTML link to the given help
                   1228: $topic, where $topic corresponds to the name of a .tex file in
                   1229: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1230: spaces. 
                   1231: 
                   1232: $text will optionally be linked to the same topic, allowing you to
                   1233: link text in addition to the graphic. If you do not want to link
                   1234: text, but wish to specify one of the later parameters, pass an
                   1235: empty string. 
                   1236: 
                   1237: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1238: the link will not open a new window. If false, the link will open
                   1239: a new window using Javascript. (Default is false.) 
                   1240: 
                   1241: $width and $height are optional numerical parameters that will
                   1242: override the width and height of the popped up window, which may
1.973     raeburn  1243: be useful for certain help topics with big pictures included.
                   1244: 
                   1245: $imgid is the id of the img tag used for the help icon. This may be
                   1246: used in a javascript call to switch the image src.  See 
                   1247: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1248: 
1.1075.2.161.  .6(raebu 1249:22): $links_target will optionally be set to a target (_top, _parent or _self).
                   1250:22): 
1.44      bowersj2 1251: =cut
                   1252: 
                   1253: sub help_open_topic {
1.1075.2.161.  .6(raebu 1254:22):     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1255:     $text = "" if (not defined $text);
1.44      bowersj2 1256:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1257:     $width = 500 if (not defined $width);
1.44      bowersj2 1258:     $height = 400 if (not defined $height);
                   1259:     my $filename = $topic;
                   1260:     $filename =~ s/ /_/g;
                   1261: 
1.48      bowersj2 1262:     my $template = "";
                   1263:     my $link;
1.572     banghart 1264:     
1.159     www      1265:     $topic=~s/\W/\_/g;
1.44      bowersj2 1266: 
1.572     banghart 1267:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1268:         if ($env{'browser.mobile'}) {
                   1269: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1270:         } else {
                   1271:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1272:         }
1.1037    www      1273:     } elsif ($stayOnPage eq 'popup') {
                   1274:         $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 1275:     } else {
1.48      bowersj2 1276: 	$link = "/adm/help/${filename}.hlp";
                   1277:     }
                   1278: 
                   1279:     # Add the text
1.1075.2.161.  .6(raebu 1280:22):     my $target = ' target="_top"';
                   1281:22):     if ($links_target) {
                   1282:22):         $target = ' target="'.$links_target.'"';
          .17(raeb 1283:-23):     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1284:-23):              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
          .6(raebu 1285:22):         $target = '';
                   1286:22):     }
1.755     neumanie 1287:     if ($text ne "") {	
1.763     bisitz   1288: 	$template.='<span class="LC_help_open_topic">'
1.1075.2.161.  .6(raebu 1289:22):                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1290:                   .$text.'</a>';
1.48      bowersj2 1291:     }
                   1292: 
1.763     bisitz   1293:     # (Always) Add the graphic
1.179     matthew  1294:     my $title = &mt('Online Help');
1.667     raeburn  1295:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1296:     if ($imgid ne '') {
                   1297:         $imgid = ' id="'.$imgid.'"';
                   1298:     }
1.1075.2.161.  .6(raebu 1299:22):     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1300:               .'<img src="'.$helpicon.'" border="0"'
                   1301:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1302:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1303:               .' /></a>';
                   1304:     if ($text ne "") {	
                   1305:         $template.='</span>';
                   1306:     }
1.44      bowersj2 1307:     return $template;
                   1308: 
1.106     bowersj2 1309: }
                   1310: 
                   1311: # This is a quicky function for Latex cheatsheet editing, since it 
                   1312: # appears in at least four places
                   1313: sub helpLatexCheatsheet {
1.1037    www      1314:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1315:     my $out;
1.106     bowersj2 1316:     my $addOther = '';
1.732     raeburn  1317:     if ($topic) {
1.1037    www      1318: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1319:     }
                   1320:     $out = '<span>' # Start cheatsheet
                   1321: 	  .$addOther
                   1322:           .'<span>'
1.1037    www      1323: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1324: 	  .'</span> <span>'
1.1037    www      1325: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1326: 	  .'</span>';
1.732     raeburn  1327:     unless ($not_author) {
1.763     bisitz   1328:         $out .= ' <span>'
1.1037    www      1329: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1330: 	       .'</span> <span>'
1.1075.2.78  raeburn  1331:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1332:                .'</span>';
1.732     raeburn  1333:     }
1.763     bisitz   1334:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1335:     return $out;
1.172     www      1336: }
                   1337: 
1.430     albertel 1338: sub general_help {
                   1339:     my $helptopic='Student_Intro';
                   1340:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1341: 	$helptopic='Authoring_Intro';
1.907     raeburn  1342:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1343: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1344:     } elsif ($env{'request.role'}=~/^dc/) {
                   1345:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1346:     }
                   1347:     return $helptopic;
                   1348: }
                   1349: 
                   1350: sub update_help_link {
                   1351:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1352:     my $origurl = $ENV{'REQUEST_URI'};
                   1353:     $origurl=~s|^/~|/priv/|;
                   1354:     my $timestamp = time;
                   1355:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1356:         $$datum = &escape($$datum);
                   1357:     }
                   1358: 
                   1359:     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";
                   1360:     my $output .= <<"ENDOUTPUT";
                   1361: <script type="text/javascript">
1.824     bisitz   1362: // <![CDATA[
1.430     albertel 1363: banner_link = '$banner_link';
1.824     bisitz   1364: // ]]>
1.430     albertel 1365: </script>
                   1366: ENDOUTPUT
                   1367:     return $output;
                   1368: }
                   1369: 
                   1370: # now just updates the help link and generates a blue icon
1.193     raeburn  1371: sub help_open_menu {
1.1075.2.161.  .6(raebu 1372:22):     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1373: 	= @_;    
1.949     droeschl 1374:     $stayOnPage = 1;
1.430     albertel 1375:     my $output;
                   1376:     if ($component_help) {
                   1377: 	if (!$text) {
                   1378: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1075.2.161.  .6(raebu 1379:22): 				       $width,$height,'',$links_target);
1.430     albertel 1380: 	} else {
                   1381: 	    my $help_text;
                   1382: 	    $help_text=&unescape($topic);
                   1383: 	    $output='<table><tr><td>'.
                   1384: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1075.2.161.  .6(raebu 1385:22): 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1386: 	}
                   1387:     }
                   1388:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1389:     return $output.$banner_link;
                   1390: }
                   1391: 
                   1392: sub top_nav_help {
1.1075.2.158  raeburn  1393:     my ($text,$linkattr) = @_;
1.436     albertel 1394:     $text = &mt($text);
1.1075.2.60  raeburn  1395:     my $stay_on_page;
                   1396:     unless ($env{'environment.remote'} eq 'on') {
                   1397:         $stay_on_page = 1;
                   1398:     }
1.1075.2.61  raeburn  1399:     my ($link,$banner_link);
                   1400:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1401:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1402: 	                         : "javascript:helpMenu('open')";
                   1403:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1404:     }
1.201     raeburn  1405:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1406:     if ($link) {
                   1407:         return <<"END";
1.436     albertel 1408: $banner_link
1.1075.2.158  raeburn  1409: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1410: END
1.1075.2.61  raeburn  1411:     } else {
                   1412:         return '&nbsp;'.$text.'&nbsp;';
                   1413:     }
1.436     albertel 1414: }
                   1415: 
                   1416: sub help_menu_js {
1.1075.2.52  raeburn  1417:     my ($httphost) = @_;
1.949     droeschl 1418:     my $stayOnPage = 1;
1.436     albertel 1419:     my $width = 620;
                   1420:     my $height = 600;
1.430     albertel 1421:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1422:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1423:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1424:     my $start_page =
                   1425:         &Apache::loncommon::start_page('Help Menu', undef,
                   1426: 				       {'frameset'    => 1,
                   1427: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1428:                                         'use_absolute' => $httphost,
1.331     albertel 1429: 					'add_entries' => {
                   1430: 					    'border' => '0',
1.579     raeburn  1431: 					    'rows'   => "110,*",},});
1.331     albertel 1432:     my $end_page =
                   1433:         &Apache::loncommon::end_page({'frameset' => 1,
                   1434: 				      'js_ready' => 1,});
                   1435: 
1.436     albertel 1436:     my $template .= <<"ENDTEMPLATE";
                   1437: <script type="text/javascript">
1.877     bisitz   1438: // <![CDATA[
1.253     albertel 1439: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1440: var banner_link = '';
1.243     raeburn  1441: function helpMenu(target) {
                   1442:     var caller = this;
                   1443:     if (target == 'open') {
                   1444:         var newWindow = null;
                   1445:         try {
1.262     albertel 1446:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1447:         }
                   1448:         catch(error) {
                   1449:             writeHelp(caller);
                   1450:             return;
                   1451:         }
                   1452:         if (newWindow) {
                   1453:             caller = newWindow;
                   1454:         }
1.193     raeburn  1455:     }
1.243     raeburn  1456:     writeHelp(caller);
                   1457:     return;
                   1458: }
                   1459: function writeHelp(caller) {
1.1075.2.61  raeburn  1460:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1461:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1462:     caller.document.close();
                   1463:     caller.focus();
1.193     raeburn  1464: }
1.877     bisitz   1465: // END LON-CAPA Internal -->
1.253     albertel 1466: // ]]>
1.436     albertel 1467: </script>
1.193     raeburn  1468: ENDTEMPLATE
                   1469:     return $template;
                   1470: }
                   1471: 
1.172     www      1472: sub help_open_bug {
                   1473:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1474:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1475:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1476:     $text = "" if (not defined $text);
                   1477: 	$stayOnPage=1;
1.184     albertel 1478:     $width = 600 if (not defined $width);
                   1479:     $height = 600 if (not defined $height);
1.172     www      1480: 
                   1481:     $topic=~s/\W+/\+/g;
                   1482:     my $link='';
                   1483:     my $template='';
1.379     albertel 1484:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1485: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1486:     if (!$stayOnPage)
                   1487:     {
                   1488: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1489:     }
                   1490:     else
                   1491:     {
                   1492: 	$link = $url;
                   1493:     }
1.1075.2.161.  .6(raebu 1494:22): 
                   1495:22):     my $target = '_top';
                   1496:22):     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1497:22):         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1498:22):         $target = '_blank';
                   1499:22):     }
                   1500:22): 
1.172     www      1501:     # Add the text
                   1502:     if ($text ne "")
                   1503:     {
                   1504: 	$template .= 
                   1505:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1075.2.161.  .6(raebu 1506:22):   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1507:     }
                   1508: 
                   1509:     # Add the graphic
1.179     matthew  1510:     my $title = &mt('Report a Bug');
1.215     albertel 1511:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1512:     $template .= <<"ENDTEMPLATE";
1.1075.2.161.  .6(raebu 1513:22):  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1514: ENDTEMPLATE
                   1515:     if ($text ne '') { $template.='</td></tr></table>' };
                   1516:     return $template;
                   1517: 
                   1518: }
                   1519: 
                   1520: sub help_open_faq {
                   1521:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1522:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1523:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1524:     $text = "" if (not defined $text);
                   1525: 	$stayOnPage=1;
                   1526:     $width = 350 if (not defined $width);
                   1527:     $height = 400 if (not defined $height);
                   1528: 
                   1529:     $topic=~s/\W+/\+/g;
                   1530:     my $link='';
                   1531:     my $template='';
                   1532:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1533:     if (!$stayOnPage)
                   1534:     {
                   1535: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1536:     }
                   1537:     else
                   1538:     {
                   1539: 	$link = $url;
                   1540:     }
                   1541: 
                   1542:     # Add the text
                   1543:     if ($text ne "")
                   1544:     {
                   1545: 	$template .= 
1.173     www      1546:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1547:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1548:     }
                   1549: 
                   1550:     # Add the graphic
1.179     matthew  1551:     my $title = &mt('View the FAQ');
1.215     albertel 1552:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1553:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1554:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1555: ENDTEMPLATE
                   1556:     if ($text ne '') { $template.='</td></tr></table>' };
                   1557:     return $template;
                   1558: 
1.44      bowersj2 1559: }
1.37      matthew  1560: 
1.180     matthew  1561: ###############################################################
                   1562: ###############################################################
                   1563: 
1.45      matthew  1564: =pod
                   1565: 
1.648     raeburn  1566: =item * &change_content_javascript():
1.256     matthew  1567: 
                   1568: This and the next function allow you to create small sections of an
                   1569: otherwise static HTML page that you can update on the fly with
                   1570: Javascript, even in Netscape 4.
                   1571: 
                   1572: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1573: must be written to the HTML page once. It will prove the Javascript
                   1574: function "change(name, content)". Calling the change function with the
                   1575: name of the section 
                   1576: you want to update, matching the name passed to C<changable_area>, and
                   1577: the new content you want to put in there, will put the content into
                   1578: that area.
                   1579: 
                   1580: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1581: to contain room for the original contents. You need to "make space"
                   1582: for whatever changes you wish to make, and be B<sure> to check your
                   1583: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1584: it's adequate for updating a one-line status display, but little more.
                   1585: This script will set the space to 100% width, so you only need to
                   1586: worry about height in Netscape 4.
                   1587: 
                   1588: Modern browsers are much less limiting, and if you can commit to the
                   1589: user not using Netscape 4, this feature may be used freely with
                   1590: pretty much any HTML.
                   1591: 
                   1592: =cut
                   1593: 
                   1594: sub change_content_javascript {
                   1595:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1596:     if ($env{'browser.type'} eq 'netscape' &&
                   1597: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1598: 	return (<<NETSCAPE4);
                   1599: 	function change(name, content) {
                   1600: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1601: 	    doc.open();
                   1602: 	    doc.write(content);
                   1603: 	    doc.close();
                   1604: 	}
                   1605: NETSCAPE4
                   1606:     } else {
                   1607: 	# Otherwise, we need to use semi-standards-compliant code
                   1608: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1609: 	# is really scary, and every useful browser supports it
                   1610: 	return (<<DOMBASED);
                   1611: 	function change(name, content) {
                   1612: 	    element = document.getElementById(name);
                   1613: 	    element.innerHTML = content;
                   1614: 	}
                   1615: DOMBASED
                   1616:     }
                   1617: }
                   1618: 
                   1619: =pod
                   1620: 
1.648     raeburn  1621: =item * &changable_area($name,$origContent):
1.256     matthew  1622: 
                   1623: This provides a "changable area" that can be modified on the fly via
                   1624: the Javascript code provided in C<change_content_javascript>. $name is
                   1625: the name you will use to reference the area later; do not repeat the
                   1626: same name on a given HTML page more then once. $origContent is what
                   1627: the area will originally contain, which can be left blank.
                   1628: 
                   1629: =cut
                   1630: 
                   1631: sub changable_area {
                   1632:     my ($name, $origContent) = @_;
                   1633: 
1.258     albertel 1634:     if ($env{'browser.type'} eq 'netscape' &&
                   1635: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1636: 	# If this is netscape 4, we need to use the Layer tag
                   1637: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1638:     } else {
                   1639: 	return "<span id='$name'>$origContent</span>";
                   1640:     }
                   1641: }
                   1642: 
                   1643: =pod
                   1644: 
1.648     raeburn  1645: =item * &viewport_geometry_js 
1.590     raeburn  1646: 
                   1647: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1648: 
                   1649: =cut
                   1650: 
                   1651: 
                   1652: sub viewport_geometry_js { 
                   1653:     return <<"GEOMETRY";
                   1654: var Geometry = {};
                   1655: function init_geometry() {
                   1656:     if (Geometry.init) { return };
                   1657:     Geometry.init=1;
                   1658:     if (window.innerHeight) {
                   1659:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1660:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1661:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1662:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1663:     }
                   1664:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1665:         Geometry.getViewportHeight =
                   1666:             function() { return document.documentElement.clientHeight; };
                   1667:         Geometry.getViewportWidth =
                   1668:             function() { return document.documentElement.clientWidth; };
                   1669: 
                   1670:         Geometry.getHorizontalScroll =
                   1671:             function() { return document.documentElement.scrollLeft; };
                   1672:         Geometry.getVerticalScroll =
                   1673:             function() { return document.documentElement.scrollTop; };
                   1674:     }
                   1675:     else if (document.body.clientHeight) {
                   1676:         Geometry.getViewportHeight =
                   1677:             function() { return document.body.clientHeight; };
                   1678:         Geometry.getViewportWidth =
                   1679:             function() { return document.body.clientWidth; };
                   1680:         Geometry.getHorizontalScroll =
                   1681:             function() { return document.body.scrollLeft; };
                   1682:         Geometry.getVerticalScroll =
                   1683:             function() { return document.body.scrollTop; };
                   1684:     }
                   1685: }
                   1686: 
                   1687: GEOMETRY
                   1688: }
                   1689: 
                   1690: =pod
                   1691: 
1.648     raeburn  1692: =item * &viewport_size_js()
1.590     raeburn  1693: 
                   1694: 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. 
                   1695: 
                   1696: =cut
                   1697: 
                   1698: sub viewport_size_js {
                   1699:     my $geometry = &viewport_geometry_js();
                   1700:     return <<"DIMS";
                   1701: 
                   1702: $geometry
                   1703: 
                   1704: function getViewportDims(width,height) {
                   1705:     init_geometry();
                   1706:     width.value = Geometry.getViewportWidth();
                   1707:     height.value = Geometry.getViewportHeight();
                   1708:     return;
                   1709: }
                   1710: 
                   1711: DIMS
                   1712: }
                   1713: 
                   1714: =pod
                   1715: 
1.648     raeburn  1716: =item * &resize_textarea_js()
1.565     albertel 1717: 
                   1718: emits the needed javascript to resize a textarea to be as big as possible
                   1719: 
                   1720: creates a function resize_textrea that takes two IDs first should be
                   1721: the id of the element to resize, second should be the id of a div that
                   1722: surrounds everything that comes after the textarea, this routine needs
                   1723: to be attached to the <body> for the onload and onresize events.
                   1724: 
1.648     raeburn  1725: =back
1.565     albertel 1726: 
                   1727: =cut
                   1728: 
                   1729: sub resize_textarea_js {
1.590     raeburn  1730:     my $geometry = &viewport_geometry_js();
1.565     albertel 1731:     return <<"RESIZE";
                   1732:     <script type="text/javascript">
1.824     bisitz   1733: // <![CDATA[
1.590     raeburn  1734: $geometry
1.565     albertel 1735: 
1.588     albertel 1736: function getX(element) {
                   1737:     var x = 0;
                   1738:     while (element) {
                   1739: 	x += element.offsetLeft;
                   1740: 	element = element.offsetParent;
                   1741:     }
                   1742:     return x;
                   1743: }
                   1744: function getY(element) {
                   1745:     var y = 0;
                   1746:     while (element) {
                   1747: 	y += element.offsetTop;
                   1748: 	element = element.offsetParent;
                   1749:     }
                   1750:     return y;
                   1751: }
                   1752: 
                   1753: 
1.565     albertel 1754: function resize_textarea(textarea_id,bottom_id) {
                   1755:     init_geometry();
                   1756:     var textarea        = document.getElementById(textarea_id);
                   1757:     //alert(textarea);
                   1758: 
1.588     albertel 1759:     var textarea_top    = getY(textarea);
1.565     albertel 1760:     var textarea_height = textarea.offsetHeight;
                   1761:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1762:     var bottom_top      = getY(bottom);
1.565     albertel 1763:     var bottom_height   = bottom.offsetHeight;
                   1764:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1765:     var fudge           = 23;
1.565     albertel 1766:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1767:     if (new_height < 300) {
                   1768: 	new_height = 300;
                   1769:     }
                   1770:     textarea.style.height=new_height+'px';
                   1771: }
1.824     bisitz   1772: // ]]>
1.565     albertel 1773: </script>
                   1774: RESIZE
                   1775: 
                   1776: }
                   1777: 
1.1075.2.112  raeburn  1778: sub colorfuleditor_js {
                   1779:     return <<"COLORFULEDIT"
                   1780: <script type="text/javascript">
                   1781: // <![CDATA[>
                   1782:     function fold_box(curDepth, lastresource){
                   1783: 
                   1784:     // we need a list because there can be several blocks you need to fold in one tag
                   1785:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1786:     // but there is only one folding button per tag
                   1787:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1788: 
                   1789:         if(block.item(0).style.display == 'none'){
                   1790: 
                   1791:             foldbutton.value = '@{[&mt("Hide")]}';
                   1792:             for (i = 0; i < block.length; i++){
                   1793:                 block.item(i).style.display = '';
                   1794:             }
                   1795:         }else{
                   1796: 
                   1797:             foldbutton.value = '@{[&mt("Show")]}';
                   1798:             for (i = 0; i < block.length; i++){
                   1799:                 // block.item(i).style.visibility = 'collapse';
                   1800:                 block.item(i).style.display = 'none';
                   1801:             }
                   1802:         };
                   1803:         saveState(lastresource);
                   1804:     }
                   1805: 
                   1806:     function saveState (lastresource) {
                   1807: 
                   1808:         var tag_list = getTagList();
                   1809:         if(tag_list != null){
                   1810:             var timestamp = new Date().getTime();
                   1811:             var key = lastresource;
                   1812: 
                   1813:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1814:             // starting with timestamp
                   1815:             var value = timestamp+';';
                   1816: 
                   1817:             // building the list of key-value pairs
                   1818:             for(var i = 0; i < tag_list.length; i++){
                   1819:                 value += tag_list[i]+',';
                   1820:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1821:             }
                   1822: 
                   1823:             // only iterate whole storage if nothing to override
                   1824:             if(localStorage.getItem(key) == null){
                   1825: 
                   1826:                 // prevent storage from growing large
                   1827:                 if(localStorage.length > 50){
                   1828:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1829:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1830:                     var oldest_key;
                   1831: 
                   1832:                     for(var i = 1; i < localStorage.length; i++){
                   1833:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1834:                             oldest_key = localStorage.key(i);
                   1835:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1836:                         }
                   1837:                     }
                   1838:                     localStorage.removeItem(oldest_key);
                   1839:                 }
                   1840:             }
                   1841:             localStorage.setItem(key,value);
                   1842:         }
                   1843:     }
                   1844: 
                   1845:     // restore folding status of blocks (on page load)
                   1846:     function restoreState (lastresource) {
                   1847:         if(localStorage.getItem(lastresource) != null){
                   1848:             var key = lastresource;
                   1849:             var value = localStorage.getItem(key);
                   1850:             var regex_delTimestamp = /^\d+;/;
                   1851: 
                   1852:             value.replace(regex_delTimestamp, '');
                   1853: 
                   1854:             var valueArr = value.split(';');
                   1855:             var pairs;
                   1856:             var elements;
                   1857:             for (var i = 0; i < valueArr.length; i++){
                   1858:                 pairs = valueArr[i].split(',');
                   1859:                 elements = document.getElementsByName(pairs[0]);
                   1860: 
                   1861:                 for (var j = 0; j < elements.length; j++){
                   1862:                     elements[j].style.display = pairs[1];
                   1863:                     if (pairs[1] == "none"){
                   1864:                         var regex_id = /([_\\d]+)\$/;
                   1865:                         regex_id.exec(pairs[0]);
                   1866:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1867:                     }
                   1868:                 }
                   1869:             }
                   1870:         }
                   1871:     }
                   1872: 
                   1873:     function getTagList () {
                   1874: 
                   1875:         var stringToSearch = document.lonhomework.innerHTML;
                   1876: 
                   1877:         var ret = new Array();
                   1878:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1879:         var tag_list = stringToSearch.match(regex_findBlock);
                   1880: 
                   1881:         if(tag_list != null){
                   1882:             for(var i = 0; i < tag_list.length; i++){
                   1883:                 ret.push(tag_list[i].replace(/"/, ''));
                   1884:             }
                   1885:         }
                   1886:         return ret;
                   1887:     }
                   1888: 
                   1889:     function saveScrollPosition (resource) {
                   1890:         var tag_list = getTagList();
                   1891: 
                   1892:         // we dont always want to jump to the first block
                   1893:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1894:         if(\$(window).scrollTop() > 170){
                   1895:             if(tag_list != null){
                   1896:                 var result;
                   1897:                 for(var i = 0; i < tag_list.length; i++){
                   1898:                     if(isElementInViewport(tag_list[i])){
                   1899:                         result += tag_list[i]+';';
                   1900:                     }
                   1901:                 }
                   1902:                 sessionStorage.setItem('anchor_'+resource, result);
                   1903:             }
                   1904:         } else {
                   1905:             // we dont need to save zero, just delete the item to leave everything tidy
                   1906:             sessionStorage.removeItem('anchor_'+resource);
                   1907:         }
                   1908:     }
                   1909: 
                   1910:     function restoreScrollPosition(resource){
                   1911: 
                   1912:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1913:         if(elem != null){
                   1914:             var tag_list = elem.split(';');
                   1915:             var elem_list;
                   1916: 
                   1917:             for(var i = 0; i < tag_list.length; i++){
                   1918:                 elem_list = document.getElementsByName(tag_list[i]);
                   1919: 
                   1920:                 if(elem_list.length > 0){
                   1921:                     elem = elem_list[0];
                   1922:                     break;
                   1923:                 }
                   1924:             }
                   1925:             elem.scrollIntoView();
                   1926:         }
                   1927:     }
                   1928: 
                   1929:     function isElementInViewport(el) {
                   1930: 
                   1931:         // change to last element instead of first
                   1932:         var elem = document.getElementsByName(el);
                   1933:         var rect = elem[0].getBoundingClientRect();
                   1934: 
                   1935:         return (
                   1936:             rect.top >= 0 &&
                   1937:             rect.left >= 0 &&
                   1938:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1939:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1940:         );
                   1941:     }
                   1942: 
                   1943:     function autosize(depth){
                   1944:         var cmInst = window['cm'+depth];
                   1945:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1946: 
                   1947:         // is fixed size, switching to dynamic
                   1948:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1949:             cmInst.setSize("","auto");
                   1950:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1951:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1952: 
                   1953:         // is dynamic size, switching to fixed
                   1954:         } else {
                   1955:             cmInst.setSize("","300px");
                   1956:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1957:             sessionStorage.removeItem("autosized_"+depth);
                   1958:         }
                   1959:     }
                   1960: 
                   1961: 
                   1962: 
                   1963: // ]]>
                   1964: </script>
                   1965: COLORFULEDIT
                   1966: }
                   1967: 
                   1968: sub xmleditor_js {
                   1969:     return <<XMLEDIT
                   1970: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1971: <script type="text/javascript">
                   1972: // <![CDATA[>
                   1973: 
                   1974:     function saveScrollPosition (resource) {
                   1975: 
                   1976:         var scrollPos = \$(window).scrollTop();
                   1977:         sessionStorage.setItem(resource,scrollPos);
                   1978:     }
                   1979: 
                   1980:     function restoreScrollPosition(resource){
                   1981: 
                   1982:         var scrollPos = sessionStorage.getItem(resource);
                   1983:         \$(window).scrollTop(scrollPos);
                   1984:     }
                   1985: 
                   1986:     // unless internet explorer
                   1987:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1988: 
                   1989:         \$(document).ready(function() {
                   1990:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1991:         });
                   1992:     }
                   1993: 
                   1994:     // inserts text at cursor position into codemirror (xml editor only)
                   1995:     function insertText(text){
                   1996:         cm.focus();
                   1997:         var curPos = cm.getCursor();
                   1998:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1999:     }
                   2000: // ]]>
                   2001: </script>
                   2002: XMLEDIT
                   2003: }
                   2004: 
                   2005: sub insert_folding_button {
                   2006:     my $curDepth = $Apache::lonxml::curdepth;
                   2007:     my $lastresource = $env{'request.ambiguous'};
                   2008: 
                   2009:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   2010:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2011: }
                   2012: 
                   2013: 
1.565     albertel 2014: =pod
                   2015: 
1.256     matthew  2016: =head1 Excel and CSV file utility routines
                   2017: 
                   2018: =cut
                   2019: 
                   2020: ###############################################################
                   2021: ###############################################################
                   2022: 
                   2023: =pod
                   2024: 
1.1075.2.56  raeburn  2025: =over 4
                   2026: 
1.648     raeburn  2027: =item * &csv_translate($text) 
1.37      matthew  2028: 
1.185     www      2029: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2030: format.
                   2031: 
                   2032: =cut
                   2033: 
1.180     matthew  2034: ###############################################################
                   2035: ###############################################################
1.37      matthew  2036: sub csv_translate {
                   2037:     my $text = shift;
                   2038:     $text =~ s/\"/\"\"/g;
1.209     albertel 2039:     $text =~ s/\n/ /g;
1.37      matthew  2040:     return $text;
                   2041: }
1.180     matthew  2042: 
                   2043: ###############################################################
                   2044: ###############################################################
                   2045: 
                   2046: =pod
                   2047: 
1.648     raeburn  2048: =item * &define_excel_formats()
1.180     matthew  2049: 
                   2050: Define some commonly used Excel cell formats.
                   2051: 
                   2052: Currently supported formats:
                   2053: 
                   2054: =over 4
                   2055: 
                   2056: =item header
                   2057: 
                   2058: =item bold
                   2059: 
                   2060: =item h1
                   2061: 
                   2062: =item h2
                   2063: 
                   2064: =item h3
                   2065: 
1.256     matthew  2066: =item h4
                   2067: 
                   2068: =item i
                   2069: 
1.180     matthew  2070: =item date
                   2071: 
                   2072: =back
                   2073: 
                   2074: Inputs: $workbook
                   2075: 
                   2076: Returns: $format, a hash reference.
                   2077: 
1.1057    foxr     2078: 
1.180     matthew  2079: =cut
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
                   2083: sub define_excel_formats {
                   2084:     my ($workbook) = @_;
                   2085:     my $format;
                   2086:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2087:                                                 bottom    => 1,
                   2088:                                                 align     => 'center');
                   2089:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2090:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2091:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2092:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2093:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2094:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2095:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2096:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2097:     return $format;
                   2098: }
                   2099: 
                   2100: ###############################################################
                   2101: ###############################################################
1.113     bowersj2 2102: 
                   2103: =pod
                   2104: 
1.648     raeburn  2105: =item * &create_workbook()
1.255     matthew  2106: 
                   2107: Create an Excel worksheet.  If it fails, output message on the
                   2108: request object and return undefs.
                   2109: 
                   2110: Inputs: Apache request object
                   2111: 
                   2112: Returns (undef) on failure, 
                   2113:     Excel worksheet object, scalar with filename, and formats 
                   2114:     from &Apache::loncommon::define_excel_formats on success
                   2115: 
                   2116: =cut
                   2117: 
                   2118: ###############################################################
                   2119: ###############################################################
                   2120: sub create_workbook {
                   2121:     my ($r) = @_;
                   2122:         #
                   2123:     # Create the excel spreadsheet
                   2124:     my $filename = '/prtspool/'.
1.258     albertel 2125:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2126:         time.'_'.rand(1000000000).'.xls';
                   2127:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2128:     if (! defined($workbook)) {
                   2129:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2130:         $r->print(
                   2131:             '<p class="LC_error">'
                   2132:            .&mt('Problems occurred in creating the new Excel file.')
                   2133:            .' '.&mt('This error has been logged.')
                   2134:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2135:            .'</p>'
                   2136:         );
1.255     matthew  2137:         return (undef);
                   2138:     }
                   2139:     #
1.1014    foxr     2140:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2141:     #
                   2142:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2143:     return ($workbook,$filename,$format);
                   2144: }
                   2145: 
                   2146: ###############################################################
                   2147: ###############################################################
                   2148: 
                   2149: =pod
                   2150: 
1.648     raeburn  2151: =item * &create_text_file()
1.113     bowersj2 2152: 
1.542     raeburn  2153: Create a file to write to and eventually make available to the user.
1.256     matthew  2154: If file creation fails, outputs an error message on the request object and 
                   2155: return undefs.
1.113     bowersj2 2156: 
1.256     matthew  2157: Inputs: Apache request object, and file suffix
1.113     bowersj2 2158: 
1.256     matthew  2159: Returns (undef) on failure, 
                   2160:     Filehandle and filename on success.
1.113     bowersj2 2161: 
                   2162: =cut
                   2163: 
1.256     matthew  2164: ###############################################################
                   2165: ###############################################################
                   2166: sub create_text_file {
                   2167:     my ($r,$suffix) = @_;
                   2168:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2169:     my $fh;
                   2170:     my $filename = '/prtspool/'.
1.258     albertel 2171:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2172:         time.'_'.rand(1000000000).'.'.$suffix;
                   2173:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2174:     if (! defined($fh)) {
                   2175:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2176:         $r->print(
                   2177:             '<p class="LC_error">'
                   2178:            .&mt('Problems occurred in creating the output file.')
                   2179:            .' '.&mt('This error has been logged.')
                   2180:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2181:            .'</p>'
                   2182:         );
1.113     bowersj2 2183:     }
1.256     matthew  2184:     return ($fh,$filename)
1.113     bowersj2 2185: }
                   2186: 
                   2187: 
1.256     matthew  2188: =pod 
1.113     bowersj2 2189: 
                   2190: =back
                   2191: 
                   2192: =cut
1.37      matthew  2193: 
                   2194: ###############################################################
1.33      matthew  2195: ##        Home server <option> list generating code          ##
                   2196: ###############################################################
1.35      matthew  2197: 
1.169     www      2198: # ------------------------------------------
                   2199: 
                   2200: sub domain_select {
                   2201:     my ($name,$value,$multiple)=@_;
                   2202:     my %domains=map { 
1.514     albertel 2203: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2204:     } &Apache::lonnet::all_domains();
1.169     www      2205:     if ($multiple) {
                   2206: 	$domains{''}=&mt('Any domain');
1.550     albertel 2207: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2208: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2209:     } else {
1.550     albertel 2210: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2211: 	return &select_form($name,$value,\%domains);
1.169     www      2212:     }
                   2213: }
                   2214: 
1.282     albertel 2215: #-------------------------------------------
                   2216: 
                   2217: =pod
                   2218: 
1.519     raeburn  2219: =head1 Routines for form select boxes
                   2220: 
                   2221: =over 4
                   2222: 
1.648     raeburn  2223: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2224: 
                   2225: Returns a string containing a <select> element int multiple mode
                   2226: 
                   2227: 
                   2228: Args:
                   2229:   $name - name of the <select> element
1.506     raeburn  2230:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2231:   $size - number of rows long the select element is
1.283     albertel 2232:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2233:           (shown text should already have been &mt())
1.506     raeburn  2234:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2235: 
1.282     albertel 2236: =cut
                   2237: 
                   2238: #-------------------------------------------
1.169     www      2239: sub multiple_select_form {
1.284     albertel 2240:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2241:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2242:     my $output='';
1.191     matthew  2243:     if (! defined($size)) {
                   2244:         $size = 4;
1.283     albertel 2245:         if (scalar(keys(%$hash))<4) {
                   2246:             $size = scalar(keys(%$hash));
1.191     matthew  2247:         }
                   2248:     }
1.734     bisitz   2249:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2250:     my @order;
1.506     raeburn  2251:     if (ref($order) eq 'ARRAY')  {
                   2252:         @order = @{$order};
                   2253:     } else {
                   2254:         @order = sort(keys(%$hash));
1.501     banghart 2255:     }
                   2256:     if (exists($$hash{'select_form_order'})) {
                   2257:         @order = @{$$hash{'select_form_order'}};
                   2258:     }
                   2259:         
1.284     albertel 2260:     foreach my $key (@order) {
1.356     albertel 2261:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2262:         $output.='selected="selected" ' if ($selected{$key});
                   2263:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2264:     }
                   2265:     $output.="</select>\n";
                   2266:     return $output;
                   2267: }
                   2268: 
1.88      www      2269: #-------------------------------------------
                   2270: 
                   2271: =pod
                   2272: 
1.1075.2.115  raeburn  2273: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2274: 
                   2275: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2276: allow a user to select options from a ref to a hash containing:
                   2277: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2278: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2279: An optional arg -- $readonly -- if true will cause the select form
                   2280: to be disabled, e.g., for the case where an instructor has a section-
                   2281: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2282: 
1.88      www      2283: See lonrights.pm for an example invocation and use.
                   2284: 
                   2285: =cut
                   2286: 
                   2287: #-------------------------------------------
                   2288: sub select_form {
1.1075.2.115  raeburn  2289:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2290:     return unless (ref($hashref) eq 'HASH');
                   2291:     if ($onchange) {
                   2292:         $onchange = ' onchange="'.$onchange.'"';
                   2293:     }
1.1075.2.129  raeburn  2294:     my $disabled;
                   2295:     if ($readonly) {
                   2296:         $disabled = ' disabled="disabled"';
                   2297:     }
                   2298:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2299:     my @keys;
1.970     raeburn  2300:     if (exists($hashref->{'select_form_order'})) {
                   2301: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2302:     } else {
1.970     raeburn  2303: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2304:     }
1.356     albertel 2305:     foreach my $key (@keys) {
                   2306:         $selectform.=
                   2307: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2308:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2309:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2310:     }
                   2311:     $selectform.="</select>";
                   2312:     return $selectform;
                   2313: }
                   2314: 
1.475     www      2315: # For display filters
                   2316: 
                   2317: sub display_filter {
1.1074    raeburn  2318:     my ($context) = @_;
1.475     www      2319:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2320:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2321:     my $phraseinput = 'hidden';
                   2322:     my $includeinput = 'hidden';
                   2323:     my ($checked,$includetypestext);
                   2324:     if ($env{'form.displayfilter'} eq 'containing') {
                   2325:         $phraseinput = 'text'; 
                   2326:         if ($context eq 'parmslog') {
                   2327:             $includeinput = 'checkbox';
                   2328:             if ($env{'form.includetypes'}) {
                   2329:                 $checked = ' checked="checked"';
                   2330:             }
                   2331:             $includetypestext = &mt('Include parameter types');
                   2332:         }
                   2333:     } else {
                   2334:         $includetypestext = '&nbsp;';
                   2335:     }
                   2336:     my ($additional,$secondid,$thirdid);
                   2337:     if ($context eq 'parmslog') {
                   2338:         $additional = 
                   2339:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2340:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2341:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2342:             '</label>';
                   2343:         $secondid = 'includetypes';
                   2344:         $thirdid = 'includetypestext';
                   2345:     }
                   2346:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2347:                                                     '$secondid','$thirdid')";
                   2348:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2349: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2350: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2351: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2352:            &mt('Filter: [_1]',
1.477     www      2353: 	   &select_form($env{'form.displayfilter'},
                   2354: 			'displayfilter',
1.970     raeburn  2355: 			{'currentfolder' => 'Current folder/page',
1.477     www      2356: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2357: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2358: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2359:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2360:                          '" />'.$additional;
                   2361: }
                   2362: 
                   2363: sub display_filter_js {
                   2364:     my $includetext = &mt('Include parameter types');
                   2365:     return <<"ENDJS";
                   2366:   
                   2367: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2368:     var firstType = 'hidden';
                   2369:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2370:         firstType = 'text';
                   2371:     }
                   2372:     firstObject = document.getElementById(firstid);
                   2373:     if (typeof(firstObject) == 'object') {
                   2374:         if (firstObject.type != firstType) {
                   2375:             changeInputType(firstObject,firstType);
                   2376:         }
                   2377:     }
                   2378:     if (context == 'parmslog') {
                   2379:         var secondType = 'hidden';
                   2380:         if (firstType == 'text') {
                   2381:             secondType = 'checkbox';
                   2382:         }
                   2383:         secondObject = document.getElementById(secondid);  
                   2384:         if (typeof(secondObject) == 'object') {
                   2385:             if (secondObject.type != secondType) {
                   2386:                 changeInputType(secondObject,secondType);
                   2387:             }
                   2388:         }
                   2389:         var textItem = document.getElementById(thirdid);
                   2390:         var currtext = textItem.innerHTML;
                   2391:         var newtext;
                   2392:         if (firstType == 'text') {
                   2393:             newtext = '$includetext';
                   2394:         } else {
                   2395:             newtext = '&nbsp;';
                   2396:         }
                   2397:         if (currtext != newtext) {
                   2398:             textItem.innerHTML = newtext;
                   2399:         }
                   2400:     }
                   2401:     return;
                   2402: }
                   2403: 
                   2404: function changeInputType(oldObject,newType) {
                   2405:     var newObject = document.createElement('input');
                   2406:     newObject.type = newType;
                   2407:     if (oldObject.size) {
                   2408:         newObject.size = oldObject.size;
                   2409:     }
                   2410:     if (oldObject.value) {
                   2411:         newObject.value = oldObject.value;
                   2412:     }
                   2413:     if (oldObject.name) {
                   2414:         newObject.name = oldObject.name;
                   2415:     }
                   2416:     if (oldObject.id) {
                   2417:         newObject.id = oldObject.id;
                   2418:     }
                   2419:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2420:     return;
                   2421: }
                   2422: 
                   2423: ENDJS
1.475     www      2424: }
                   2425: 
1.167     www      2426: sub gradeleveldescription {
                   2427:     my $gradelevel=shift;
                   2428:     my %gradelevels=(0 => 'Not specified',
                   2429: 		     1 => 'Grade 1',
                   2430: 		     2 => 'Grade 2',
                   2431: 		     3 => 'Grade 3',
                   2432: 		     4 => 'Grade 4',
                   2433: 		     5 => 'Grade 5',
                   2434: 		     6 => 'Grade 6',
                   2435: 		     7 => 'Grade 7',
                   2436: 		     8 => 'Grade 8',
                   2437: 		     9 => 'Grade 9',
                   2438: 		     10 => 'Grade 10',
                   2439: 		     11 => 'Grade 11',
                   2440: 		     12 => 'Grade 12',
                   2441: 		     13 => 'Grade 13',
                   2442: 		     14 => '100 Level',
                   2443: 		     15 => '200 Level',
                   2444: 		     16 => '300 Level',
                   2445: 		     17 => '400 Level',
                   2446: 		     18 => 'Graduate Level');
                   2447:     return &mt($gradelevels{$gradelevel});
                   2448: }
                   2449: 
1.163     www      2450: sub select_level_form {
                   2451:     my ($deflevel,$name)=@_;
                   2452:     unless ($deflevel) { $deflevel=0; }
1.167     www      2453:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2454:     for (my $i=0; $i<=18; $i++) {
                   2455:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2456:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2457:                 ">".&gradeleveldescription($i)."</option>\n";
                   2458:     }
                   2459:     $selectform.="</select>";
                   2460:     return $selectform;
1.163     www      2461: }
1.167     www      2462: 
1.35      matthew  2463: #-------------------------------------------
                   2464: 
1.45      matthew  2465: =pod
                   2466: 
1.1075.2.115  raeburn  2467: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2468: 
                   2469: Returns a string containing a <select name='$name' size='1'> form to 
                   2470: allow a user to select the domain to preform an operation in.  
                   2471: See loncreateuser.pm for an example invocation and use.
                   2472: 
1.90      www      2473: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2474: selected");
                   2475: 
1.743     raeburn  2476: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2477: 
1.910     raeburn  2478: 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.
                   2479: 
1.1075.2.36  raeburn  2480: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2481: 
1.1075.2.115  raeburn  2482: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2483: 
                   2484: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2485: 
1.35      matthew  2486: =cut
                   2487: 
                   2488: #-------------------------------------------
1.34      matthew  2489: sub select_dom_form {
1.1075.2.115  raeburn  2490:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2491:     if ($onchange) {
1.874     raeburn  2492:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2493:     }
1.1075.2.115  raeburn  2494:     if ($disabled) {
                   2495:         $disabled = ' disabled="disabled"';
                   2496:     }
1.1075.2.36  raeburn  2497:     my (@domains,%exclude);
1.910     raeburn  2498:     if (ref($incdoms) eq 'ARRAY') {
                   2499:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2500:     } else {
                   2501:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2502:     }
1.90      www      2503:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2504:     if (ref($excdoms) eq 'ARRAY') {
                   2505:         map { $exclude{$_} = 1; } @{$excdoms};
                   2506:     }
1.1075.2.115  raeburn  2507:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2508:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2509:         next if ($exclude{$dom});
1.356     albertel 2510:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2511:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2512:         if ($showdomdesc) {
                   2513:             if ($dom ne '') {
                   2514:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2515:                 if ($domdesc ne '') {
                   2516:                     $selectdomain .= ' ('.$domdesc.')';
                   2517:                 }
                   2518:             } 
                   2519:         }
                   2520:         $selectdomain .= "</option>\n";
1.34      matthew  2521:     }
                   2522:     $selectdomain.="</select>";
                   2523:     return $selectdomain;
                   2524: }
                   2525: 
1.35      matthew  2526: #-------------------------------------------
                   2527: 
1.45      matthew  2528: =pod
                   2529: 
1.648     raeburn  2530: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2531: 
1.586     raeburn  2532: input: 4 arguments (two required, two optional) - 
                   2533:     $domain - domain of new user
                   2534:     $name - name of form element
                   2535:     $default - Value of 'default' causes a default item to be first 
                   2536:                             option, and selected by default. 
                   2537:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2538:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2539: output: returns 2 items: 
1.586     raeburn  2540: (a) form element which contains either:
                   2541:    (i) <select name="$name">
                   2542:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2543:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2544:        </select>
                   2545:        form item if there are multiple library servers in $domain, or
                   2546:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2547:        if there is only one library server in $domain.
                   2548: 
                   2549: (b) number of library servers found.
                   2550: 
                   2551: See loncreateuser.pm for example of use.
1.35      matthew  2552: 
                   2553: =cut
                   2554: 
                   2555: #-------------------------------------------
1.586     raeburn  2556: sub home_server_form_item {
                   2557:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2558:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2559:     my $result;
                   2560:     my $numlib = keys(%servers);
                   2561:     if ($numlib > 1) {
                   2562:         $result .= '<select name="'.$name.'" />'."\n";
                   2563:         if ($default) {
1.804     bisitz   2564:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2565:                        '</option>'."\n";
                   2566:         }
                   2567:         foreach my $hostid (sort(keys(%servers))) {
                   2568:             $result.= '<option value="'.$hostid.'">'.
                   2569: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2570:         }
                   2571:         $result .= '</select>'."\n";
                   2572:     } elsif ($numlib == 1) {
                   2573:         my $hostid;
                   2574:         foreach my $item (keys(%servers)) {
                   2575:             $hostid = $item;
                   2576:         }
                   2577:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2578:                    $hostid.'" />';
                   2579:                    if (!$hide) {
                   2580:                        $result .= $hostid.' '.$servers{$hostid};
                   2581:                    }
                   2582:                    $result .= "\n";
                   2583:     } elsif ($default) {
                   2584:         $result .= '<input type="hidden" name="'.$name.
                   2585:                    '" value="default" />';
                   2586:                    if (!$hide) {
                   2587:                        $result .= &mt('default');
                   2588:                    }
                   2589:                    $result .= "\n";
1.33      matthew  2590:     }
1.586     raeburn  2591:     return ($result,$numlib);
1.33      matthew  2592: }
1.112     bowersj2 2593: 
                   2594: =pod
                   2595: 
1.534     albertel 2596: =back 
                   2597: 
1.112     bowersj2 2598: =cut
1.87      matthew  2599: 
                   2600: ###############################################################
1.112     bowersj2 2601: ##                  Decoding User Agent                      ##
1.87      matthew  2602: ###############################################################
                   2603: 
                   2604: =pod
                   2605: 
1.112     bowersj2 2606: =head1 Decoding the User Agent
                   2607: 
                   2608: =over 4
                   2609: 
                   2610: =item * &decode_user_agent()
1.87      matthew  2611: 
                   2612: Inputs: $r
                   2613: 
                   2614: Outputs:
                   2615: 
                   2616: =over 4
                   2617: 
1.112     bowersj2 2618: =item * $httpbrowser
1.87      matthew  2619: 
1.112     bowersj2 2620: =item * $clientbrowser
1.87      matthew  2621: 
1.112     bowersj2 2622: =item * $clientversion
1.87      matthew  2623: 
1.112     bowersj2 2624: =item * $clientmathml
1.87      matthew  2625: 
1.112     bowersj2 2626: =item * $clientunicode
1.87      matthew  2627: 
1.112     bowersj2 2628: =item * $clientos
1.87      matthew  2629: 
1.1075.2.42  raeburn  2630: =item * $clientmobile
                   2631: 
                   2632: =item * $clientinfo
                   2633: 
1.1075.2.77  raeburn  2634: =item * $clientosversion
                   2635: 
1.87      matthew  2636: =back
                   2637: 
1.157     matthew  2638: =back 
                   2639: 
1.87      matthew  2640: =cut
                   2641: 
                   2642: ###############################################################
                   2643: ###############################################################
                   2644: sub decode_user_agent {
1.247     albertel 2645:     my ($r)=@_;
1.87      matthew  2646:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2647:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2648:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2649:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2650:     my $clientbrowser='unknown';
                   2651:     my $clientversion='0';
                   2652:     my $clientmathml='';
                   2653:     my $clientunicode='0';
1.1075.2.42  raeburn  2654:     my $clientmobile=0;
1.1075.2.77  raeburn  2655:     my $clientosversion='';
1.87      matthew  2656:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2657:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2658: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2659: 	    $clientbrowser=$bname;
                   2660:             $httpbrowser=~/$vreg/i;
                   2661: 	    $clientversion=$1;
                   2662:             $clientmathml=($clientversion>=$minv);
                   2663:             $clientunicode=($clientversion>=$univ);
                   2664: 	}
                   2665:     }
                   2666:     my $clientos='unknown';
1.1075.2.42  raeburn  2667:     my $clientinfo;
1.87      matthew  2668:     if (($httpbrowser=~/linux/i) ||
                   2669:         ($httpbrowser=~/unix/i) ||
                   2670:         ($httpbrowser=~/ux/i) ||
                   2671:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2672:     if (($httpbrowser=~/vax/i) ||
                   2673:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2674:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2675:     if (($httpbrowser=~/mac/i) ||
                   2676:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2677:     if ($httpbrowser=~/win/i) {
                   2678:         $clientos='win';
                   2679:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2680:             $clientosversion = $1;
                   2681:         }
                   2682:     }
1.87      matthew  2683:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2684:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2685:         $clientmobile=lc($1);
                   2686:     }
                   2687:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2688:         $clientinfo = 'firefox-'.$1;
                   2689:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2690:         $clientinfo = 'chromeframe-'.$1;
                   2691:     }
1.87      matthew  2692:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2693:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2694:             $clientosversion);
1.87      matthew  2695: }
                   2696: 
1.32      matthew  2697: ###############################################################
                   2698: ##    Authentication changing form generation subroutines    ##
                   2699: ###############################################################
                   2700: ##
                   2701: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2702: ## hash, and have reasonable default values.
                   2703: ##
                   2704: ##    formname = the name given in the <form> tag.
1.35      matthew  2705: #-------------------------------------------
                   2706: 
1.45      matthew  2707: =pod
                   2708: 
1.112     bowersj2 2709: =head1 Authentication Routines
                   2710: 
                   2711: =over 4
                   2712: 
1.648     raeburn  2713: =item * &authform_xxxxxx()
1.35      matthew  2714: 
                   2715: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2716: handle some of the conveniences required for authentication forms.  
                   2717: This is not an optimal method, but it works.  
                   2718: 
                   2719: =over 4
                   2720: 
1.112     bowersj2 2721: =item * authform_header
1.35      matthew  2722: 
1.112     bowersj2 2723: =item * authform_authorwarning
1.35      matthew  2724: 
1.112     bowersj2 2725: =item * authform_nochange
1.35      matthew  2726: 
1.112     bowersj2 2727: =item * authform_kerberos
1.35      matthew  2728: 
1.112     bowersj2 2729: =item * authform_internal
1.35      matthew  2730: 
1.112     bowersj2 2731: =item * authform_filesystem
1.35      matthew  2732: 
1.1075.2.161.  .17(raeb 2733:-23): =item * authform_lti
                   2734:-23): 
1.35      matthew  2735: =back
                   2736: 
1.648     raeburn  2737: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2738: 
1.35      matthew  2739: =cut
                   2740: 
                   2741: #-------------------------------------------
1.32      matthew  2742: sub authform_header{  
                   2743:     my %in = (
                   2744:         formname => 'cu',
1.80      albertel 2745:         kerb_def_dom => '',
1.32      matthew  2746:         @_,
                   2747:     );
                   2748:     $in{'formname'} = 'document.' . $in{'formname'};
                   2749:     my $result='';
1.80      albertel 2750: 
                   2751: #---------------------------------------------- Code for upper case translation
                   2752:     my $Javascript_toUpperCase;
                   2753:     unless ($in{kerb_def_dom}) {
                   2754:         $Javascript_toUpperCase =<<"END";
                   2755:         switch (choice) {
                   2756:            case 'krb': currentform.elements[choicearg].value =
                   2757:                currentform.elements[choicearg].value.toUpperCase();
                   2758:                break;
                   2759:            default:
                   2760:         }
                   2761: END
                   2762:     } else {
                   2763:         $Javascript_toUpperCase = "";
                   2764:     }
                   2765: 
1.165     raeburn  2766:     my $radioval = "'nochange'";
1.591     raeburn  2767:     if (defined($in{'curr_authtype'})) {
                   2768:         if ($in{'curr_authtype'} ne '') {
                   2769:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2770:         }
1.174     matthew  2771:     }
1.165     raeburn  2772:     my $argfield = 'null';
1.591     raeburn  2773:     if (defined($in{'mode'})) {
1.165     raeburn  2774:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2775:             if (defined($in{'curr_autharg'})) {
                   2776:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2777:                     $argfield = "'$in{'curr_autharg'}'";
                   2778:                 }
                   2779:             }
                   2780:         }
                   2781:     }
                   2782: 
1.32      matthew  2783:     $result.=<<"END";
                   2784: var current = new Object();
1.165     raeburn  2785: current.radiovalue = $radioval;
                   2786: current.argfield = $argfield;
1.32      matthew  2787: 
                   2788: function changed_radio(choice,currentform) {
                   2789:     var choicearg = choice + 'arg';
                   2790:     // If a radio button in changed, we need to change the argfield
                   2791:     if (current.radiovalue != choice) {
                   2792:         current.radiovalue = choice;
                   2793:         if (current.argfield != null) {
                   2794:             currentform.elements[current.argfield].value = '';
                   2795:         }
                   2796:         if (choice == 'nochange') {
                   2797:             current.argfield = null;
                   2798:         } else {
                   2799:             current.argfield = choicearg;
                   2800:             switch(choice) {
                   2801:                 case 'krb': 
                   2802:                     currentform.elements[current.argfield].value = 
                   2803:                         "$in{'kerb_def_dom'}";
                   2804:                 break;
                   2805:               default:
                   2806:                 break;
                   2807:             }
                   2808:         }
                   2809:     }
                   2810:     return;
                   2811: }
1.22      www      2812: 
1.32      matthew  2813: function changed_text(choice,currentform) {
                   2814:     var choicearg = choice + 'arg';
                   2815:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2816:         $Javascript_toUpperCase
1.32      matthew  2817:         // clear old field
                   2818:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2819:             currentform.elements[current.argfield].value = '';
                   2820:         }
                   2821:         current.argfield = choicearg;
                   2822:     }
                   2823:     set_auth_radio_buttons(choice,currentform);
                   2824:     return;
1.20      www      2825: }
1.32      matthew  2826: 
                   2827: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2828:     var numauthchoices = currentform.login.length;
                   2829:     if (typeof numauthchoices  == "undefined") {
                   2830:         return;
                   2831:     } 
1.32      matthew  2832:     var i=0;
1.986     raeburn  2833:     while (i < numauthchoices) {
1.32      matthew  2834:         if (currentform.login[i].value == newvalue) { break; }
                   2835:         i++;
                   2836:     }
1.986     raeburn  2837:     if (i == numauthchoices) {
1.32      matthew  2838:         return;
                   2839:     }
                   2840:     current.radiovalue = newvalue;
                   2841:     currentform.login[i].checked = true;
                   2842:     return;
                   2843: }
                   2844: END
                   2845:     return $result;
                   2846: }
                   2847: 
1.1075.2.20  raeburn  2848: sub authform_authorwarning {
1.32      matthew  2849:     my $result='';
1.144     matthew  2850:     $result='<i>'.
                   2851:         &mt('As a general rule, only authors or co-authors should be '.
                   2852:             'filesystem authenticated '.
                   2853:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2854:     return $result;
                   2855: }
                   2856: 
1.1075.2.20  raeburn  2857: sub authform_nochange {
1.32      matthew  2858:     my %in = (
                   2859:               formname => 'document.cu',
                   2860:               kerb_def_dom => 'MSU.EDU',
                   2861:               @_,
                   2862:           );
1.1075.2.20  raeburn  2863:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2864:     my $result;
1.1075.2.20  raeburn  2865:     if (!$authnum) {
                   2866:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2867:     } else {
                   2868:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2869:                   '<input type="radio" name="login" value="nochange" '.
                   2870:                   'checked="checked" onclick="'.
1.281     albertel 2871:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2872: 	    '</label>';
1.586     raeburn  2873:     }
1.32      matthew  2874:     return $result;
                   2875: }
                   2876: 
1.591     raeburn  2877: sub authform_kerberos {
1.32      matthew  2878:     my %in = (
                   2879:               formname => 'document.cu',
                   2880:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2881:               kerb_def_auth => 'krb4',
1.32      matthew  2882:               @_,
                   2883:               );
1.586     raeburn  2884:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2885:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2886:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2887:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2888:        $check5 = ' checked="checked"';
1.80      albertel 2889:     } else {
1.772     bisitz   2890:        $check4 = ' checked="checked"';
1.80      albertel 2891:     }
1.1075.2.117  raeburn  2892:     if ($in{'readonly'}) {
                   2893:         $disabled = ' disabled="disabled"';
                   2894:     }
1.165     raeburn  2895:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2896:     if (defined($in{'curr_authtype'})) {
                   2897:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2898:             $krbcheck = ' checked="checked"';
1.623     raeburn  2899:             if (defined($in{'mode'})) {
                   2900:                 if ($in{'mode'} eq 'modifyuser') {
                   2901:                     $krbcheck = '';
                   2902:                 }
                   2903:             }
1.591     raeburn  2904:             if (defined($in{'curr_kerb_ver'})) {
                   2905:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2906:                     $check5 = ' checked="checked"';
1.591     raeburn  2907:                     $check4 = '';
                   2908:                 } else {
1.772     bisitz   2909:                     $check4 = ' checked="checked"';
1.591     raeburn  2910:                     $check5 = '';
                   2911:                 }
1.586     raeburn  2912:             }
1.591     raeburn  2913:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2914:                 $krbarg = $in{'curr_autharg'};
                   2915:             }
1.586     raeburn  2916:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2917:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2918:                     $result = 
                   2919:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2920:         $in{'curr_autharg'},$krbver);
                   2921:                 } else {
                   2922:                     $result =
                   2923:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2924:                 }
                   2925:                 return $result; 
                   2926:             }
                   2927:         }
                   2928:     } else {
                   2929:         if ($authnum == 1) {
1.784     bisitz   2930:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2931:         }
                   2932:     }
1.586     raeburn  2933:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2934:         return;
1.587     raeburn  2935:     } elsif ($authtype eq '') {
1.591     raeburn  2936:         if (defined($in{'mode'})) {
1.587     raeburn  2937:             if ($in{'mode'} eq 'modifycourse') {
                   2938:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2939:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2940:                 }
                   2941:             }
                   2942:         }
1.586     raeburn  2943:     }
                   2944:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2945:     if ($authtype eq '') {
                   2946:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2947:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2948:                     $krbcheck.$disabled.' />';
1.586     raeburn  2949:     }
                   2950:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2951:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2952:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2953:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2954:          $in{'curr_authtype'} eq 'krb4')) {
                   2955:         $result .= &mt
1.144     matthew  2956:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2957:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2958:          '<label>'.$authtype,
1.281     albertel 2959:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2960:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2961:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2962:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2963:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2964: 	 '</label>');
1.586     raeburn  2965:     } elsif ($can_assign{'krb4'}) {
                   2966:         $result .= &mt
                   2967:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2968:          '[_3] Version 4 [_4]',
                   2969:          '<label>'.$authtype,
                   2970:          '</label><input type="text" size="10" name="krbarg" '.
                   2971:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2972:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2973:          '<label><input type="hidden" name="krbver" value="4" />',
                   2974:          '</label>');
                   2975:     } elsif ($can_assign{'krb5'}) {
                   2976:         $result .= &mt
                   2977:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2978:          '[_3] Version 5 [_4]',
                   2979:          '<label>'.$authtype,
                   2980:          '</label><input type="text" size="10" name="krbarg" '.
                   2981:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2982:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2983:          '<label><input type="hidden" name="krbver" value="5" />',
                   2984:          '</label>');
                   2985:     }
1.32      matthew  2986:     return $result;
                   2987: }
                   2988: 
1.1075.2.20  raeburn  2989: sub authform_internal {
1.586     raeburn  2990:     my %in = (
1.32      matthew  2991:                 formname => 'document.cu',
                   2992:                 kerb_def_dom => 'MSU.EDU',
                   2993:                 @_,
                   2994:                 );
1.1075.2.117  raeburn  2995:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2996:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2997:     if ($in{'readonly'}) {
                   2998:         $disabled = ' disabled="disabled"';
                   2999:     }
1.591     raeburn  3000:     if (defined($in{'curr_authtype'})) {
                   3001:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3002:             if ($can_assign{'int'}) {
1.772     bisitz   3003:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3004:                 if (defined($in{'mode'})) {
                   3005:                     if ($in{'mode'} eq 'modifyuser') {
                   3006:                         $intcheck = '';
                   3007:                     }
                   3008:                 }
1.591     raeburn  3009:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3010:                     $intarg = $in{'curr_autharg'};
                   3011:                 }
                   3012:             } else {
                   3013:                 $result = &mt('Currently internally authenticated.');
                   3014:                 return $result;
1.165     raeburn  3015:             }
                   3016:         }
1.586     raeburn  3017:     } else {
                   3018:         if ($authnum == 1) {
1.784     bisitz   3019:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3020:         }
                   3021:     }
                   3022:     if (!$can_assign{'int'}) {
                   3023:         return;
1.587     raeburn  3024:     } elsif ($authtype eq '') {
1.591     raeburn  3025:         if (defined($in{'mode'})) {
1.587     raeburn  3026:             if ($in{'mode'} eq 'modifycourse') {
                   3027:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3028:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3029:                 }
                   3030:             }
                   3031:         }
1.165     raeburn  3032:     }
1.586     raeburn  3033:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3034:     if ($authtype eq '') {
                   3035:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3036:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3037:     }
1.605     bisitz   3038:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3039:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3040:     $result = &mt
1.144     matthew  3041:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3042:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3043:     $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  3044:     return $result;
                   3045: }
                   3046: 
1.1075.2.20  raeburn  3047: sub authform_local {
1.32      matthew  3048:     my %in = (
                   3049:               formname => 'document.cu',
                   3050:               kerb_def_dom => 'MSU.EDU',
                   3051:               @_,
                   3052:               );
1.1075.2.117  raeburn  3053:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3054:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3055:     if ($in{'readonly'}) {
                   3056:         $disabled = ' disabled="disabled"';
                   3057:     }
1.591     raeburn  3058:     if (defined($in{'curr_authtype'})) {
                   3059:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3060:             if ($can_assign{'loc'}) {
1.772     bisitz   3061:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3062:                 if (defined($in{'mode'})) {
                   3063:                     if ($in{'mode'} eq 'modifyuser') {
                   3064:                         $loccheck = '';
                   3065:                     }
                   3066:                 }
1.591     raeburn  3067:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3068:                     $locarg = $in{'curr_autharg'};
                   3069:                 }
                   3070:             } else {
                   3071:                 $result = &mt('Currently using local (institutional) authentication.');
                   3072:                 return $result;
1.165     raeburn  3073:             }
                   3074:         }
1.586     raeburn  3075:     } else {
                   3076:         if ($authnum == 1) {
1.784     bisitz   3077:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3078:         }
                   3079:     }
                   3080:     if (!$can_assign{'loc'}) {
                   3081:         return;
1.587     raeburn  3082:     } elsif ($authtype eq '') {
1.591     raeburn  3083:         if (defined($in{'mode'})) {
1.587     raeburn  3084:             if ($in{'mode'} eq 'modifycourse') {
                   3085:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3086:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3087:                 }
                   3088:             }
                   3089:         }
1.165     raeburn  3090:     }
1.586     raeburn  3091:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3092:     if ($authtype eq '') {
                   3093:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3094:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3095:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3096:     }
                   3097:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3098:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3099:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3100:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3101:     return $result;
                   3102: }
                   3103: 
1.1075.2.20  raeburn  3104: sub authform_filesystem {
1.32      matthew  3105:     my %in = (
                   3106:               formname => 'document.cu',
                   3107:               kerb_def_dom => 'MSU.EDU',
                   3108:               @_,
                   3109:               );
1.1075.2.117  raeburn  3110:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3111:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3112:     if ($in{'readonly'}) {
                   3113:         $disabled = ' disabled="disabled"';
                   3114:     }
1.591     raeburn  3115:     if (defined($in{'curr_authtype'})) {
                   3116:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3117:             if ($can_assign{'fsys'}) {
1.772     bisitz   3118:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3119:                 if (defined($in{'mode'})) {
                   3120:                     if ($in{'mode'} eq 'modifyuser') {
                   3121:                         $fsyscheck = '';
                   3122:                     }
                   3123:                 }
1.586     raeburn  3124:             } else {
                   3125:                 $result = &mt('Currently Filesystem Authenticated.');
                   3126:                 return $result;
                   3127:             }           
                   3128:         }
                   3129:     } else {
                   3130:         if ($authnum == 1) {
1.784     bisitz   3131:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3132:         }
                   3133:     }
                   3134:     if (!$can_assign{'fsys'}) {
                   3135:         return;
1.587     raeburn  3136:     } elsif ($authtype eq '') {
1.591     raeburn  3137:         if (defined($in{'mode'})) {
1.587     raeburn  3138:             if ($in{'mode'} eq 'modifycourse') {
                   3139:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3140:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3141:                 }
                   3142:             }
                   3143:         }
1.586     raeburn  3144:     }
                   3145:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3146:     if ($authtype eq '') {
                   3147:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3148:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3149:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3150:     }
1.1075.2.158  raeburn  3151:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3152:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3153:     $result = &mt
1.144     matthew  3154:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3155:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3156:     return $result;
                   3157: }
                   3158: 
1.1075.2.161.  .17(raeb 3159:-23): sub authform_lti {
                   3160:-23):     my %in = (
                   3161:-23):               formname => 'document.cu',
                   3162:-23):               kerb_def_dom => 'MSU.EDU',
                   3163:-23):               @_,
                   3164:-23):               );
                   3165:-23):     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3166:-23):     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3167:-23):     if ($in{'readonly'}) {
                   3168:-23):         $disabled = ' disabled="disabled"';
                   3169:-23):     }
                   3170:-23):     if (defined($in{'curr_authtype'})) {
                   3171:-23):         if ($in{'curr_authtype'} eq 'lti') {
                   3172:-23):             if ($can_assign{'lti'}) {
                   3173:-23):                 $lticheck = 'checked="checked" ';
                   3174:-23):                 if (defined($in{'mode'})) {
                   3175:-23):                     if ($in{'mode'} eq 'modifyuser') {
                   3176:-23):                         $lticheck = '';
                   3177:-23):                     }
                   3178:-23):                 }
                   3179:-23):             } else {
                   3180:-23):                 $result = &mt('Currently LTI Authenticated.');
                   3181:-23):                 return $result;
                   3182:-23):             }
                   3183:-23):         }
                   3184:-23):     } else {
                   3185:-23):         if ($authnum == 1) {
                   3186:-23):             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3187:-23):         }
                   3188:-23):     }
                   3189:-23):     if (!$can_assign{'lti'}) {
                   3190:-23):         return;
                   3191:-23):     } elsif ($authtype eq '') {
                   3192:-23):         if (defined($in{'mode'})) {
                   3193:-23):             if ($in{'mode'} eq 'modifycourse') {
                   3194:-23):                 if ($authnum == 1) {
                   3195:-23):                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3196:-23):                 }
                   3197:-23):             }
                   3198:-23):         }
                   3199:-23):     }
                   3200:-23):     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3201:-23):     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3202:-23):         $authtype = '<input type="radio" name="login" value="lti" '.
                   3203:-23):                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3204:-23):                     $jscall.'"'.$disabled.' />';
                   3205:-23):     }
                   3206:-23):     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3207:-23):     if ($authtype) {
                   3208:-23):         $result = &mt('[_1] LTI Authenticated',
                   3209:-23):                       '<label>'.$authtype.'</label>'.$autharg);
                   3210:-23):     } else {
                   3211:-23):         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3212:-23):                   $autharg;
                   3213:-23):     }
                   3214:-23):     return $result;
                   3215:-23): }
                   3216:-23): 
1.586     raeburn  3217: sub get_assignable_auth {
                   3218:     my ($dom) = @_;
                   3219:     if ($dom eq '') {
                   3220:         $dom = $env{'request.role.domain'};
                   3221:     }
                   3222:     my %can_assign = (
                   3223:                           krb4 => 1,
                   3224:                           krb5 => 1,
                   3225:                           int  => 1,
                   3226:                           loc  => 1,
                   3227:                      );
                   3228:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3229:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3230:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3231:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3232:             my $context;
                   3233:             if ($env{'request.role'} =~ /^au/) {
                   3234:                 $context = 'author';
1.1075.2.117  raeburn  3235:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3236:                 $context = 'domain';
                   3237:             } elsif ($env{'request.course.id'}) {
                   3238:                 $context = 'course';
                   3239:             }
                   3240:             if ($context) {
                   3241:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3242:                    %can_assign = %{$authhash->{$context}}; 
                   3243:                 }
                   3244:             }
                   3245:         }
                   3246:     }
                   3247:     my $authnum = 0;
                   3248:     foreach my $key (keys(%can_assign)) {
                   3249:         if ($can_assign{$key}) {
                   3250:             $authnum ++;
                   3251:         }
                   3252:     }
                   3253:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3254:         $authnum --;
                   3255:     }
                   3256:     return ($authnum,%can_assign);
                   3257: }
                   3258: 
1.1075.2.137  raeburn  3259: sub check_passwd_rules {
                   3260:     my ($domain,$plainpass) = @_;
                   3261:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3262:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3263:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3264:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3265:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3266:             if ($passwdconf{'min'} > $min) {
                   3267:                 $min = $passwdconf{'min'};
                   3268:             }
1.1075.2.137  raeburn  3269:         }
                   3270:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3271:             $max = $passwdconf{'max'};
                   3272:         }
                   3273:         @chars = @{$passwdconf{'chars'}};
                   3274:     }
                   3275:     if (($min) && (length($plainpass) < $min)) {
                   3276:         push(@brokerule,'min');
                   3277:     }
                   3278:     if (($max) && (length($plainpass) > $max)) {
                   3279:         push(@brokerule,'max');
                   3280:     }
                   3281:     if (@chars) {
                   3282:         my %rules;
                   3283:         map { $rules{$_} = 1; } @chars;
                   3284:         if ($rules{'uc'}) {
                   3285:             unless ($plainpass =~ /[A-Z]/) {
                   3286:                 push(@brokerule,'uc');
                   3287:             }
                   3288:         }
                   3289:         if ($rules{'lc'}) {
                   3290:             unless ($plainpass =~ /[a-z]/) {
                   3291:                 push(@brokerule,'lc');
                   3292:             }
                   3293:         }
                   3294:         if ($rules{'num'}) {
                   3295:             unless ($plainpass =~ /\d/) {
                   3296:                 push(@brokerule,'num');
                   3297:             }
                   3298:         }
                   3299:         if ($rules{'spec'}) {
                   3300:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3301:                 push(@brokerule,'spec');
                   3302:             }
                   3303:         }
                   3304:     }
                   3305:     if (@brokerule) {
                   3306:         my %rulenames = &Apache::lonlocal::texthash(
                   3307:             uc   => 'At least one upper case letter',
                   3308:             lc   => 'At least one lower case letter',
                   3309:             num  => 'At least one number',
                   3310:             spec => 'At least one non-alphanumeric',
                   3311:         );
                   3312:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3313:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3314:         $rulenames{'num'} .= ': 0123456789';
                   3315:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3316:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3317:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3318:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3319:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3320:             if (grep(/^$rule$/,@brokerule)) {
                   3321:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3322:             }
                   3323:         }
                   3324:         $warning .= '</ul>';
                   3325:     }
                   3326:     if (wantarray) {
                   3327:         return @brokerule;
                   3328:     }
                   3329:     return $warning;
                   3330: }
                   3331: 
1.1075.2.161.  .5(raebu 3332:22): sub passwd_validation_js {
                   3333:22):     my ($currpasswdval,$domain,$context,$id) = @_;
                   3334:22):     my (%passwdconf,$alertmsg);
                   3335:22):     if ($context eq 'linkprot') {
                   3336:22):         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3337:22):         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3338:22):             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3339:22):                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3340:22):             }
                   3341:22):         }
                   3342:22):         if ($id eq 'add') {
                   3343:22):             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3344:22):         } elsif ($id =~ /^\d+$/) {
                   3345:22):             my $pos = $id+1;
                   3346:22):             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3347:22):         } else {
                   3348:22):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3349:22):         }
                   3350:22):     } else {
                   3351:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3352:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3353:22):     }
                   3354:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3355:22):     $numrules = 0;
                   3356:22):     $min = $Apache::lonnet::passwdmin;
                   3357:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3358:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3359:22):             if ($passwdconf{'min'} > $min) {
                   3360:22):                 $min = $passwdconf{'min'};
                   3361:22):             }
                   3362:22):         }
                   3363:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3364:22):             $max = $passwdconf{'max'};
                   3365:22):             $numrules ++;
                   3366:22):         }
                   3367:22):         @chars = @{$passwdconf{'chars'}};
                   3368:22):         if (@chars) {
                   3369:22):             $numrules ++;
                   3370:22):         }
                   3371:22):     }
                   3372:22):     if ($min > 0) {
                   3373:22):         $numrules ++;
                   3374:22):     }
                   3375:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3376:22):         if ($min) {
                   3377:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3378:22):         }
                   3379:22):         if ($max) {
                   3380:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3381:22):         }
                   3382:22):         my (@charalerts,@charrules);
                   3383:22):         if (@chars) {
                   3384:22):             if (grep(/^uc$/,@chars)) {
                   3385:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3386:22):                 push(@charrules,'uc');
                   3387:22):             }
                   3388:22):             if (grep(/^lc$/,@chars)) {
                   3389:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3390:22):                 push(@charrules,'lc');
                   3391:22):             }
                   3392:22):             if (grep(/^num$/,@chars)) {
                   3393:22):                 push(@charalerts,&mt('contain at least one number'));
                   3394:22):                 push(@charrules,'num');
                   3395:22):             }
                   3396:22):             if (grep(/^spec$/,@chars)) {
                   3397:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3398:22):                 push(@charrules,'spec');
                   3399:22):             }
                   3400:22):         }
                   3401:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3402:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3403:22):             if ($min) {
                   3404:22):                 $intargjs .= qq|
                   3405:22):             if (currpwval.length < $min) {
                   3406:22):                 rulesmsg += ' - $alert{min}';
                   3407:22):             }
                   3408:22): |;
                   3409:22):             }
                   3410:22):             if ($max) {
                   3411:22):                 $intargjs .= qq|
                   3412:22):             if (currpwval.length > $max) {
                   3413:22):                 rulesmsg += ' - $alert{max}';
                   3414:22):             }
                   3415:22): |;
                   3416:22):             }
                   3417:22):             if (@chars > 0) {
                   3418:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3419:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3420:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3421:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3422:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3423:22):                 my %rules;
                   3424:22):                 map { $rules{$_} = 1; } @chars;
                   3425:22):                 if ($rules{'uc'}) {
                   3426:22):                     $intargjs .= qq|
                   3427:22):             var ucRegExp = /[A-Z]/;
                   3428:22):             if (!ucRegExp.test(currpwval)) {
                   3429:22):                 brokerules.push('uc');
                   3430:22):             }
                   3431:22): |;
                   3432:22):                 }
                   3433:22):                 if ($rules{'lc'}) {
                   3434:22):                     $intargjs .= qq|
                   3435:22):             var lcRegExp = /[a-z]/;
                   3436:22):             if (!lcRegExp.test(currpwval)) {
                   3437:22):                 brokerules.push('lc');
                   3438:22):             }
                   3439:22): |;
                   3440:22):                 }
                   3441:22):                 if ($rules{'num'}) {
                   3442:22):                      $intargjs .= qq|
                   3443:22):             var numRegExp = /[0-9]/;
                   3444:22):             if (!numRegExp.test(currpwval)) {
                   3445:22):                 brokerules.push('num');
                   3446:22):             }
                   3447:22): |;
                   3448:22):                 }
                   3449:22):                 if ($rules{'spec'}) {
                   3450:22):                      $intargjs .= q|
                   3451:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3452:22):             if (!specRegExp.test(currpwval)) {
                   3453:22):                 brokerules.push('spec');
                   3454:22):             }
                   3455:22): |;
                   3456:22):                 }
                   3457:22):                 $intargjs .= qq|
                   3458:22):             if (brokerules.length > 0) {
                   3459:22):                 for (var i=0; i<brokerules.length; i++) {
                   3460:22):                     for (var j=0; j<charrules.length; j++) {
                   3461:22):                         if (brokerules[i] == charrules[j]) {
                   3462:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3463:22):                             break;
                   3464:22):                         }
                   3465:22):                     }
                   3466:22):                 }
                   3467:22):             }
                   3468:22): |;
                   3469:22):             }
                   3470:22):             $intargjs .= qq|
                   3471:22):             if (rulesmsg != '') {
                   3472:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3473:22):                 alert(rulesmsg);
                   3474:22):                 return false;
                   3475:22):             }
                   3476:22): |;
                   3477:22):     }
                   3478:22):     return ($numrules,$intargjs);
                   3479:22): }
                   3480:22): 
1.80      albertel 3481: ###############################################################
                   3482: ##    Get Kerberos Defaults for Domain                 ##
                   3483: ###############################################################
                   3484: ##
                   3485: ## Returns default kerberos version and an associated argument
                   3486: ## as listed in file domain.tab. If not listed, provides
                   3487: ## appropriate default domain and kerberos version.
                   3488: ##
                   3489: #-------------------------------------------
                   3490: 
                   3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &get_kerberos_defaults()
1.80      albertel 3494: 
                   3495: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3496: version and domain. If not found, it defaults to version 4 and the 
                   3497: domain of the server.
1.80      albertel 3498: 
1.648     raeburn  3499: =over 4
                   3500: 
1.80      albertel 3501: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3502: 
1.648     raeburn  3503: =back
                   3504: 
                   3505: =back
                   3506: 
1.80      albertel 3507: =cut
                   3508: 
                   3509: #-------------------------------------------
                   3510: sub get_kerberos_defaults {
                   3511:     my $domain=shift;
1.641     raeburn  3512:     my ($krbdef,$krbdefdom);
                   3513:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3514:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3515:         $krbdef = $domdefaults{'auth_def'};
                   3516:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3517:     } else {
1.80      albertel 3518:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3519:         my $krbdefdom=$1;
                   3520:         $krbdefdom=~tr/a-z/A-Z/;
                   3521:         $krbdef = "krb4";
                   3522:     }
                   3523:     return ($krbdef,$krbdefdom);
                   3524: }
1.112     bowersj2 3525: 
1.32      matthew  3526: 
1.46      matthew  3527: ###############################################################
                   3528: ##                Thesaurus Functions                        ##
                   3529: ###############################################################
1.20      www      3530: 
1.46      matthew  3531: =pod
1.20      www      3532: 
1.112     bowersj2 3533: =head1 Thesaurus Functions
                   3534: 
                   3535: =over 4
                   3536: 
1.648     raeburn  3537: =item * &initialize_keywords()
1.46      matthew  3538: 
                   3539: Initializes the package variable %Keywords if it is empty.  Uses the
                   3540: package variable $thesaurus_db_file.
                   3541: 
                   3542: =cut
                   3543: 
                   3544: ###################################################
                   3545: 
                   3546: sub initialize_keywords {
                   3547:     return 1 if (scalar keys(%Keywords));
                   3548:     # If we are here, %Keywords is empty, so fill it up
                   3549:     #   Make sure the file we need exists...
                   3550:     if (! -e $thesaurus_db_file) {
                   3551:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3552:                                  " failed because it does not exist");
                   3553:         return 0;
                   3554:     }
                   3555:     #   Set up the hash as a database
                   3556:     my %thesaurus_db;
                   3557:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3558:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3559:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3560:                                  $thesaurus_db_file);
                   3561:         return 0;
                   3562:     } 
                   3563:     #  Get the average number of appearances of a word.
                   3564:     my $avecount = $thesaurus_db{'average.count'};
                   3565:     #  Put keywords (those that appear > average) into %Keywords
                   3566:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3567:         my ($count,undef) = split /:/,$data;
                   3568:         $Keywords{$word}++ if ($count > $avecount);
                   3569:     }
                   3570:     untie %thesaurus_db;
                   3571:     # Remove special values from %Keywords.
1.356     albertel 3572:     foreach my $value ('total.count','average.count') {
                   3573:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3574:   }
1.46      matthew  3575:     return 1;
                   3576: }
                   3577: 
                   3578: ###################################################
                   3579: 
                   3580: =pod
                   3581: 
1.648     raeburn  3582: =item * &keyword($word)
1.46      matthew  3583: 
                   3584: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3585: than the average number of times in the thesaurus database.  Calls 
                   3586: &initialize_keywords
                   3587: 
                   3588: =cut
                   3589: 
                   3590: ###################################################
1.20      www      3591: 
                   3592: sub keyword {
1.46      matthew  3593:     return if (!&initialize_keywords());
                   3594:     my $word=lc(shift());
                   3595:     $word=~s/\W//g;
                   3596:     return exists($Keywords{$word});
1.20      www      3597: }
1.46      matthew  3598: 
                   3599: ###############################################################
                   3600: 
                   3601: =pod 
1.20      www      3602: 
1.648     raeburn  3603: =item * &get_related_words()
1.46      matthew  3604: 
1.160     matthew  3605: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3606: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3607: will be returned.  The order of the words returned is determined by the
                   3608: database which holds them.
                   3609: 
                   3610: Uses global $thesaurus_db_file.
                   3611: 
1.1057    foxr     3612: 
1.46      matthew  3613: =cut
                   3614: 
                   3615: ###############################################################
                   3616: sub get_related_words {
                   3617:     my $keyword = shift;
                   3618:     my %thesaurus_db;
                   3619:     if (! -e $thesaurus_db_file) {
                   3620:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3621:                                  "failed because the file does not exist");
                   3622:         return ();
                   3623:     }
                   3624:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3625:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3626:         return ();
                   3627:     } 
                   3628:     my @Words=();
1.429     www      3629:     my $count=0;
1.46      matthew  3630:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3631: 	# The first element is the number of times
                   3632: 	# the word appears.  We do not need it now.
1.429     www      3633: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3634: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3635: 	my $threshold=$mostfrequentcount/10;
                   3636:         foreach my $possibleword (@RelatedWords) {
                   3637:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3638:             if ($wordcount>$threshold) {
                   3639: 		push(@Words,$word);
                   3640:                 $count++;
                   3641:                 if ($count>10) { last; }
                   3642: 	    }
1.20      www      3643:         }
                   3644:     }
1.46      matthew  3645:     untie %thesaurus_db;
                   3646:     return @Words;
1.14      harris41 3647: }
1.46      matthew  3648: 
1.112     bowersj2 3649: =pod
                   3650: 
                   3651: =back
                   3652: 
                   3653: =cut
1.61      www      3654: 
                   3655: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3656: =pod
                   3657: 
1.112     bowersj2 3658: =head1 User Name Functions
                   3659: 
                   3660: =over 4
                   3661: 
1.648     raeburn  3662: =item * &plainname($uname,$udom,$first)
1.81      albertel 3663: 
1.112     bowersj2 3664: Takes a users logon name and returns it as a string in
1.226     albertel 3665: "first middle last generation" form 
                   3666: if $first is set to 'lastname' then it returns it as
                   3667: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3668: 
                   3669: =cut
1.61      www      3670: 
1.295     www      3671: 
1.81      albertel 3672: ###############################################################
1.61      www      3673: sub plainname {
1.226     albertel 3674:     my ($uname,$udom,$first)=@_;
1.537     albertel 3675:     return if (!defined($uname) || !defined($udom));
1.295     www      3676:     my %names=&getnames($uname,$udom);
1.226     albertel 3677:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3678: 					  $names{'middlename'},
                   3679: 					  $names{'lastname'},
                   3680: 					  $names{'generation'},$first);
                   3681:     $name=~s/^\s+//;
1.62      www      3682:     $name=~s/\s+$//;
                   3683:     $name=~s/\s+/ /g;
1.353     albertel 3684:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3685:     return $name;
1.61      www      3686: }
1.66      www      3687: 
                   3688: # -------------------------------------------------------------------- Nickname
1.81      albertel 3689: =pod
                   3690: 
1.648     raeburn  3691: =item * &nickname($uname,$udom)
1.81      albertel 3692: 
                   3693: Gets a users name and returns it as a string as
                   3694: 
                   3695: "&quot;nickname&quot;"
1.66      www      3696: 
1.81      albertel 3697: if the user has a nickname or
                   3698: 
                   3699: "first middle last generation"
                   3700: 
                   3701: if the user does not
                   3702: 
                   3703: =cut
1.66      www      3704: 
                   3705: sub nickname {
                   3706:     my ($uname,$udom)=@_;
1.537     albertel 3707:     return if (!defined($uname) || !defined($udom));
1.295     www      3708:     my %names=&getnames($uname,$udom);
1.68      albertel 3709:     my $name=$names{'nickname'};
1.66      www      3710:     if ($name) {
                   3711:        $name='&quot;'.$name.'&quot;'; 
                   3712:     } else {
                   3713:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3714: 	     $names{'lastname'}.' '.$names{'generation'};
                   3715:        $name=~s/\s+$//;
                   3716:        $name=~s/\s+/ /g;
                   3717:     }
                   3718:     return $name;
                   3719: }
                   3720: 
1.295     www      3721: sub getnames {
                   3722:     my ($uname,$udom)=@_;
1.537     albertel 3723:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3724:     if ($udom eq 'public' && $uname eq 'public') {
                   3725: 	return ('lastname' => &mt('Public'));
                   3726:     }
1.295     www      3727:     my $id=$uname.':'.$udom;
                   3728:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3729:     if ($cached) {
                   3730: 	return %{$names};
                   3731:     } else {
                   3732: 	my %loadnames=&Apache::lonnet::get('environment',
                   3733:                     ['firstname','middlename','lastname','generation','nickname'],
                   3734: 					 $udom,$uname);
                   3735: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3736: 	return %loadnames;
                   3737:     }
                   3738: }
1.61      www      3739: 
1.542     raeburn  3740: # -------------------------------------------------------------------- getemails
1.648     raeburn  3741: 
1.542     raeburn  3742: =pod
                   3743: 
1.648     raeburn  3744: =item * &getemails($uname,$udom)
1.542     raeburn  3745: 
                   3746: Gets a user's email information and returns it as a hash with keys:
                   3747: notification, critnotification, permanentemail
                   3748: 
                   3749: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3750: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3751:  
1.648     raeburn  3752: 
1.542     raeburn  3753: =cut
                   3754: 
1.648     raeburn  3755: 
1.466     albertel 3756: sub getemails {
                   3757:     my ($uname,$udom)=@_;
                   3758:     if ($udom eq 'public' && $uname eq 'public') {
                   3759: 	return;
                   3760:     }
1.467     www      3761:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3762:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3763:     my $id=$uname.':'.$udom;
                   3764:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3765:     if ($cached) {
                   3766: 	return %{$names};
                   3767:     } else {
                   3768: 	my %loadnames=&Apache::lonnet::get('environment',
                   3769:                     			   ['notification','critnotification',
                   3770: 					    'permanentemail'],
                   3771: 					   $udom,$uname);
                   3772: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3773: 	return %loadnames;
                   3774:     }
                   3775: }
                   3776: 
1.551     albertel 3777: sub flush_email_cache {
                   3778:     my ($uname,$udom)=@_;
                   3779:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3780:     if (!$uname) { $uname=$env{'user.name'};   }
                   3781:     return if ($udom eq 'public' && $uname eq 'public');
                   3782:     my $id=$uname.':'.$udom;
                   3783:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3784: }
                   3785: 
1.728     raeburn  3786: # -------------------------------------------------------------------- getlangs
                   3787: 
                   3788: =pod
                   3789: 
                   3790: =item * &getlangs($uname,$udom)
                   3791: 
                   3792: Gets a user's language preference and returns it as a hash with key:
                   3793: language.
                   3794: 
                   3795: =cut
                   3796: 
                   3797: 
                   3798: sub getlangs {
                   3799:     my ($uname,$udom) = @_;
                   3800:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3801:     if (!$uname) { $uname=$env{'user.name'};   }
                   3802:     my $id=$uname.':'.$udom;
                   3803:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3804:     if ($cached) {
                   3805:         return %{$langs};
                   3806:     } else {
                   3807:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3808:                                            $udom,$uname);
                   3809:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3810:         return %loadlangs;
                   3811:     }
                   3812: }
                   3813: 
                   3814: sub flush_langs_cache {
                   3815:     my ($uname,$udom)=@_;
                   3816:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3817:     if (!$uname) { $uname=$env{'user.name'};   }
                   3818:     return if ($udom eq 'public' && $uname eq 'public');
                   3819:     my $id=$uname.':'.$udom;
                   3820:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3821: }
                   3822: 
1.61      www      3823: # ------------------------------------------------------------------ Screenname
1.81      albertel 3824: 
                   3825: =pod
                   3826: 
1.648     raeburn  3827: =item * &screenname($uname,$udom)
1.81      albertel 3828: 
                   3829: Gets a users screenname and returns it as a string
                   3830: 
                   3831: =cut
1.61      www      3832: 
                   3833: sub screenname {
                   3834:     my ($uname,$udom)=@_;
1.258     albertel 3835:     if ($uname eq $env{'user.name'} &&
                   3836: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3837:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3838:     return $names{'screenname'};
1.62      www      3839: }
                   3840: 
1.212     albertel 3841: 
1.802     bisitz   3842: # ------------------------------------------------------------- Confirm Wrapper
                   3843: =pod
                   3844: 
1.1075.2.42  raeburn  3845: =item * &confirmwrapper($message)
1.802     bisitz   3846: 
                   3847: Wrap messages about completion of operation in box
                   3848: 
                   3849: =cut
                   3850: 
                   3851: sub confirmwrapper {
                   3852:     my ($message)=@_;
                   3853:     if ($message) {
                   3854:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3855:                .$message."\n"
                   3856:                .'</div>'."\n";
                   3857:     } else {
                   3858:         return $message;
                   3859:     }
                   3860: }
                   3861: 
1.62      www      3862: # ------------------------------------------------------------- Message Wrapper
                   3863: 
                   3864: sub messagewrapper {
1.369     www      3865:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3866:     return 
1.441     albertel 3867:         '<a href="/adm/email?compose=individual&amp;'.
                   3868:         'recname='.$username.'&amp;recdom='.$domain.
                   3869: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3870:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3871: }
1.802     bisitz   3872: 
1.74      www      3873: # --------------------------------------------------------------- Notes Wrapper
                   3874: 
                   3875: sub noteswrapper {
                   3876:     my ($link,$un,$do)=@_;
                   3877:     return 
1.896     amueller 3878: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3879: }
1.802     bisitz   3880: 
1.62      www      3881: # ------------------------------------------------------------- Aboutme Wrapper
                   3882: 
                   3883: sub aboutmewrapper {
1.1070    raeburn  3884:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3885:     if (!defined($username)  && !defined($domain)) {
                   3886:         return;
                   3887:     }
1.1075.2.15  raeburn  3888:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3889: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3890: }
                   3891: 
                   3892: # ------------------------------------------------------------ Syllabus Wrapper
                   3893: 
                   3894: sub syllabuswrapper {
1.707     bisitz   3895:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3896:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3897: }
1.14      harris41 3898: 
1.1075.2.161.  .11(raeb 3899:-22): sub aboutme_on {
                   3900:-22):     my ($uname,$udom)=@_;
                   3901:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   3902:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   3903:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3904:-22):     my $hashkey=$uname.':'.$udom;
                   3905:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   3906:-22):     if ($cached) {
                   3907:-22):         return $aboutme;
                   3908:-22):     }
                   3909:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   3910:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   3911:-22):     return $aboutme;
                   3912:-22): }
                   3913:-22): 
                   3914:-22): sub devalidate_aboutme_cache {
                   3915:-22):     my ($uname,$udom)=@_;
                   3916:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3917:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   3918:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3919:-22):     my $id=$uname.':'.$udom;
                   3920:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   3921:-22): }
                   3922:-22): 
1.802     bisitz   3923: # -----------------------------------------------------------------------------
                   3924: 
1.208     matthew  3925: sub track_student_link {
1.887     raeburn  3926:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3927:     my $link ="/adm/trackstudent?";
1.208     matthew  3928:     my $title = 'View recent activity';
                   3929:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3930:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3931:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3932:         $title .= ' of this student';
1.268     albertel 3933:     } 
1.208     matthew  3934:     if (defined($target) && $target !~ /^\s*$/) {
                   3935:         $target = qq{target="$target"};
                   3936:     } else {
                   3937:         $target = '';
                   3938:     }
1.268     albertel 3939:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3940:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3941:     $title = &mt($title);
                   3942:     $linktext = &mt($linktext);
1.448     albertel 3943:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3944: 	&help_open_topic('View_recent_activity');
1.208     matthew  3945: }
                   3946: 
1.781     raeburn  3947: sub slot_reservations_link {
                   3948:     my ($linktext,$sname,$sdom,$target) = @_;
                   3949:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3950:     my $title = 'View slot reservation history';
                   3951:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3952:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3953:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3954:         $title .= ' of this student';
                   3955:     }
                   3956:     if (defined($target) && $target !~ /^\s*$/) {
                   3957:         $target = qq{target="$target"};
                   3958:     } else {
                   3959:         $target = '';
                   3960:     }
                   3961:     $title = &mt($title);
                   3962:     $linktext = &mt($linktext);
                   3963:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3964: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3965: 
                   3966: }
                   3967: 
1.508     www      3968: # ===================================================== Display a student photo
                   3969: 
                   3970: 
1.509     albertel 3971: sub student_image_tag {
1.508     www      3972:     my ($domain,$user)=@_;
                   3973:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3974:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3975: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3976:     } else {
                   3977: 	return '';
                   3978:     }
                   3979: }
                   3980: 
1.112     bowersj2 3981: =pod
                   3982: 
                   3983: =back
                   3984: 
                   3985: =head1 Access .tab File Data
                   3986: 
                   3987: =over 4
                   3988: 
1.648     raeburn  3989: =item * &languageids() 
1.112     bowersj2 3990: 
                   3991: returns list of all language ids
                   3992: 
                   3993: =cut
                   3994: 
1.14      harris41 3995: sub languageids {
1.16      harris41 3996:     return sort(keys(%language));
1.14      harris41 3997: }
                   3998: 
1.112     bowersj2 3999: =pod
                   4000: 
1.648     raeburn  4001: =item * &languagedescription() 
1.112     bowersj2 4002: 
                   4003: returns description of a specified language id
                   4004: 
                   4005: =cut
                   4006: 
1.14      harris41 4007: sub languagedescription {
1.125     www      4008:     my $code=shift;
                   4009:     return  ($supported_language{$code}?'* ':'').
                   4010:             $language{$code}.
1.126     www      4011: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4012: }
                   4013: 
1.1048    foxr     4014: =pod
                   4015: 
                   4016: =item * &plainlanguagedescription
                   4017: 
                   4018: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4019: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4020: 
                   4021: =cut
                   4022: 
1.145     www      4023: sub plainlanguagedescription {
                   4024:     my $code=shift;
                   4025:     return $language{$code};
                   4026: }
                   4027: 
1.1048    foxr     4028: =pod
                   4029: 
                   4030: =item * &supportedlanguagecode
                   4031: 
                   4032: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4033: code.
                   4034: 
                   4035: =cut
                   4036: 
1.145     www      4037: sub supportedlanguagecode {
                   4038:     my $code=shift;
                   4039:     return $supported_language{$code};
1.97      www      4040: }
                   4041: 
1.112     bowersj2 4042: =pod
                   4043: 
1.1048    foxr     4044: =item * &latexlanguage()
                   4045: 
                   4046: Given a language key code returns the correspondnig language to use
                   4047: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4048: is no supported hyphenation for the language code.
                   4049: 
                   4050: =cut
                   4051: 
                   4052: sub latexlanguage {
                   4053:     my $code = shift;
                   4054:     return $latex_language{$code};
                   4055: }
                   4056: 
                   4057: =pod
                   4058: 
                   4059: =item * &latexhyphenation()
                   4060: 
                   4061: Same as above but what's supplied is the language as it might be stored
                   4062: in the metadata.
                   4063: 
                   4064: =cut
                   4065: 
                   4066: sub latexhyphenation {
                   4067:     my $key = shift;
                   4068:     return $latex_language_bykey{$key};
                   4069: }
                   4070: 
                   4071: =pod
                   4072: 
1.648     raeburn  4073: =item * &copyrightids() 
1.112     bowersj2 4074: 
                   4075: returns list of all copyrights
                   4076: 
                   4077: =cut
                   4078: 
                   4079: sub copyrightids {
                   4080:     return sort(keys(%cprtag));
                   4081: }
                   4082: 
                   4083: =pod
                   4084: 
1.648     raeburn  4085: =item * &copyrightdescription() 
1.112     bowersj2 4086: 
                   4087: returns description of a specified copyright id
                   4088: 
                   4089: =cut
                   4090: 
                   4091: sub copyrightdescription {
1.166     www      4092:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4093: }
1.197     matthew  4094: 
                   4095: =pod
                   4096: 
1.648     raeburn  4097: =item * &source_copyrightids() 
1.192     taceyjo1 4098: 
                   4099: returns list of all source copyrights
                   4100: 
                   4101: =cut
                   4102: 
                   4103: sub source_copyrightids {
                   4104:     return sort(keys(%scprtag));
                   4105: }
                   4106: 
                   4107: =pod
                   4108: 
1.648     raeburn  4109: =item * &source_copyrightdescription() 
1.192     taceyjo1 4110: 
                   4111: returns description of a specified source copyright id
                   4112: 
                   4113: =cut
                   4114: 
                   4115: sub source_copyrightdescription {
                   4116:     return &mt($scprtag{shift(@_)});
                   4117: }
1.112     bowersj2 4118: 
                   4119: =pod
                   4120: 
1.648     raeburn  4121: =item * &filecategories() 
1.112     bowersj2 4122: 
                   4123: returns list of all file categories
                   4124: 
                   4125: =cut
                   4126: 
                   4127: sub filecategories {
                   4128:     return sort(keys(%category_extensions));
                   4129: }
                   4130: 
                   4131: =pod
                   4132: 
1.648     raeburn  4133: =item * &filecategorytypes() 
1.112     bowersj2 4134: 
                   4135: returns list of file types belonging to a given file
                   4136: category
                   4137: 
                   4138: =cut
                   4139: 
                   4140: sub filecategorytypes {
1.356     albertel 4141:     my ($cat) = @_;
                   4142:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4143: }
                   4144: 
                   4145: =pod
                   4146: 
1.648     raeburn  4147: =item * &fileembstyle() 
1.112     bowersj2 4148: 
                   4149: returns embedding style for a specified file type
                   4150: 
                   4151: =cut
                   4152: 
                   4153: sub fileembstyle {
                   4154:     return $fe{lc(shift(@_))};
1.169     www      4155: }
                   4156: 
1.351     www      4157: sub filemimetype {
                   4158:     return $fm{lc(shift(@_))};
                   4159: }
                   4160: 
1.169     www      4161: 
                   4162: sub filecategoryselect {
                   4163:     my ($name,$value)=@_;
1.189     matthew  4164:     return &select_form($value,$name,
1.970     raeburn  4165:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4166: }
                   4167: 
                   4168: =pod
                   4169: 
1.648     raeburn  4170: =item * &filedescription() 
1.112     bowersj2 4171: 
                   4172: returns description for a specified file type
                   4173: 
                   4174: =cut
                   4175: 
                   4176: sub filedescription {
1.188     matthew  4177:     my $file_description = $fd{lc(shift())};
                   4178:     $file_description =~ s:([\[\]]):~$1:g;
                   4179:     return &mt($file_description);
1.112     bowersj2 4180: }
                   4181: 
                   4182: =pod
                   4183: 
1.648     raeburn  4184: =item * &filedescriptionex() 
1.112     bowersj2 4185: 
                   4186: returns description for a specified file type with
                   4187: extra formatting
                   4188: 
                   4189: =cut
                   4190: 
                   4191: sub filedescriptionex {
                   4192:     my $ex=shift;
1.188     matthew  4193:     my $file_description = $fd{lc($ex)};
                   4194:     $file_description =~ s:([\[\]]):~$1:g;
                   4195:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4196: }
                   4197: 
                   4198: # End of .tab access
                   4199: =pod
                   4200: 
                   4201: =back
                   4202: 
                   4203: =cut
                   4204: 
                   4205: # ------------------------------------------------------------------ File Types
                   4206: sub fileextensions {
                   4207:     return sort(keys(%fe));
                   4208: }
                   4209: 
1.97      www      4210: # ----------------------------------------------------------- Display Languages
                   4211: # returns a hash with all desired display languages
                   4212: #
                   4213: 
                   4214: sub display_languages {
                   4215:     my %languages=();
1.695     raeburn  4216:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4217: 	$languages{$lang}=1;
1.97      www      4218:     }
                   4219:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4220:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4221: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4222: 	    $languages{$lang}=1;
1.97      www      4223:         }
                   4224:     }
                   4225:     return %languages;
1.14      harris41 4226: }
                   4227: 
1.582     albertel 4228: sub languages {
                   4229:     my ($possible_langs) = @_;
1.695     raeburn  4230:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4231:     if (!ref($possible_langs)) {
                   4232: 	if( wantarray ) {
                   4233: 	    return @preferred_langs;
                   4234: 	} else {
                   4235: 	    return $preferred_langs[0];
                   4236: 	}
                   4237:     }
                   4238:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4239:     my @preferred_possibilities;
                   4240:     foreach my $preferred_lang (@preferred_langs) {
                   4241: 	if (exists($possibilities{$preferred_lang})) {
                   4242: 	    push(@preferred_possibilities, $preferred_lang);
                   4243: 	}
                   4244:     }
                   4245:     if( wantarray ) {
                   4246: 	return @preferred_possibilities;
                   4247:     }
                   4248:     return $preferred_possibilities[0];
                   4249: }
                   4250: 
1.742     raeburn  4251: sub user_lang {
                   4252:     my ($touname,$toudom,$fromcid) = @_;
                   4253:     my @userlangs;
                   4254:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4255:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4256:                     $env{'course.'.$fromcid.'.languages'}));
                   4257:     } else {
                   4258:         my %langhash = &getlangs($touname,$toudom);
                   4259:         if ($langhash{'languages'} ne '') {
                   4260:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4261:         } else {
                   4262:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4263:             if ($domdefs{'lang_def'} ne '') {
                   4264:                 @userlangs = ($domdefs{'lang_def'});
                   4265:             }
                   4266:         }
                   4267:     }
                   4268:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4269:     my $user_lh = Apache::localize->get_handle(@languages);
                   4270:     return $user_lh;
                   4271: }
                   4272: 
                   4273: 
1.112     bowersj2 4274: ###############################################################
                   4275: ##               Student Answer Attempts                     ##
                   4276: ###############################################################
                   4277: 
                   4278: =pod
                   4279: 
                   4280: =head1 Alternate Problem Views
                   4281: 
                   4282: =over 4
                   4283: 
1.648     raeburn  4284: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4285:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4286: 
                   4287: Return string with previous attempt on problem. Arguments:
                   4288: 
                   4289: =over 4
                   4290: 
                   4291: =item * $symb: Problem, including path
                   4292: 
                   4293: =item * $username: username of the desired student
                   4294: 
                   4295: =item * $domain: domain of the desired student
1.14      harris41 4296: 
1.112     bowersj2 4297: =item * $course: Course ID
1.14      harris41 4298: 
1.112     bowersj2 4299: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4300:     something
1.14      harris41 4301: 
1.112     bowersj2 4302: =item * $regexp: if string matches this regexp, the string will be
                   4303:     sent to $gradesub
1.14      harris41 4304: 
1.112     bowersj2 4305: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4306: 
1.1075.2.86  raeburn  4307: =item * $usec: section of the desired student
                   4308: 
                   4309: =item * $identifier: counter for student (multiple students one problem) or
                   4310:     problem (one student; whole sequence).
                   4311: 
1.112     bowersj2 4312: =back
1.14      harris41 4313: 
1.112     bowersj2 4314: The output string is a table containing all desired attempts, if any.
1.16      harris41 4315: 
1.112     bowersj2 4316: =cut
1.1       albertel 4317: 
                   4318: sub get_previous_attempt {
1.1075.2.86  raeburn  4319:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4320:   my $prevattempts='';
1.43      ng       4321:   no strict 'refs';
1.1       albertel 4322:   if ($symb) {
1.3       albertel 4323:     my (%returnhash)=
                   4324:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4325:     if ($returnhash{'version'}) {
                   4326:       my %lasthash=();
                   4327:       my $version;
                   4328:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4329:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4330:             if ($key =~ /\.rawrndseed$/) {
                   4331:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4332:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4333:             } else {
                   4334:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4335:             }
1.19      harris41 4336:         }
1.1       albertel 4337:       }
1.596     albertel 4338:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4339:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4340:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4341:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4342:       foreach my $key (sort(keys(%lasthash))) {
                   4343: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4344: 	if ($#parts > 0) {
1.31      albertel 4345: 	  my $data=$parts[-1];
1.989     raeburn  4346:           next if ($data eq 'foilorder');
1.31      albertel 4347: 	  pop(@parts);
1.1010    www      4348:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4349:           if ($data eq 'type') {
                   4350:               unless ($showsurv) {
                   4351:                   my $id = join(',',@parts);
                   4352:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4353:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4354:                       $lasthidden{$ign.'.'.$id} = 1;
                   4355:                   }
1.945     raeburn  4356:               }
1.1075.2.86  raeburn  4357:               if ($identifier ne '') {
                   4358:                   my $id = join(',',@parts);
                   4359:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4360:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4361:                       $hidestatus{$ign.'.'.$id} = 1;
                   4362:                   }
                   4363:               }
                   4364:           } elsif ($data eq 'regrader') {
                   4365:               if (($identifier ne '') && (@parts)) {
                   4366:                   my $id = join(',',@parts);
                   4367:                   $regraded{$ign.'.'.$id} = 1;
                   4368:               }
1.1010    www      4369:           } 
1.31      albertel 4370: 	} else {
1.41      ng       4371: 	  if ($#parts == 0) {
                   4372: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4373: 	  } else {
                   4374: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4375: 	  }
1.31      albertel 4376: 	}
1.16      harris41 4377:       }
1.596     albertel 4378:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4379:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4380:         my (%solved,%resets,%probstatus);
                   4381:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4382:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4383:                 foreach my $id (keys(%regraded)) {
                   4384:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4385:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4386:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4387:                         push(@{$resets{$id}},$version);
                   4388:                     }
                   4389:                 }
                   4390:             }
                   4391:         }
1.40      ng       4392: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4393:             my (@hidden,@unsolved);
1.945     raeburn  4394:             if (%typeparts) {
                   4395:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4396:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4397:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4398:                         push(@hidden,$id);
1.1075.2.86  raeburn  4399:                     } elsif ($identifier ne '') {
                   4400:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4401:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4402:                                 ($hidestatus{$id})) {
                   4403:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4404:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4405:                                 push(@{$solved{$id}},$version);
                   4406:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4407:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4408:                                 my $skip;
                   4409:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4410:                                     foreach my $reset (@{$resets{$id}}) {
                   4411:                                         if ($reset > $solved{$id}[-1]) {
                   4412:                                             $skip=1;
                   4413:                                             last;
                   4414:                                         }
                   4415:                                     }
                   4416:                                 }
                   4417:                                 unless ($skip) {
                   4418:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4419:                                     push(@unsolved,$partslist);
                   4420:                                 }
                   4421:                             }
                   4422:                         }
1.945     raeburn  4423:                     }
                   4424:                 }
                   4425:             }
                   4426:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4427:                            '<td>'.&mt('Transaction [_1]',$version);
                   4428:             if (@unsolved) {
                   4429:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4430:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4431:                                  &mt('Hide').'</label></span>';
                   4432:             }
                   4433:             $prevattempts .= '</td>';
1.945     raeburn  4434:             if (@hidden) {
                   4435:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4436:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4437:                     my $hide;
                   4438:                     foreach my $id (@hidden) {
                   4439:                         if ($key =~ /^\Q$id\E/) {
                   4440:                             $hide = 1;
                   4441:                             last;
                   4442:                         }
                   4443:                     }
                   4444:                     if ($hide) {
                   4445:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4446:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4447:                             my $value = &format_previous_attempt_value($key,
                   4448:                                              $returnhash{$version.':'.$key});
                   4449:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4450:                         } else {
                   4451:                             $prevattempts.='<td>&nbsp;</td>';
                   4452:                         }
                   4453:                     } else {
                   4454:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4455:                             my $value = $returnhash{$version.':'.$key};
                   4456:                             if ($key =~ /\.rndseed$/) {
                   4457:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4458:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4459:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4460:                                 }
                   4461:                             }
                   4462:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4463:                                            '&nbsp;</td>';
1.945     raeburn  4464:                         } else {
                   4465:                             $prevattempts.='<td>&nbsp;</td>';
                   4466:                         }
                   4467:                     }
                   4468:                 }
                   4469:             } else {
                   4470: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4471:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4472:                     my $value = $returnhash{$version.':'.$key};
                   4473:                     if ($key =~ /\.rndseed$/) {
                   4474:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4475:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4476:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4477:                         }
                   4478:                     }
                   4479:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4480:                                    '&nbsp;</td>';
1.945     raeburn  4481: 	        }
                   4482:             }
                   4483: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4484: 	 }
1.1       albertel 4485:       }
1.945     raeburn  4486:       my @currhidden = keys(%lasthidden);
1.596     albertel 4487:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4488:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4489:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4490:           if (%typeparts) {
                   4491:               my $hidden;
                   4492:               foreach my $id (@currhidden) {
                   4493:                   if ($key =~ /^\Q$id\E/) {
                   4494:                       $hidden = 1;
                   4495:                       last;
                   4496:                   }
                   4497:               }
                   4498:               if ($hidden) {
                   4499:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4500:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4501:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4502:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4503:                           $value = &$gradesub($value);
                   4504:                       }
                   4505:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4506:                   } else {
                   4507:                       $prevattempts.='<td>&nbsp;</td>';
                   4508:                   }
                   4509:               } else {
                   4510:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4511:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4512:                       $value = &$gradesub($value);
                   4513:                   }
                   4514:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4515:               }
                   4516:           } else {
                   4517: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4518: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4519:                   $value = &$gradesub($value);
                   4520:               }
                   4521: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4522:           }
1.16      harris41 4523:       }
1.596     albertel 4524:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4525:     } else {
1.1075.2.161.  .17(raeb 4526:-23):       my $msg;
                   4527:-23):       if ($symb =~ /ext\.tool$/) {
                   4528:-23):           $msg = &mt('No grade passed back.');
                   4529:-23):       } else {
                   4530:-23):           $msg = &mt('Nothing submitted - no attempts.');
                   4531:-23):       }
1.596     albertel 4532:       $prevattempts=
                   4533: 	  &start_data_table().&start_data_table_row().
1.1075.2.161.  .17(raeb 4534:-23): 	  '<td>'.$msg.'</td>'.
1.596     albertel 4535: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4536:     }
                   4537:   } else {
1.596     albertel 4538:     $prevattempts=
                   4539: 	  &start_data_table().&start_data_table_row().
                   4540: 	  '<td>'.&mt('No data.').'</td>'.
                   4541: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4542:   }
1.10      albertel 4543: }
                   4544: 
1.581     albertel 4545: sub format_previous_attempt_value {
                   4546:     my ($key,$value) = @_;
1.1011    www      4547:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4548: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4549:     } elsif (ref($value) eq 'ARRAY') {
                   4550: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4551:     } elsif ($key =~ /answerstring$/) {
                   4552:         my %answers = &Apache::lonnet::str2hash($value);
                   4553:         my @anskeys = sort(keys(%answers));
                   4554:         if (@anskeys == 1) {
                   4555:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4556:             if ($answer =~ m{\0}) {
                   4557:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4558:             }
                   4559:             my $tag_internal_answer_name = 'INTERNAL';
                   4560:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4561:                 $value = $answer; 
                   4562:             } else {
                   4563:                 $value = $anskeys[0].'='.$answer;
                   4564:             }
                   4565:         } else {
                   4566:             foreach my $ans (@anskeys) {
                   4567:                 my $answer = $answers{$ans};
1.1001    raeburn  4568:                 if ($answer =~ m{\0}) {
                   4569:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4570:                 }
                   4571:                 $value .=  $ans.'='.$answer.'<br />';;
                   4572:             } 
                   4573:         }
1.581     albertel 4574:     } else {
                   4575: 	$value = &unescape($value);
                   4576:     }
                   4577:     return $value;
                   4578: }
                   4579: 
                   4580: 
1.107     albertel 4581: sub relative_to_absolute {
                   4582:     my ($url,$output)=@_;
                   4583:     my $parser=HTML::TokeParser->new(\$output);
                   4584:     my $token;
                   4585:     my $thisdir=$url;
                   4586:     my @rlinks=();
                   4587:     while ($token=$parser->get_token) {
                   4588: 	if ($token->[0] eq 'S') {
                   4589: 	    if ($token->[1] eq 'a') {
                   4590: 		if ($token->[2]->{'href'}) {
                   4591: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4592: 		}
                   4593: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4594: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4595: 	    } elsif ($token->[1] eq 'base') {
                   4596: 		$thisdir=$token->[2]->{'href'};
                   4597: 	    }
                   4598: 	}
                   4599:     }
                   4600:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4601:     foreach my $link (@rlinks) {
1.726     raeburn  4602: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4603: 		($link=~/^\//) ||
                   4604: 		($link=~/^javascript:/i) ||
                   4605: 		($link=~/^mailto:/i) ||
                   4606: 		($link=~/^\#/)) {
                   4607: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4608: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4609: 	}
                   4610:     }
                   4611: # -------------------------------------------------- Deal with Applet codebases
                   4612:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4613:     return $output;
                   4614: }
                   4615: 
1.112     bowersj2 4616: =pod
                   4617: 
1.648     raeburn  4618: =item * &get_student_view()
1.112     bowersj2 4619: 
                   4620: show a snapshot of what student was looking at
                   4621: 
                   4622: =cut
                   4623: 
1.10      albertel 4624: sub get_student_view {
1.186     albertel 4625:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4626:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4627:   my (%form);
1.10      albertel 4628:   my @elements=('symb','courseid','domain','username');
                   4629:   foreach my $element (@elements) {
1.186     albertel 4630:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4631:   }
1.186     albertel 4632:   if (defined($moreenv)) {
                   4633:       %form=(%form,%{$moreenv});
                   4634:   }
1.236     albertel 4635:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4636:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4637:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4638:   $userview=~s/\<body[^\>]*\>//gi;
                   4639:   $userview=~s/\<\/body\>//gi;
                   4640:   $userview=~s/\<html\>//gi;
                   4641:   $userview=~s/\<\/html\>//gi;
                   4642:   $userview=~s/\<head\>//gi;
                   4643:   $userview=~s/\<\/head\>//gi;
                   4644:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4645:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4646:   if (wantarray) {
                   4647:      return ($userview,$response);
                   4648:   } else {
                   4649:      return $userview;
                   4650:   }
                   4651: }
                   4652: 
                   4653: sub get_student_view_with_retries {
                   4654:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4655: 
                   4656:     my $ok = 0;                 # True if we got a good response.
                   4657:     my $content;
                   4658:     my $response;
                   4659: 
                   4660:     # Try to get the student_view done. within the retries count:
                   4661:     
                   4662:     do {
                   4663:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4664:          $ok      = $response->is_success;
                   4665:          if (!$ok) {
                   4666:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4667:          }
                   4668:          $retries--;
                   4669:     } while (!$ok && ($retries > 0));
                   4670:     
                   4671:     if (!$ok) {
                   4672:        $content = '';          # On error return an empty content.
                   4673:     }
1.651     www      4674:     if (wantarray) {
                   4675:        return ($content, $response);
                   4676:     } else {
                   4677:        return $content;
                   4678:     }
1.11      albertel 4679: }
                   4680: 
1.1075.2.149  raeburn  4681: sub css_links {
                   4682:     my ($currsymb,$level) = @_;
                   4683:     my ($links,@symbs,%cssrefs,%httpref);
                   4684:     if ($level eq 'map') {
                   4685:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4686:         if (ref($navmap)) {
                   4687:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4688:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4689:             foreach my $res (@resources) {
                   4690:                 if (ref($res) && $res->symb()) {
                   4691:                     push(@symbs,$res->symb());
                   4692:                 }
                   4693:             }
                   4694:         }
                   4695:     } else {
                   4696:         @symbs = ($currsymb);
                   4697:     }
                   4698:     foreach my $symb (@symbs) {
                   4699:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4700:         if ($css_href =~ /\S/) {
                   4701:             unless ($css_href =~ m{https?://}) {
                   4702:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4703:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4704:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4705:                 unless ($css_href =~ m{^/}) {
                   4706:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4707:                 }
                   4708:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4709:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4710:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4711:                         my $thisurl = $proburl;
                   4712:                         if ($env{'httpref.'.$proburl}) {
                   4713:                             $thisurl = $env{'httpref.'.$proburl};
                   4714:                         }
                   4715:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4716:                     }
                   4717:                 }
                   4718:             }
                   4719:             $cssrefs{$css_href} = 1;
                   4720:         }
                   4721:     }
                   4722:     if (keys(%httpref)) {
                   4723:         &Apache::lonnet::appenv(\%httpref);
                   4724:     }
                   4725:     if (keys(%cssrefs)) {
                   4726:         foreach my $css_href (keys(%cssrefs)) {
                   4727:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4728:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4729:         }
                   4730:     }
                   4731:     return $links;
                   4732: }
                   4733: 
1.112     bowersj2 4734: =pod
                   4735: 
1.648     raeburn  4736: =item * &get_student_answers() 
1.112     bowersj2 4737: 
                   4738: show a snapshot of how student was answering problem
                   4739: 
                   4740: =cut
                   4741: 
1.11      albertel 4742: sub get_student_answers {
1.100     sakharuk 4743:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4744:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4745:   my (%moreenv);
1.11      albertel 4746:   my @elements=('symb','courseid','domain','username');
                   4747:   foreach my $element (@elements) {
1.186     albertel 4748:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4749:   }
1.186     albertel 4750:   $moreenv{'grade_target'}='answer';
                   4751:   %moreenv=(%form,%moreenv);
1.497     raeburn  4752:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4753:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4754:   return $userview;
1.1       albertel 4755: }
1.116     albertel 4756: 
                   4757: =pod
                   4758: 
                   4759: =item * &submlink()
                   4760: 
1.242     albertel 4761: Inputs: $text $uname $udom $symb $target
1.116     albertel 4762: 
                   4763: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4764: 
                   4765: =cut
                   4766: 
                   4767: ###############################################
                   4768: sub submlink {
1.242     albertel 4769:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4770:     if (!($uname && $udom)) {
                   4771: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4772: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4773: 	if (!$symb) { $symb=$cursymb; }
                   4774:     }
1.254     matthew  4775:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4776:     $symb=&escape($symb);
1.960     bisitz   4777:     if ($target) { $target=" target=\"$target\""; }
                   4778:     return
                   4779:         '<a href="/adm/grades?command=submission'.
                   4780:         '&amp;symb='.$symb.
                   4781:         '&amp;student='.$uname.
                   4782:         '&amp;userdom='.$udom.'"'.
                   4783:         $target.'>'.$text.'</a>';
1.242     albertel 4784: }
                   4785: ##############################################
                   4786: 
                   4787: =pod
                   4788: 
                   4789: =item * &pgrdlink()
                   4790: 
                   4791: Inputs: $text $uname $udom $symb $target
                   4792: 
                   4793: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4794: 
                   4795: =cut
                   4796: 
                   4797: ###############################################
                   4798: sub pgrdlink {
                   4799:     my $link=&submlink(@_);
                   4800:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4801:     return $link;
                   4802: }
                   4803: ##############################################
                   4804: 
                   4805: =pod
                   4806: 
                   4807: =item * &pprmlink()
                   4808: 
                   4809: Inputs: $text $uname $udom $symb $target
                   4810: 
                   4811: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4812: student and a specific resource
1.242     albertel 4813: 
                   4814: =cut
                   4815: 
                   4816: ###############################################
                   4817: sub pprmlink {
                   4818:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4819:     if (!($uname && $udom)) {
                   4820: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4821: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4822: 	if (!$symb) { $symb=$cursymb; }
                   4823:     }
1.254     matthew  4824:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4825:     $symb=&escape($symb);
1.242     albertel 4826:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4827:     return '<a href="/adm/parmset?command=set&amp;'.
                   4828: 	'symb='.$symb.'&amp;uname='.$uname.
                   4829: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4830: }
                   4831: ##############################################
1.37      matthew  4832: 
1.112     bowersj2 4833: =pod
                   4834: 
                   4835: =back
                   4836: 
                   4837: =cut
                   4838: 
1.37      matthew  4839: ###############################################
1.51      www      4840: 
                   4841: 
                   4842: sub timehash {
1.687     raeburn  4843:     my ($thistime) = @_;
                   4844:     my $timezone = &Apache::lonlocal::gettimezone();
                   4845:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4846:                      ->set_time_zone($timezone);
                   4847:     my $wday = $dt->day_of_week();
                   4848:     if ($wday == 7) { $wday = 0; }
                   4849:     return ( 'second' => $dt->second(),
                   4850:              'minute' => $dt->minute(),
                   4851:              'hour'   => $dt->hour(),
                   4852:              'day'     => $dt->day_of_month(),
                   4853:              'month'   => $dt->month(),
                   4854:              'year'    => $dt->year(),
                   4855:              'weekday' => $wday,
                   4856:              'dayyear' => $dt->day_of_year(),
                   4857:              'dlsav'   => $dt->is_dst() );
1.51      www      4858: }
                   4859: 
1.370     www      4860: sub utc_string {
                   4861:     my ($date)=@_;
1.371     www      4862:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4863: }
                   4864: 
1.51      www      4865: sub maketime {
                   4866:     my %th=@_;
1.687     raeburn  4867:     my ($epoch_time,$timezone,$dt);
                   4868:     $timezone = &Apache::lonlocal::gettimezone();
                   4869:     eval {
                   4870:         $dt = DateTime->new( year   => $th{'year'},
                   4871:                              month  => $th{'month'},
                   4872:                              day    => $th{'day'},
                   4873:                              hour   => $th{'hour'},
                   4874:                              minute => $th{'minute'},
                   4875:                              second => $th{'second'},
                   4876:                              time_zone => $timezone,
                   4877:                          );
                   4878:     };
                   4879:     if (!$@) {
                   4880:         $epoch_time = $dt->epoch;
                   4881:         if ($epoch_time) {
                   4882:             return $epoch_time;
                   4883:         }
                   4884:     }
1.51      www      4885:     return POSIX::mktime(
                   4886:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4887:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4888: }
                   4889: 
                   4890: #########################################
1.51      www      4891: 
                   4892: sub findallcourses {
1.482     raeburn  4893:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4894:     my %roles;
                   4895:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4896:     my %courses;
1.51      www      4897:     my $now=time;
1.482     raeburn  4898:     if (!defined($uname)) {
                   4899:         $uname = $env{'user.name'};
                   4900:     }
                   4901:     if (!defined($udom)) {
                   4902:         $udom = $env{'user.domain'};
                   4903:     }
                   4904:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4905:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4906:         if (!%roles) {
                   4907:             %roles = (
                   4908:                        cc => 1,
1.907     raeburn  4909:                        co => 1,
1.482     raeburn  4910:                        in => 1,
                   4911:                        ep => 1,
                   4912:                        ta => 1,
                   4913:                        cr => 1,
                   4914:                        st => 1,
                   4915:              );
                   4916:         }
                   4917:         foreach my $entry (keys(%roleshash)) {
                   4918:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4919:             if ($trole =~ /^cr/) { 
                   4920:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4921:             } else {
                   4922:                 next if (!exists($roles{$trole}));
                   4923:             }
                   4924:             if ($tend) {
                   4925:                 next if ($tend < $now);
                   4926:             }
                   4927:             if ($tstart) {
                   4928:                 next if ($tstart > $now);
                   4929:             }
1.1058    raeburn  4930:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4931:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4932:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4933:             if ($secpart eq '') {
                   4934:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4935:                 $sec = 'none';
1.1058    raeburn  4936:                 $value .= $cnum.'/';
1.482     raeburn  4937:             } else {
                   4938:                 $cnum = $cnumpart;
                   4939:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4940:                 $value .= $cnum.'/'.$sec;
                   4941:             }
                   4942:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4943:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4944:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4945:                 }
                   4946:             } else {
                   4947:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4948:             }
1.482     raeburn  4949:         }
                   4950:     } else {
                   4951:         foreach my $key (keys(%env)) {
1.483     albertel 4952: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4953:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4954: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4955: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4956: 	        next if (%roles && !exists($roles{$role}));
                   4957: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4958:                 my $active=1;
                   4959:                 if ($starttime) {
                   4960: 		    if ($now<$starttime) { $active=0; }
                   4961:                 }
                   4962:                 if ($endtime) {
                   4963:                     if ($now>$endtime) { $active=0; }
                   4964:                 }
                   4965:                 if ($active) {
1.1058    raeburn  4966:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4967:                     if ($sec eq '') {
                   4968:                         $sec = 'none';
1.1058    raeburn  4969:                     } else {
                   4970:                         $value .= $sec;
                   4971:                     }
                   4972:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4973:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4974:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4975:                         }
                   4976:                     } else {
                   4977:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4978:                     }
1.474     raeburn  4979:                 }
                   4980:             }
1.51      www      4981:         }
                   4982:     }
1.474     raeburn  4983:     return %courses;
1.51      www      4984: }
1.37      matthew  4985: 
1.54      www      4986: ###############################################
1.474     raeburn  4987: 
                   4988: sub blockcheck {
1.1075.2.158  raeburn  4989:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4990: 
1.1075.2.161.  .4(raebu 4991:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  4992:         my ($has_evb,$check_ipaccess);
                   4993:         my $dom = $env{'user.domain'};
                   4994:         if ($env{'request.course.id'}) {
                   4995:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4996:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4997:             my $checkrole = "cm./$cdom/$cnum";
                   4998:             my $sec = $env{'request.course.sec'};
                   4999:             if ($sec ne '') {
                   5000:                 $checkrole .= "/$sec";
                   5001:             }
                   5002:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5003:                 ($env{'request.role'} !~ /^st/)) {
                   5004:                 $has_evb = 1;
                   5005:             }
                   5006:             unless ($has_evb) {
                   5007:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5008:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5009:                     if ($udom eq $cdom) {
                   5010:                         $check_ipaccess = 1;
                   5011:                     }
                   5012:                 }
                   5013:             }
1.1075.2.161.  .3(raebu 5014:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5015:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5016:22):             my $checkrole;
                   5017:22):             if ($env{'request.role.domain'} eq '') {
                   5018:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   5019:22):             } else {
                   5020:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5021:22):             }
                   5022:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5023:22):                 $has_evb = 1;
                   5024:22):             }
1.1075.2.158  raeburn  5025:         }
                   5026:         unless ($has_evb || $check_ipaccess) {
                   5027:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5028:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5029:                 $dom = $udom;
                   5030:             }
                   5031:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5032:                 $check_ipaccess = 1;
                   5033:             } else {
                   5034:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5035:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5036:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5037:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5038:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5039:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5040:                         $check_ipaccess = 1;
                   5041:                     }
                   5042:                 }
                   5043:             }
                   5044:         }
                   5045:         if ($check_ipaccess) {
                   5046:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5047:             unless (defined($cached)) {
                   5048:                 my %domconfig =
                   5049:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5050:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5051:             }
                   5052:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5053:                 foreach my $id (keys(%{$ipaccessref})) {
                   5054:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5055:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5056:                         if ($range) {
                   5057:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5058:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5059:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5060:                                         return ('','','',$id,$dom);
                   5061:                                         last;
                   5062:                                     }
                   5063:                                 }
                   5064:                             }
                   5065:                         }
                   5066:                     }
                   5067:                 }
                   5068:             }
                   5069:         }
1.1075.2.161.  .4(raebu 5070:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5071:22):             return ();
                   5072:22):         }
1.1075.2.158  raeburn  5073:     }
1.1075.2.73  raeburn  5074:     if (defined($udom) && defined($uname)) {
                   5075:         # If uname and udom are for a course, check for blocks in the course.
                   5076:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5077:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5078:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5079:             return ($startblock,$endblock,$triggerblock);
                   5080:         }
                   5081:     } else {
1.490     raeburn  5082:         $udom = $env{'user.domain'};
                   5083:         $uname = $env{'user.name'};
                   5084:     }
                   5085: 
1.502     raeburn  5086:     my $startblock = 0;
                   5087:     my $endblock = 0;
1.1062    raeburn  5088:     my $triggerblock = '';
1.1075.2.160  raeburn  5089:     my %live_courses;
                   5090:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5091:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5092:     }
1.474     raeburn  5093: 
1.490     raeburn  5094:     # If uname is for a user, and activity is course-specific, i.e.,
                   5095:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5096: 
1.490     raeburn  5097:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5098:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5099:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5100:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5101:         foreach my $key (keys(%live_courses)) {
                   5102:             if ($key ne $env{'request.course.id'}) {
                   5103:                 delete($live_courses{$key});
                   5104:             }
                   5105:         }
                   5106:     }
                   5107: 
                   5108:     my $otheruser = 0;
                   5109:     my %own_courses;
                   5110:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5111:         # Resource belongs to user other than current user.
                   5112:         $otheruser = 1;
                   5113:         # Gather courses for current user
                   5114:         %own_courses = 
                   5115:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5116:     }
                   5117: 
                   5118:     # Gather active course roles - course coordinator, instructor, 
                   5119:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5120: 
                   5121:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5122:         my ($cdom,$cnum);
                   5123:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5124:             $cdom = $env{'course.'.$course.'.domain'};
                   5125:             $cnum = $env{'course.'.$course.'.num'};
                   5126:         } else {
1.490     raeburn  5127:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5128:         }
                   5129:         my $no_ownblock = 0;
                   5130:         my $no_userblock = 0;
1.533     raeburn  5131:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5132:             # Check if current user has 'evb' priv for this
                   5133:             if (defined($own_courses{$course})) {
                   5134:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5135:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5136:                     if ($sec ne 'none') {
                   5137:                         $checkrole .= '/'.$sec;
                   5138:                     }
                   5139:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5140:                         $no_ownblock = 1;
                   5141:                         last;
                   5142:                     }
                   5143:                 }
                   5144:             }
                   5145:             # if they have 'evb' priv and are currently not playing student
                   5146:             next if (($no_ownblock) &&
                   5147:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5148:         }
1.474     raeburn  5149:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5150:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5151:             if ($sec ne 'none') {
1.482     raeburn  5152:                 $checkrole .= '/'.$sec;
1.474     raeburn  5153:             }
1.490     raeburn  5154:             if ($otheruser) {
                   5155:                 # Resource belongs to user other than current user.
                   5156:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5157:                 my (%allroles,%userroles);
                   5158:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5159:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5160:                         my ($trole,$tdom,$tnum,$tsec);
                   5161:                         if ($entry =~ /^cr/) {
                   5162:                             ($trole,$tdom,$tnum,$tsec) = 
                   5163:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5164:                         } else {
                   5165:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5166:                         }
                   5167:                         my ($spec,$area,$trest);
                   5168:                         $area = '/'.$tdom.'/'.$tnum;
                   5169:                         $trest = $tnum;
                   5170:                         if ($tsec ne '') {
                   5171:                             $area .= '/'.$tsec;
                   5172:                             $trest .= '/'.$tsec;
                   5173:                         }
                   5174:                         $spec = $trole.'.'.$area;
                   5175:                         if ($trole =~ /^cr/) {
                   5176:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5177:                                                               $tdom,$spec,$trest,$area);
                   5178:                         } else {
                   5179:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5180:                                                                 $tdom,$spec,$trest,$area);
                   5181:                         }
                   5182:                     }
1.1075.2.124  raeburn  5183:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5184:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5185:                         if ($1) {
                   5186:                             $no_userblock = 1;
                   5187:                             last;
                   5188:                         }
1.486     raeburn  5189:                     }
                   5190:                 }
1.490     raeburn  5191:             } else {
                   5192:                 # Resource belongs to current user
                   5193:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5194:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5195:                     $no_ownblock = 1;
                   5196:                     last;
                   5197:                 }
1.474     raeburn  5198:             }
                   5199:         }
                   5200:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5201:         next if (($no_ownblock) &&
1.491     albertel 5202:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5203:         next if ($no_userblock);
1.474     raeburn  5204: 
1.1075.2.128  raeburn  5205:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5206:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5207:         
1.1062    raeburn  5208:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5209:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5210:         if (($start != 0) && 
                   5211:             (($startblock == 0) || ($startblock > $start))) {
                   5212:             $startblock = $start;
1.1062    raeburn  5213:             if ($trigger ne '') {
                   5214:                 $triggerblock = $trigger;
                   5215:             }
1.502     raeburn  5216:         }
                   5217:         if (($end != 0)  &&
                   5218:             (($endblock == 0) || ($endblock < $end))) {
                   5219:             $endblock = $end;
1.1062    raeburn  5220:             if ($trigger ne '') {
                   5221:                 $triggerblock = $trigger;
                   5222:             }
1.502     raeburn  5223:         }
1.490     raeburn  5224:     }
1.1062    raeburn  5225:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5226: }
                   5227: 
                   5228: sub get_blocks {
1.1075.2.147  raeburn  5229:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5230:     my $startblock = 0;
                   5231:     my $endblock = 0;
1.1062    raeburn  5232:     my $triggerblock = '';
1.490     raeburn  5233:     my $course = $cdom.'_'.$cnum;
                   5234:     $setters->{$course} = {};
                   5235:     $setters->{$course}{'staff'} = [];
                   5236:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5237:     $setters->{$course}{'triggers'} = [];
                   5238:     my (@blockers,%triggered);
                   5239:     my $now = time;
                   5240:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5241:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5242:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5243:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5244:             $blocked = 1;
                   5245:             $nosymbcache = 1;
1.1075.2.148  raeburn  5246:             $noenccheck = 1;
1.1075.2.147  raeburn  5247:         }
1.1075.2.148  raeburn  5248:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5249:         foreach my $block (@blockers) {
                   5250:             if ($block =~ /^firstaccess____(.+)$/) {
                   5251:                 my $item = $1;
                   5252:                 my $type = 'map';
                   5253:                 my $timersymb = $item;
                   5254:                 if ($item eq 'course') {
                   5255:                     $type = 'course';
                   5256:                 } elsif ($item =~ /___\d+___/) {
                   5257:                     $type = 'resource';
                   5258:                 } else {
                   5259:                     $timersymb = &Apache::lonnet::symbread($item);
                   5260:                 }
                   5261:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5262:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5263:                 $triggered{$block} = {
                   5264:                                        start => $start,
                   5265:                                        end   => $end,
                   5266:                                        type  => $type,
                   5267:                                      };
                   5268:             }
                   5269:         }
                   5270:     } else {
                   5271:         foreach my $block (keys(%commblocks)) {
                   5272:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5273:                 my ($start,$end) = ($1,$2);
                   5274:                 if ($start <= time && $end >= time) {
                   5275:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5276:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5277:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5278:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5279:                                     push(@blockers,$block);
                   5280:                                 }
                   5281:                             }
                   5282:                         }
                   5283:                     }
                   5284:                 }
                   5285:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5286:                 my $item = $1;
                   5287:                 my $timersymb = $item; 
                   5288:                 my $type = 'map';
                   5289:                 if ($item eq 'course') {
                   5290:                     $type = 'course';
                   5291:                 } elsif ($item =~ /___\d+___/) {
                   5292:                     $type = 'resource';
                   5293:                 } else {
                   5294:                     $timersymb = &Apache::lonnet::symbread($item);
                   5295:                 }
                   5296:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5297:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5298:                 if ($start && $end) {
                   5299:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5300:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5301:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5302:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5303:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5304:                                         push(@blockers,$block);
                   5305:                                         $triggered{$block} = {
                   5306:                                                                start => $start,
                   5307:                                                                end   => $end,
                   5308:                                                                type  => $type,
                   5309:                                                              };
                   5310:                                     }
                   5311:                                 }
                   5312:                             }
1.1062    raeburn  5313:                         }
                   5314:                     }
1.490     raeburn  5315:                 }
1.1062    raeburn  5316:             }
                   5317:         }
                   5318:     }
                   5319:     foreach my $blocker (@blockers) {
                   5320:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5321:             &parse_block_record($commblocks{$blocker});
                   5322:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5323:         my ($start,$end,$triggertype);
                   5324:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5325:             ($start,$end) = ($1,$2);
                   5326:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5327:             $start = $triggered{$blocker}{'start'};
                   5328:             $end = $triggered{$blocker}{'end'};
                   5329:             $triggertype = $triggered{$blocker}{'type'};
                   5330:         }
                   5331:         if ($start) {
                   5332:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5333:             if ($triggertype) {
                   5334:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5335:             } else {
                   5336:                 push(@{$$setters{$course}{'triggers'}},0);
                   5337:             }
                   5338:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5339:                 $startblock = $start;
                   5340:                 if ($triggertype) {
                   5341:                     $triggerblock = $blocker;
1.474     raeburn  5342:                 }
                   5343:             }
1.1062    raeburn  5344:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5345:                $endblock = $end;
                   5346:                if ($triggertype) {
                   5347:                    $triggerblock = $blocker;
                   5348:                }
                   5349:             }
1.474     raeburn  5350:         }
                   5351:     }
1.1062    raeburn  5352:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5353: }
                   5354: 
                   5355: sub parse_block_record {
                   5356:     my ($record) = @_;
                   5357:     my ($setuname,$setudom,$title,$blocks);
                   5358:     if (ref($record) eq 'HASH') {
                   5359:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5360:         $title = &unescape($record->{'event'});
                   5361:         $blocks = $record->{'blocks'};
                   5362:     } else {
                   5363:         my @data = split(/:/,$record,3);
                   5364:         if (scalar(@data) eq 2) {
                   5365:             $title = $data[1];
                   5366:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5367:         } else {
                   5368:             ($setuname,$setudom,$title) = @data;
                   5369:         }
                   5370:         $blocks = { 'com' => 'on' };
                   5371:     }
                   5372:     return ($setuname,$setudom,$title,$blocks);
                   5373: }
                   5374: 
1.854     kalberla 5375: sub blocking_status {
1.1075.2.158  raeburn  5376:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5377:     my %setters;
1.890     droeschl 5378: 
1.1061    raeburn  5379: # check for active blocking
1.1075.2.158  raeburn  5380:     if ($clientip eq '') {
                   5381:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5382:     }
                   5383:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5384:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5385:     my $blocked = 0;
1.1075.2.158  raeburn  5386:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5387:         $blocked = 1;
                   5388:     }
1.890     droeschl 5389: 
1.1061    raeburn  5390: # caller just wants to know whether a block is active
                   5391:     if (!wantarray) { return $blocked; }
                   5392: 
                   5393: # build a link to a popup window containing the details
                   5394:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5395: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5396:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5397:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5398:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5399:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5400:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5401:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5402:         if ($symb) {
                   5403:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5404:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5405:         }
1.1062    raeburn  5406:     }
1.1061    raeburn  5407: 
                   5408:     my $output .= <<'END_MYBLOCK';
                   5409: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5410:     var options = "width=" + w + ",height=" + h + ",";
                   5411:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5412:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5413:     var newWin = window.open(url, wdwName, options);
                   5414:     newWin.focus();
                   5415: }
1.890     droeschl 5416: END_MYBLOCK
1.854     kalberla 5417: 
1.1061    raeburn  5418:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5419:   
1.1061    raeburn  5420:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5421:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5422:     my $class = 'LC_comblock';
1.1062    raeburn  5423:     if ($activity eq 'docs') {
                   5424:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5425:         $class = '';
1.1063    raeburn  5426:     } elsif ($activity eq 'printout') {
                   5427:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5428:     } elsif ($activity eq 'passwd') {
                   5429:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5430:     } elsif ($activity eq 'grades') {
                   5431:         $text = &mt('Gradebook Blocked');
                   5432:     } elsif ($activity eq 'search') {
                   5433:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5434:21):     } elsif ($activity eq 'alert') {
                   5435:21):         $text = &mt('Checking Critical Messages Blocked');
                   5436:21):     } elsif ($activity eq 'reinit') {
                   5437:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5438:     } elsif ($activity eq 'about') {
                   5439:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5440:     } elsif ($activity eq 'wishlist') {
                   5441:         $text = &mt('Access to Stored Links Blocked');
                   5442:     } elsif ($activity eq 'annotate') {
                   5443:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5444:     }
1.1061    raeburn  5445:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5446: <div class='$class'>
1.869     kalberla 5447:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5448:   title='$text'>
                   5449:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5450:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5451:   title='$text'>$text</a>
1.867     kalberla 5452: </div>
                   5453: 
                   5454: END_BLOCK
1.474     raeburn  5455: 
1.1061    raeburn  5456:     return ($blocked, $output);
1.854     kalberla 5457: }
1.490     raeburn  5458: 
1.60      matthew  5459: ###############################################
                   5460: 
1.682     raeburn  5461: sub check_ip_acc {
1.1075.2.105  raeburn  5462:     my ($acc,$clientip)=@_;
1.682     raeburn  5463:     &Apache::lonxml::debug("acc is $acc");
                   5464:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5465:         return 1;
                   5466:     }
                   5467:     my $allowed=0;
1.1075.2.144  raeburn  5468:     my $ip;
                   5469:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5470:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5471:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5472:     } else {
1.1075.2.150  raeburn  5473:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5474:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5475:     }
1.682     raeburn  5476: 
                   5477:     my $name;
1.1075.2.161.  .1(raebu 5478:21):     my %access = (
                   5479:21):                      allowfrom => 1,
                   5480:21):                      denyfrom  => 0,
                   5481:21):                  );
                   5482:21):     my @allows;
                   5483:21):     my @denies;
                   5484:21):     foreach my $item (split(',',$acc)) {
                   5485:21):         $item =~ s/^\s*//;
                   5486:21):         $item =~ s/\s*$//;
                   5487:21):         if ($item =~ /^\!(.+)$/) {
                   5488:21):             push(@denies,$1);
                   5489:21):         } else {
                   5490:21):             push(@allows,$item);
                   5491:21):         }
                   5492:21):     }
                   5493:21):     my $numdenies = scalar(@denies);
                   5494:21):     my $numallows = scalar(@allows);
                   5495:21):     my $count = 0;
                   5496:21):     foreach my $pattern (@denies,@allows) {
                   5497:21):         $count ++;
                   5498:21):         my $acctype = 'allowfrom';
                   5499:21):         if ($count <= $numdenies) {
                   5500:21):             $acctype = 'denyfrom';
                   5501:21):         }
1.682     raeburn  5502:         if ($pattern =~ /\*$/) {
                   5503:             #35.8.*
                   5504:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5505:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5506:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5507:             #35.8.3.[34-56]
                   5508:             my $low=$2;
                   5509:             my $high=$3;
                   5510:             $pattern=$1;
                   5511:             if ($ip =~ /^\Q$pattern\E/) {
                   5512:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5513:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5514:             }
                   5515:         } elsif ($pattern =~ /^\*/) {
                   5516:             #*.msu.edu
                   5517:             $pattern=~s/\*//;
                   5518:             if (!defined($name)) {
                   5519:                 use Socket;
                   5520:                 my $netaddr=inet_aton($ip);
                   5521:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5522:             }
1.1075.2.161.  .1(raebu 5523:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5524:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5525:             #127.0.0.1
1.1075.2.161.  .1(raebu 5526:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5527:         } else {
                   5528:             #some.name.com
                   5529:             if (!defined($name)) {
                   5530:                 use Socket;
                   5531:                 my $netaddr=inet_aton($ip);
                   5532:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5533:             }
1.1075.2.161.  .1(raebu 5534:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5535:21):         }
                   5536:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5537:21):     }
                   5538:21):     if ($allowed eq '') {
                   5539:21):         if ($numdenies && !$numallows) {
                   5540:21):             $allowed = 1;
                   5541:21):         } else {
                   5542:21):             $allowed = 0;
1.682     raeburn  5543:         }
                   5544:     }
                   5545:     return $allowed;
                   5546: }
                   5547: 
                   5548: ###############################################
                   5549: 
1.60      matthew  5550: =pod
                   5551: 
1.112     bowersj2 5552: =head1 Domain Template Functions
                   5553: 
                   5554: =over 4
                   5555: 
                   5556: =item * &determinedomain()
1.60      matthew  5557: 
                   5558: Inputs: $domain (usually will be undef)
                   5559: 
1.63      www      5560: Returns: Determines which domain should be used for designs
1.60      matthew  5561: 
                   5562: =cut
1.54      www      5563: 
1.60      matthew  5564: ###############################################
1.63      www      5565: sub determinedomain {
                   5566:     my $domain=shift;
1.531     albertel 5567:     if (! $domain) {
1.60      matthew  5568:         # Determine domain if we have not been given one
1.893     raeburn  5569:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5570:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5571:         if ($env{'request.role.domain'}) { 
                   5572:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5573:         }
                   5574:     }
1.63      www      5575:     return $domain;
                   5576: }
                   5577: ###############################################
1.517     raeburn  5578: 
1.518     albertel 5579: sub devalidate_domconfig_cache {
                   5580:     my ($udom)=@_;
                   5581:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5582: }
                   5583: 
                   5584: # ---------------------- Get domain configuration for a domain
                   5585: sub get_domainconf {
                   5586:     my ($udom) = @_;
                   5587:     my $cachetime=1800;
                   5588:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5589:     if (defined($cached)) { return %{$result}; }
                   5590: 
                   5591:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5592: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5593:     my (%designhash,%legacy);
1.518     albertel 5594:     if (keys(%domconfig) > 0) {
                   5595:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5596:             if (keys(%{$domconfig{'login'}})) {
                   5597:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5598:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5599:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5600:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5601:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5602:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5603:                                         if ($key eq 'loginvia') {
                   5604:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5605:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5606:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5607:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5608:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5609:                                                 } else {
                   5610:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5611:                                                 }
1.948     raeburn  5612:                                             }
1.1075.2.87  raeburn  5613:                                         } elsif ($key eq 'headtag') {
                   5614:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5615:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5616:                                             }
1.946     raeburn  5617:                                         }
1.1075.2.87  raeburn  5618:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5619:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5620:                                         }
1.946     raeburn  5621:                                     }
                   5622:                                 }
                   5623:                             }
1.1075.2.158  raeburn  5624:                         } elsif ($key eq 'saml') {
                   5625:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5626:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5627:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5628:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5629:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5630:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5631:                                         }
                   5632:                                     }
                   5633:                                 }
                   5634:                             }
1.946     raeburn  5635:                         } else {
                   5636:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5637:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5638:                                     $domconfig{'login'}{$key}{$img};
                   5639:                             }
1.699     raeburn  5640:                         }
                   5641:                     } else {
                   5642:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5643:                     }
1.632     raeburn  5644:                 }
                   5645:             } else {
                   5646:                 $legacy{'login'} = 1;
1.518     albertel 5647:             }
1.632     raeburn  5648:         } else {
                   5649:             $legacy{'login'} = 1;
1.518     albertel 5650:         }
                   5651:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5652:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5653:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5654:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5655:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5656:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5657:                         }
1.518     albertel 5658:                     }
                   5659:                 }
1.632     raeburn  5660:             } else {
                   5661:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5662:             }
1.632     raeburn  5663:         } else {
                   5664:             $legacy{'rolecolors'} = 1;
1.518     albertel 5665:         }
1.948     raeburn  5666:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5667:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5668:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5669:             }
                   5670:         }
1.632     raeburn  5671:         if (keys(%legacy) > 0) {
                   5672:             my %legacyhash = &get_legacy_domconf($udom);
                   5673:             foreach my $item (keys(%legacyhash)) {
                   5674:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5675:                     if ($legacy{'login'}) { 
                   5676:                         $designhash{$item} = $legacyhash{$item};
                   5677:                     }
                   5678:                 } else {
                   5679:                     if ($legacy{'rolecolors'}) {
                   5680:                         $designhash{$item} = $legacyhash{$item};
                   5681:                     }
1.518     albertel 5682:                 }
                   5683:             }
                   5684:         }
1.632     raeburn  5685:     } else {
                   5686:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5687:     }
                   5688:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5689: 				  $cachetime);
                   5690:     return %designhash;
                   5691: }
                   5692: 
1.632     raeburn  5693: sub get_legacy_domconf {
                   5694:     my ($udom) = @_;
                   5695:     my %legacyhash;
                   5696:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5697:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5698:     if (-e $designfile) {
1.1075.2.128  raeburn  5699:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5700:             while (my $line = <$fh>) {
                   5701:                 next if ($line =~ /^\#/);
                   5702:                 chomp($line);
                   5703:                 my ($key,$val)=(split(/\=/,$line));
                   5704:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5705:             }
                   5706:             close($fh);
                   5707:         }
                   5708:     }
1.1026    raeburn  5709:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5710:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5711:     }
                   5712:     return %legacyhash;
                   5713: }
                   5714: 
1.63      www      5715: =pod
                   5716: 
1.112     bowersj2 5717: =item * &domainlogo()
1.63      www      5718: 
                   5719: Inputs: $domain (usually will be undef)
                   5720: 
                   5721: Returns: A link to a domain logo, if the domain logo exists.
                   5722: If the domain logo does not exist, a description of the domain.
                   5723: 
                   5724: =cut
1.112     bowersj2 5725: 
1.63      www      5726: ###############################################
                   5727: sub domainlogo {
1.517     raeburn  5728:     my $domain = &determinedomain(shift);
1.518     albertel 5729:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5730:     # See if there is a logo
                   5731:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5732:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5733:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5734: 	    if ($imgsrc =~ m{^/res/}) {
                   5735: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5736: 		&Apache::lonnet::repcopy($local_name);
                   5737: 	    }
                   5738: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5739:22):         }
                   5740:22):         my $alttext = $domain;
                   5741:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5742:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5743:22):         }
                   5744:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5745:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5746:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5747:     } else {
1.60      matthew  5748:         return '';
1.59      www      5749:     }
                   5750: }
1.63      www      5751: ##############################################
                   5752: 
                   5753: =pod
                   5754: 
1.112     bowersj2 5755: =item * &designparm()
1.63      www      5756: 
                   5757: Inputs: $which parameter; $domain (usually will be undef)
                   5758: 
                   5759: Returns: value of designparamter $which
                   5760: 
                   5761: =cut
1.112     bowersj2 5762: 
1.397     albertel 5763: 
1.400     albertel 5764: ##############################################
1.397     albertel 5765: sub designparm {
                   5766:     my ($which,$domain)=@_;
                   5767:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5768:         return $env{'environment.color.'.$which};
1.96      www      5769:     }
1.63      www      5770:     $domain=&determinedomain($domain);
1.1016    raeburn  5771:     my %domdesign;
                   5772:     unless ($domain eq 'public') {
                   5773:         %domdesign = &get_domainconf($domain);
                   5774:     }
1.520     raeburn  5775:     my $output;
1.517     raeburn  5776:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5777:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5778:     } else {
1.520     raeburn  5779:         $output = $defaultdesign{$which};
                   5780:     }
                   5781:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5782:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5783:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5784:             if ($output =~ m{^/res/}) {
                   5785:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5786:                 &Apache::lonnet::repcopy($local_name);
                   5787:             }
1.520     raeburn  5788:             $output = &lonhttpdurl($output);
                   5789:         }
1.63      www      5790:     }
1.520     raeburn  5791:     return $output;
1.63      www      5792: }
1.59      www      5793: 
1.822     bisitz   5794: ##############################################
                   5795: =pod
                   5796: 
1.832     bisitz   5797: =item * &authorspace()
                   5798: 
1.1028    raeburn  5799: Inputs: $url (usually will be undef).
1.832     bisitz   5800: 
1.1075.2.40  raeburn  5801: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5802:          directory being viewed (or for which action is being taken). 
                   5803:          If $url is provided, and begins /priv/<domain>/<uname>
                   5804:          the path will be that portion of the $context argument.
                   5805:          Otherwise the path will be for the author space of the current
                   5806:          user when the current role is author, or for that of the 
                   5807:          co-author/assistant co-author space when the current role 
                   5808:          is co-author or assistant co-author.
1.832     bisitz   5809: 
                   5810: =cut
                   5811: 
                   5812: sub authorspace {
1.1028    raeburn  5813:     my ($url) = @_;
                   5814:     if ($url ne '') {
                   5815:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5816:            return $1;
                   5817:         }
                   5818:     }
1.832     bisitz   5819:     my $caname = '';
1.1024    www      5820:     my $cadom = '';
1.1028    raeburn  5821:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5822:         ($cadom,$caname) =
1.832     bisitz   5823:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5824:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5825:         $caname = $env{'user.name'};
1.1024    www      5826:         $cadom = $env{'user.domain'};
1.832     bisitz   5827:     }
1.1028    raeburn  5828:     if (($caname ne '') && ($cadom ne '')) {
                   5829:         return "/priv/$cadom/$caname/";
                   5830:     }
                   5831:     return;
1.832     bisitz   5832: }
                   5833: 
                   5834: ##############################################
                   5835: =pod
                   5836: 
1.822     bisitz   5837: =item * &head_subbox()
                   5838: 
                   5839: Inputs: $content (contains HTML code with page functions, etc.)
                   5840: 
                   5841: Returns: HTML div with $content
                   5842:          To be included in page header
                   5843: 
                   5844: =cut
                   5845: 
                   5846: sub head_subbox {
                   5847:     my ($content)=@_;
                   5848:     my $output =
1.993     raeburn  5849:         '<div class="LC_head_subbox">'
1.822     bisitz   5850:        .$content
                   5851:        .'</div>'
                   5852: }
                   5853: 
                   5854: ##############################################
                   5855: =pod
                   5856: 
                   5857: =item * &CSTR_pageheader()
                   5858: 
1.1026    raeburn  5859: Input: (optional) filename from which breadcrumb trail is built.
                   5860:        In most cases no input as needed, as $env{'request.filename'}
                   5861:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5862:22):        frameset flag
                   5863:22):        If page header is being requested for use in a frameset, then
                   5864:22):        the second (option) argument -- frameset will be true, and
                   5865:22):        the target attribute set for links should be target="_parent".
1.822     bisitz   5866: 
                   5867: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5868:          To be included on Authoring Space pages
1.822     bisitz   5869: 
                   5870: =cut
                   5871: 
                   5872: sub CSTR_pageheader {
1.1075.2.161.  .6(raebu 5873:22):     my ($trailfile,$frameset) = @_;
1.1026    raeburn  5874:     if ($trailfile eq '') {
                   5875:         $trailfile = $env{'request.filename'};
                   5876:     }
                   5877: 
                   5878: # this is for resources; directories have customtitle, and crumbs
                   5879: # and select recent are created in lonpubdir.pm
                   5880: 
                   5881:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5882:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5883:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5884:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5885:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5886: 
                   5887:     my $parentpath = '';
                   5888:     my $lastitem = '';
                   5889:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5890:         $parentpath = $1;
                   5891:         $lastitem = $2;
                   5892:     } else {
                   5893:         $lastitem = $thisdisfn;
                   5894:     }
1.921     bisitz   5895: 
1.1075.2.161.  .6(raebu 5896:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   5897:22):     if ($frameset) {
                   5898:22):         $target = ' target="_parent"';
                   5899:22):         $crumbtarget = '_parent';
          .17(raeb 5900:-23):     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   5901:-23):         $target = '';
                   5902:-23):         $crumbtarget = '';
          .6(raebu 5903:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   5904:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   5905:22):         $crumbtarget = $env{'request.deeplink.target'};
                   5906:22):     }
                   5907:22): 
1.921     bisitz   5908:     my $output =
1.822     bisitz   5909:          '<div>'
                   5910:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5911:         .'<b>'.&mt('Authoring Space:').'</b> '
1.1075.2.161.  .6(raebu 5912:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5913:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5914: 
                   5915:     if ($lastitem) {
                   5916:         $output .=
                   5917:              '<span class="LC_filename">'
                   5918:             .$lastitem
                   5919:             .'</span>';
                   5920:     }
                   5921:     $output .=
                   5922:          '<br />'
1.1075.2.161.  .6(raebu 5923:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   5924:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5925:         .'</form>'
1.1075.2.161.  .6(raebu 5926:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   5927:         .'</div>';
1.921     bisitz   5928: 
                   5929:     return $output;
1.822     bisitz   5930: }
                   5931: 
1.60      matthew  5932: ###############################################
                   5933: ###############################################
                   5934: 
                   5935: =pod
                   5936: 
1.112     bowersj2 5937: =back
                   5938: 
1.549     albertel 5939: =head1 HTML Helpers
1.112     bowersj2 5940: 
                   5941: =over 4
                   5942: 
                   5943: =item * &bodytag()
1.60      matthew  5944: 
                   5945: Returns a uniform header for LON-CAPA web pages.
                   5946: 
                   5947: Inputs: 
                   5948: 
1.112     bowersj2 5949: =over 4
                   5950: 
                   5951: =item * $title, A title to be displayed on the page.
                   5952: 
                   5953: =item * $function, the current role (can be undef).
                   5954: 
                   5955: =item * $addentries, extra parameters for the <body> tag.
                   5956: 
                   5957: =item * $bodyonly, if defined, only return the <body> tag.
                   5958: 
                   5959: =item * $domain, if defined, force a given domain.
                   5960: 
                   5961: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5962:             text interface only)
1.60      matthew  5963: 
1.814     bisitz   5964: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5965:                      navigational links
1.317     albertel 5966: 
1.338     albertel 5967: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5968: 
1.1075.2.12  raeburn  5969: =item * $no_inline_link, if true and in remote mode, don't show the
                   5970:          'Switch To Inline Menu' link
                   5971: 
1.460     albertel 5972: =item * $args, optional argument valid values are
                   5973:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5974:             use_absolute     -> for external resource or syllabus, this will
                   5975:                                 contain https://<hostname> if server uses
                   5976:                                 https (as per hosts.tab), but request is for http
                   5977:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5978: 
1.1075.2.15  raeburn  5979: =item * $advtoolsref, optional argument, ref to an array containing
                   5980:             inlineremote items to be added in "Functions" menu below
                   5981:             breadcrumbs.
                   5982: 
1.1075.2.161.  .1(raebu 5983:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   5984:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   5985:21):             the scope of use, i.e., launch was for access to a single, a map
                   5986:21):             or the entire course.
                   5987:21): 
                   5988:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   5989:21):             context, this will contain the URL for the landing item in
                   5990:21):             the course, after launch from an LTI Consumer
                   5991:21): 
                   5992:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   5993:21):             context, this will contain a reference to hash of items
                   5994:21):             to be included in the page header and/or inline menu.
                   5995:21): 
          .8(raebu 5996:22): =item * $menucoll, optional argument, if specific menu collection is in
                   5997:22):             effect, either set as the default for the course, or set for
                   5998:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   5999:22):             then $menucoll will be the number of that collection.
                   6000:22): 
                   6001:22): =item * $menuref, optional argument, reference to a hash, containing the
                   6002:22):             menu options included for the menu in effect, based on the
                   6003:22):             configuration for the numbered menu collection in use.
                   6004:22): 
                   6005:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6006:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6007:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   6008:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6009:22):             being called a second time.
                   6010:22): 
1.112     bowersj2 6011: =back
                   6012: 
1.60      matthew  6013: Returns: A uniform header for LON-CAPA web pages.  
                   6014: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6015: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6016: other decorations will be returned.
                   6017: 
                   6018: =cut
                   6019: 
1.54      www      6020: sub bodytag {
1.831     bisitz   6021:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 6022:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 6023:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6024: 
1.954     raeburn  6025:     my $public;
                   6026:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6027:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6028:         $public = 1;
                   6029:     }
1.460     albertel 6030:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  6031:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  6032:     my $hostname = $args->{'hostname'};
1.339     albertel 6033: 
1.183     matthew  6034:     $function = &get_users_function() if (!$function);
1.339     albertel 6035:     my $img =    &designparm($function.'.img',$domain);
                   6036:     my $font =   &designparm($function.'.font',$domain);
                   6037:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6038: 
1.803     bisitz   6039:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6040: 		   'bgcolor' => $pgbg,
1.339     albertel 6041: 		   'text'    => $font,
                   6042:                    'alink'   => &designparm($function.'.alink',$domain),
                   6043: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6044: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6045:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6046: 
1.63      www      6047:  # role and realm
1.1075.2.68  raeburn  6048:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6049:     if ($realm) {
                   6050:         $realm = '/'.$realm;
                   6051:     }
1.1075.2.159  raeburn  6052:     if ($role eq 'ca') {
1.479     albertel 6053:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6054:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6055:     } 
1.55      www      6056: # realm
1.1075.2.158  raeburn  6057:     my ($cid,$sec);
1.258     albertel 6058:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  6059:         $cid = $env{'request.course.id'};
                   6060:         if ($env{'request.course.sec'}) {
                   6061:             $sec = $env{'request.course.sec'};
                   6062:         }
                   6063:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6064:         if (&Apache::lonnet::is_course($1,$2)) {
                   6065:             $cid = $1.'_'.$2;
                   6066:             $sec = $3;
                   6067:         }
                   6068:     }
                   6069:     if ($cid) {
1.378     raeburn  6070:         if ($env{'request.role'} !~ /^cr/) {
                   6071:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6072:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6073:             if ($env{'request.role.desc'}) {
                   6074:                 $role = $env{'request.role.desc'};
                   6075:             } else {
                   6076:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6077:             }
1.1075.2.115  raeburn  6078:         } else {
                   6079:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6080:         }
1.1075.2.158  raeburn  6081:         if ($sec) {
                   6082:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6083:         }   
1.1075.2.158  raeburn  6084: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6085:     } else {
                   6086:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6087:     }
1.433     albertel 6088: 
1.359     albertel 6089:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6090: 
1.438     albertel 6091:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6092: 
1.101     www      6093: # construct main body tag
1.359     albertel 6094:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6095: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6096: 
1.1075.2.38  raeburn  6097:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6098: 
                   6099:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6100:         return $bodytag;
1.1075.2.38  raeburn  6101:     }
1.359     albertel 6102: 
1.954     raeburn  6103:     if ($public) {
1.433     albertel 6104: 	undef($role);
                   6105:     }
1.1075.2.158  raeburn  6106: 
1.1075.2.161.  .1(raebu 6107:21):     my $showcrstitle = 1;
                   6108:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6109:21):         if (ref($ltimenu) eq 'HASH') {
                   6110:21):             unless ($ltimenu->{'role'}) {
                   6111:21):                 undef($role);
                   6112:21):             }
                   6113:21):             unless ($ltimenu->{'coursetitle'}) {
                   6114:21):                 $realm='&nbsp;';
                   6115:21):                 $showcrstitle = 0;
                   6116:21):             }
                   6117:21):         }
                   6118:21):     } elsif (($cid) && ($menucoll)) {
                   6119:21):         if (ref($menuref) eq 'HASH') {
                   6120:21):             unless ($menuref->{'role'}) {
                   6121:21):                 undef($role);
                   6122:21):             }
                   6123:21):             unless ($menuref->{'crs'}) {
                   6124:21):                 $realm='&nbsp;';
                   6125:21):                 $showcrstitle = 0;
                   6126:21):             }
                   6127:21):         }
                   6128:21):     }
                   6129:21): 
1.762     bisitz   6130:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6131:     #
                   6132:     # Extra info if you are the DC
                   6133:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6134:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6135:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6136:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6137:         $dc_info =~ s/\s+$//;
1.359     albertel 6138:     }
                   6139: 
1.1075.2.161.  .1(raebu 6140:21):     my $crstype;
                   6141:21):     if ($cid) {
                   6142:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6143:21):     } elsif ($args->{'crstype'}) {
                   6144:21):         $crstype = $args->{'crstype'};
                   6145:21):     }
                   6146:21): 
1.1075.2.108  raeburn  6147:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6148: 
1.1075.2.13  raeburn  6149:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6150: 
1.1075.2.38  raeburn  6151: 
                   6152: 
1.1075.2.21  raeburn  6153:     my $funclist;
                   6154:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  6155:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  6156:                     Apache::lonmenu::serverform();
                   6157:         my $forbodytag;
                   6158:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6159:                                             $forcereg,$args->{'group'},
                   6160:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6161:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  6162:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6163:             $funclist = $forbodytag;
                   6164:         }
                   6165:     } else {
1.903     droeschl 6166: 
                   6167:         #    if ($env{'request.state'} eq 'construct') {
                   6168:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6169:         #    }
                   6170: 
1.1075.2.38  raeburn  6171:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6172:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6173: 
1.1075.2.161.  .1(raebu 6174:21):         unless ($args->{'no_primary_menu'}) {
          .4(raebu 6175:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6176:22):                                                               $args->{'links_disabled'},
                   6177:22):                                                               $args->{'links_target'});
          .1(raebu 6178:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6179:21):                 if ($dc_info) {
                   6180:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6181:21):                 }
                   6182:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6183:21):                                <em>$realm</em> $dc_info</div>|;
                   6184:21):                 return $bodytag;
1.1075.2.1  raeburn  6185:             }
1.894     droeschl 6186: 
1.1075.2.161.  .1(raebu 6187:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6188:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6189:21):             }
1.916     droeschl 6190: 
1.1075.2.161.  .1(raebu 6191:21):             $bodytag .= $right;
1.852     droeschl 6192: 
1.1075.2.161.  .1(raebu 6193:21):             if ($dc_info) {
                   6194:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6195:21):             }
                   6196:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6197:         }
1.916     droeschl 6198: 
1.1075.2.61  raeburn  6199:         #if directed to not display the secondary menu, don't.
                   6200:         if ($args->{'no_secondary_menu'}) {
                   6201:             return $bodytag;
                   6202:         }
1.903     droeschl 6203:         #don't show menus for public users
1.954     raeburn  6204:         if (!$public){
1.1075.2.161.  .1(raebu 6205:21):             unless ($args->{'no_inline_menu'}) {
                   6206:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6207:21):                                                             $args->{'no_primary_menu'},
                   6208:21):                                                             $menucoll,$menuref,
          .6(raebu 6209:22):                                                             $args->{'links_disabled'},
                   6210:22):                                                             $args->{'links_target'});
          .1(raebu 6211:21):             }
1.903     droeschl 6212:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6213:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6214:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6215:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6216:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6217:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6218:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6219:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6220:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6221:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6222:             } else {
1.1075.2.21  raeburn  6223:                 my $forbodytag;
                   6224:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6225:                                                     $forcereg,$args->{'group'},
                   6226:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6227:                                                     $advtoolsref,'',$hostname,
                   6228:                                                     \$forbodytag);
1.1075.2.21  raeburn  6229:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6230:                     $bodytag .= $forbodytag;
                   6231:                 }
1.920     raeburn  6232:             }
1.903     droeschl 6233:         }else{
                   6234:             # this is to seperate menu from content when there's no secondary
                   6235:             # menu. Especially needed for public accessible ressources.
                   6236:             $bodytag .= '<hr style="clear:both" />';
                   6237:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6238:         }
1.903     droeschl 6239: 
1.235     raeburn  6240:         return $bodytag;
1.1075.2.12  raeburn  6241:     }
                   6242: 
                   6243: #
                   6244: # Top frame rendering, Remote is up
                   6245: #
                   6246: 
                   6247:     my $imgsrc = $img;
                   6248:     if ($img =~ /^\/adm/) {
                   6249:         $imgsrc = &lonhttpdurl($img);
                   6250:     }
                   6251:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   6252: 
1.1075.2.60  raeburn  6253:     my $help=($no_inline_link?''
                   6254:               :&Apache::loncommon::top_nav_help('Help'));
                   6255: 
1.1075.2.12  raeburn  6256:     # Explicit link to get inline menu
                   6257:     my $menu= ($no_inline_link?''
                   6258:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6259: 
                   6260:     if ($dc_info) {
                   6261:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6262:     }
                   6263: 
1.1075.2.38  raeburn  6264:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6265:     unless ($public) {
                   6266:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6267:                                 undef,'LC_menubuttons_link');
                   6268:     }
                   6269: 
1.1075.2.12  raeburn  6270:     unless ($env{'form.inhibitmenu'}) {
                   6271:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  6272:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  6273:                        <li>$help</li>
1.1075.2.12  raeburn  6274:                        <li>$menu</li>
                   6275:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6276:     }
1.1075.2.13  raeburn  6277:     if ($env{'request.state'} eq 'construct') {
                   6278:         if (!$public){
                   6279:             if ($env{'request.state'} eq 'construct') {
                   6280:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6281:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  6282:                             &Apache::lonhtmlcommon::scripttag('','end').
                   6283:                             &Apache::lonmenu::innerregister($forcereg,
                   6284:                                                             $args->{'bread_crumbs'});
                   6285:             }
                   6286:         }
                   6287:     }
1.1075.2.21  raeburn  6288:     return $bodytag."\n".$funclist;
1.182     matthew  6289: }
                   6290: 
1.917     raeburn  6291: sub dc_courseid_toggle {
                   6292:     my ($dc_info) = @_;
1.980     raeburn  6293:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6294:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6295:            &mt('(More ...)').'</a></span>'.
                   6296:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6297: }
                   6298: 
1.330     albertel 6299: sub make_attr_string {
                   6300:     my ($register,$attr_ref) = @_;
                   6301: 
                   6302:     if ($attr_ref && !ref($attr_ref)) {
                   6303: 	die("addentries Must be a hash ref ".
                   6304: 	    join(':',caller(1))." ".
                   6305: 	    join(':',caller(0))." ");
                   6306:     }
                   6307: 
                   6308:     if ($register) {
1.339     albertel 6309: 	my ($on_load,$on_unload);
                   6310: 	foreach my $key (keys(%{$attr_ref})) {
                   6311: 	    if      (lc($key) eq 'onload') {
                   6312: 		$on_load.=$attr_ref->{$key}.';';
                   6313: 		delete($attr_ref->{$key});
                   6314: 
                   6315: 	    } elsif (lc($key) eq 'onunload') {
                   6316: 		$on_unload.=$attr_ref->{$key}.';';
                   6317: 		delete($attr_ref->{$key});
                   6318: 	    }
                   6319: 	}
1.1075.2.12  raeburn  6320:         if ($env{'environment.remote'} eq 'on') {
                   6321:             $attr_ref->{'onload'}  =
                   6322:                 &Apache::lonmenu::loadevents().  $on_load;
                   6323:             $attr_ref->{'onunload'}=
                   6324:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6325:         } else {  
                   6326: 	    $attr_ref->{'onload'}  = $on_load;
                   6327: 	    $attr_ref->{'onunload'}= $on_unload;
                   6328:         }
1.330     albertel 6329:     }
1.339     albertel 6330: 
1.330     albertel 6331:     my $attr_string;
1.1075.2.56  raeburn  6332:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6333: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6334:     }
                   6335:     return $attr_string;
                   6336: }
                   6337: 
                   6338: 
1.182     matthew  6339: ###############################################
1.251     albertel 6340: ###############################################
                   6341: 
                   6342: =pod
                   6343: 
                   6344: =item * &endbodytag()
                   6345: 
                   6346: Returns a uniform footer for LON-CAPA web pages.
                   6347: 
1.635     raeburn  6348: Inputs: 1 - optional reference to an args hash
                   6349: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6350: a 'Continue' link is not displayed if the page contains an
                   6351: internal redirect in the <head></head> section,
                   6352: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6353: 
                   6354: =cut
                   6355: 
                   6356: sub endbodytag {
1.635     raeburn  6357:     my ($args) = @_;
1.1075.2.6  raeburn  6358:     my $endbodytag;
                   6359:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6360:         $endbodytag='</body>';
                   6361:     }
1.315     albertel 6362:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6363:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6364:22):             my ($endbodyjs,$idattr);
                   6365:22):             if ($env{'internal.head.to_opener'}) {
                   6366:22):                 my $linkid = 'LC_continue_link';
                   6367:22):                 $idattr = ' id="'.$linkid.'"';
                   6368:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6369:22):                 $endbodyjs=<<ENDJS;
                   6370:22): <script type="text/javascript">
                   6371:22): // <![CDATA[
                   6372:22): function ebFunction(evt) {
                   6373:22):     evt.preventDefault();
                   6374:22):     var dest = '$redirect_for_js';
                   6375:22):     if (window.opener != null && !window.opener.closed) {
                   6376:22):         window.opener.location.href=dest;
                   6377:22):         window.close();
                   6378:22):     } else {
                   6379:22):         window.location.href=dest;
                   6380:22):     }
                   6381:22):     return false;
                   6382:22): }
                   6383:22): 
                   6384:22): \$(document).ready(function () {
                   6385:22):   if (document.getElementById('$linkid')) {
                   6386:22):     var clickelem = document.getElementById('$linkid');
                   6387:22):     clickelem.addEventListener('click',ebFunction,false);
                   6388:22):   }
                   6389:22): });
                   6390:22): // ]]>
                   6391:22): </script>
                   6392:22): ENDJS
                   6393:22):             }
1.635     raeburn  6394: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6395:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6396: 	        &mt('Continue').'</a>'.
                   6397: 	        $endbodytag;
                   6398:         }
1.315     albertel 6399:     }
1.251     albertel 6400:     return $endbodytag;
                   6401: }
                   6402: 
1.352     albertel 6403: =pod
                   6404: 
                   6405: =item * &standard_css()
                   6406: 
                   6407: Returns a style sheet
                   6408: 
                   6409: Inputs: (all optional)
                   6410:             domain         -> force to color decorate a page for a specific
                   6411:                                domain
                   6412:             function       -> force usage of a specific rolish color scheme
                   6413:             bgcolor        -> override the default page bgcolor
                   6414: 
                   6415: =cut
                   6416: 
1.343     albertel 6417: sub standard_css {
1.345     albertel 6418:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6419:     $function  = &get_users_function() if (!$function);
                   6420:     my $img    = &designparm($function.'.img',   $domain);
                   6421:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6422:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6423:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6424: #second colour for later usage
1.345     albertel 6425:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6426:     my $pgbg_or_bgcolor =
                   6427: 	         $bgcolor ||
1.352     albertel 6428: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6429:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6430:     my $alink  = &designparm($function.'.alink', $domain);
                   6431:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6432:     my $link   = &designparm($function.'.link',  $domain);
                   6433: 
1.602     albertel 6434:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6435:     my $mono                 = 'monospace';
1.850     bisitz   6436:     my $data_table_head      = $sidebg;
                   6437:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6438:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6439:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6440:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6441:     my $mail_new             = '#FFBB77';
                   6442:     my $mail_new_hover       = '#DD9955';
                   6443:     my $mail_read            = '#BBBB77';
                   6444:     my $mail_read_hover      = '#999944';
                   6445:     my $mail_replied         = '#AAAA88';
                   6446:     my $mail_replied_hover   = '#888855';
                   6447:     my $mail_other           = '#99BBBB';
                   6448:     my $mail_other_hover     = '#669999';
1.391     albertel 6449:     my $table_header         = '#DDDDDD';
1.489     raeburn  6450:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6451:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6452:     my $button_hover         = '#BF2317';
1.392     albertel 6453: 
1.608     albertel 6454:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6455:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6456:                                              : '0 3px 0 4px';
1.448     albertel 6457: 
1.523     albertel 6458: 
1.343     albertel 6459:     return <<END;
1.947     droeschl 6460: 
                   6461: /* needed for iframe to allow 100% height in FF */
                   6462: body, html { 
                   6463:     margin: 0;
                   6464:     padding: 0 0.5%;
                   6465:     height: 99%; /* to avoid scrollbars */
                   6466: }
                   6467: 
1.795     www      6468: body {
1.911     bisitz   6469:   font-family: $sans;
                   6470:   line-height:130%;
                   6471:   font-size:0.83em;
                   6472:   color:$font;
1.795     www      6473: }
                   6474: 
1.959     onken    6475: a:focus,
                   6476: a:focus img {
1.795     www      6477:   color: red;
                   6478: }
1.698     harmsja  6479: 
1.911     bisitz   6480: form, .inline {
                   6481:   display: inline;
1.795     www      6482: }
1.721     harmsja  6483: 
1.795     www      6484: .LC_right {
1.911     bisitz   6485:   text-align:right;
1.795     www      6486: }
                   6487: 
                   6488: .LC_middle {
1.911     bisitz   6489:   vertical-align:middle;
1.795     www      6490: }
1.721     harmsja  6491: 
1.1075.2.38  raeburn  6492: .LC_floatleft {
                   6493:   float: left;
                   6494: }
                   6495: 
                   6496: .LC_floatright {
                   6497:   float: right;
                   6498: }
                   6499: 
1.911     bisitz   6500: .LC_400Box {
                   6501:   width:400px;
                   6502: }
1.721     harmsja  6503: 
1.947     droeschl 6504: .LC_iframecontainer {
                   6505:     width: 98%;
                   6506:     margin: 0;
                   6507:     position: fixed;
                   6508:     top: 8.5em;
                   6509:     bottom: 0;
                   6510: }
                   6511: 
                   6512: .LC_iframecontainer iframe{
                   6513:     border: none;
                   6514:     width: 100%;
                   6515:     height: 100%;
                   6516: }
                   6517: 
1.778     bisitz   6518: .LC_filename {
                   6519:   font-family: $mono;
                   6520:   white-space:pre;
1.921     bisitz   6521:   font-size: 120%;
1.778     bisitz   6522: }
                   6523: 
                   6524: .LC_fileicon {
                   6525:   border: none;
                   6526:   height: 1.3em;
                   6527:   vertical-align: text-bottom;
                   6528:   margin-right: 0.3em;
                   6529:   text-decoration:none;
                   6530: }
                   6531: 
1.1008    www      6532: .LC_setting {
                   6533:   text-decoration:underline;
                   6534: }
                   6535: 
1.350     albertel 6536: .LC_error {
                   6537:   color: red;
                   6538: }
1.795     www      6539: 
1.1075.2.15  raeburn  6540: .LC_warning {
                   6541:   color: darkorange;
                   6542: }
                   6543: 
1.457     albertel 6544: .LC_diff_removed {
1.733     bisitz   6545:   color: red;
1.394     albertel 6546: }
1.532     albertel 6547: 
                   6548: .LC_info,
1.457     albertel 6549: .LC_success,
                   6550: .LC_diff_added {
1.350     albertel 6551:   color: green;
                   6552: }
1.795     www      6553: 
1.802     bisitz   6554: div.LC_confirm_box {
                   6555:   background-color: #FAFAFA;
                   6556:   border: 1px solid $lg_border_color;
                   6557:   margin-right: 0;
                   6558:   padding: 5px;
                   6559: }
                   6560: 
                   6561: div.LC_confirm_box .LC_error img,
                   6562: div.LC_confirm_box .LC_success img {
                   6563:   vertical-align: middle;
                   6564: }
                   6565: 
1.1075.2.108  raeburn  6566: .LC_maxwidth {
                   6567:   max-width: 100%;
                   6568:   height: auto;
                   6569: }
                   6570: 
                   6571: .LC_textsize_mobile {
                   6572:   \@media only screen and (max-device-width: 480px) {
                   6573:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6574:   }
                   6575: }
                   6576: 
1.440     albertel 6577: .LC_icon {
1.771     droeschl 6578:   border: none;
1.790     droeschl 6579:   vertical-align: middle;
1.771     droeschl 6580: }
                   6581: 
1.543     albertel 6582: .LC_docs_spacer {
                   6583:   width: 25px;
                   6584:   height: 1px;
1.771     droeschl 6585:   border: none;
1.543     albertel 6586: }
1.346     albertel 6587: 
1.532     albertel 6588: .LC_internal_info {
1.735     bisitz   6589:   color: #999999;
1.532     albertel 6590: }
                   6591: 
1.794     www      6592: .LC_discussion {
1.1050    www      6593:   background: $data_table_dark;
1.911     bisitz   6594:   border: 1px solid black;
                   6595:   margin: 2px;
1.794     www      6596: }
                   6597: 
                   6598: .LC_disc_action_left {
1.1050    www      6599:   background: $sidebg;
1.911     bisitz   6600:   text-align: left;
1.1050    www      6601:   padding: 4px;
                   6602:   margin: 2px;
1.794     www      6603: }
                   6604: 
                   6605: .LC_disc_action_right {
1.1050    www      6606:   background: $sidebg;
1.911     bisitz   6607:   text-align: right;
1.1050    www      6608:   padding: 4px;
                   6609:   margin: 2px;
1.794     www      6610: }
                   6611: 
                   6612: .LC_disc_new_item {
1.911     bisitz   6613:   background: white;
                   6614:   border: 2px solid red;
1.1050    www      6615:   margin: 4px;
                   6616:   padding: 4px;
1.794     www      6617: }
                   6618: 
                   6619: .LC_disc_old_item {
1.911     bisitz   6620:   background: white;
1.1050    www      6621:   margin: 4px;
                   6622:   padding: 4px;
1.794     www      6623: }
                   6624: 
1.458     albertel 6625: table.LC_pastsubmission {
                   6626:   border: 1px solid black;
                   6627:   margin: 2px;
                   6628: }
                   6629: 
1.924     bisitz   6630: table#LC_menubuttons {
1.345     albertel 6631:   width: 100%;
                   6632:   background: $pgbg;
1.392     albertel 6633:   border: 2px;
1.402     albertel 6634:   border-collapse: separate;
1.803     bisitz   6635:   padding: 0;
1.345     albertel 6636: }
1.392     albertel 6637: 
1.801     tempelho 6638: table#LC_title_bar a {
                   6639:   color: $fontmenu;
                   6640: }
1.836     bisitz   6641: 
1.807     droeschl 6642: table#LC_title_bar {
1.819     tempelho 6643:   clear: both;
1.836     bisitz   6644:   display: none;
1.807     droeschl 6645: }
                   6646: 
1.795     www      6647: table#LC_title_bar,
1.933     droeschl 6648: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6649: table#LC_title_bar.LC_with_remote {
1.359     albertel 6650:   width: 100%;
1.392     albertel 6651:   border-color: $pgbg;
                   6652:   border-style: solid;
                   6653:   border-width: $border;
1.379     albertel 6654:   background: $pgbg;
1.801     tempelho 6655:   color: $fontmenu;
1.392     albertel 6656:   border-collapse: collapse;
1.803     bisitz   6657:   padding: 0;
1.819     tempelho 6658:   margin: 0;
1.359     albertel 6659: }
1.795     www      6660: 
1.933     droeschl 6661: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6662:     margin: 0;
                   6663:     padding: 0;
1.933     droeschl 6664:     position: relative;
                   6665:     list-style: none;
1.913     droeschl 6666: }
1.933     droeschl 6667: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6668:     display: inline;
                   6669: }
1.933     droeschl 6670: 
                   6671: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6672:     padding: 0;
1.933     droeschl 6673:     margin: 0;
                   6674:     float: left;
1.913     droeschl 6675: }
1.933     droeschl 6676: .LC_breadcrumb_tools_tools {
                   6677:     padding: 0;
                   6678:     margin: 0;
1.913     droeschl 6679:     float: right;
                   6680: }
                   6681: 
1.359     albertel 6682: table#LC_title_bar td {
                   6683:   background: $tabbg;
                   6684: }
1.795     www      6685: 
1.911     bisitz   6686: table#LC_menubuttons img {
1.803     bisitz   6687:   border: none;
1.346     albertel 6688: }
1.795     www      6689: 
1.842     droeschl 6690: .LC_breadcrumbs_component {
1.911     bisitz   6691:   float: right;
                   6692:   margin: 0 1em;
1.357     albertel 6693: }
1.842     droeschl 6694: .LC_breadcrumbs_component img {
1.911     bisitz   6695:   vertical-align: middle;
1.777     tempelho 6696: }
1.795     www      6697: 
1.1075.2.108  raeburn  6698: .LC_breadcrumbs_hoverable {
                   6699:   background: $sidebg;
                   6700: }
                   6701: 
1.383     albertel 6702: td.LC_table_cell_checkbox {
                   6703:   text-align: center;
                   6704: }
1.795     www      6705: 
                   6706: .LC_fontsize_small {
1.911     bisitz   6707:   font-size: 70%;
1.705     tempelho 6708: }
                   6709: 
1.844     bisitz   6710: #LC_breadcrumbs {
1.911     bisitz   6711:   clear:both;
                   6712:   background: $sidebg;
                   6713:   border-bottom: 1px solid $lg_border_color;
                   6714:   line-height: 2.5em;
1.933     droeschl 6715:   overflow: hidden;
1.911     bisitz   6716:   margin: 0;
                   6717:   padding: 0;
1.995     raeburn  6718:   text-align: left;
1.819     tempelho 6719: }
1.862     bisitz   6720: 
1.1075.2.16  raeburn  6721: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6722:   clear:both;
                   6723:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6724:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6725:   margin: 0 0 10px 0;
1.966     bisitz   6726:   padding: 3px;
1.995     raeburn  6727:   text-align: left;
1.822     bisitz   6728: }
                   6729: 
1.795     www      6730: .LC_fontsize_medium {
1.911     bisitz   6731:   font-size: 85%;
1.705     tempelho 6732: }
                   6733: 
1.795     www      6734: .LC_fontsize_large {
1.911     bisitz   6735:   font-size: 120%;
1.705     tempelho 6736: }
                   6737: 
1.346     albertel 6738: .LC_menubuttons_inline_text {
                   6739:   color: $font;
1.698     harmsja  6740:   font-size: 90%;
1.701     harmsja  6741:   padding-left:3px;
1.346     albertel 6742: }
                   6743: 
1.934     droeschl 6744: .LC_menubuttons_inline_text img{
                   6745:   vertical-align: middle;
                   6746: }
                   6747: 
1.1051    www      6748: li.LC_menubuttons_inline_text img {
1.951     onken    6749:   cursor:pointer;
1.1002    droeschl 6750:   text-decoration: none;
1.951     onken    6751: }
                   6752: 
1.526     www      6753: .LC_menubuttons_link {
                   6754:   text-decoration: none;
                   6755: }
1.795     www      6756: 
1.522     albertel 6757: .LC_menubuttons_category {
1.521     www      6758:   color: $font;
1.526     www      6759:   background: $pgbg;
1.521     www      6760:   font-size: larger;
                   6761:   font-weight: bold;
                   6762: }
                   6763: 
1.346     albertel 6764: td.LC_menubuttons_text {
1.911     bisitz   6765:   color: $font;
1.346     albertel 6766: }
1.706     harmsja  6767: 
1.346     albertel 6768: .LC_current_location {
                   6769:   background: $tabbg;
                   6770: }
1.795     www      6771: 
1.1075.2.134  raeburn  6772: td.LC_zero_height {
                   6773:   line-height: 0;
                   6774:   cellpadding: 0;
                   6775: }
                   6776: 
1.938     bisitz   6777: table.LC_data_table {
1.347     albertel 6778:   border: 1px solid #000000;
1.402     albertel 6779:   border-collapse: separate;
1.426     albertel 6780:   border-spacing: 1px;
1.610     albertel 6781:   background: $pgbg;
1.347     albertel 6782: }
1.795     www      6783: 
1.422     albertel 6784: .LC_data_table_dense {
                   6785:   font-size: small;
                   6786: }
1.795     www      6787: 
1.507     raeburn  6788: table.LC_nested_outer {
                   6789:   border: 1px solid #000000;
1.589     raeburn  6790:   border-collapse: collapse;
1.803     bisitz   6791:   border-spacing: 0;
1.507     raeburn  6792:   width: 100%;
                   6793: }
1.795     www      6794: 
1.879     raeburn  6795: table.LC_innerpickbox,
1.507     raeburn  6796: table.LC_nested {
1.803     bisitz   6797:   border: none;
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.911     bisitz   6803: table.LC_data_table tr th,
                   6804: table.LC_calendar tr th,
1.879     raeburn  6805: table.LC_prior_tries tr th,
                   6806: table.LC_innerpickbox tr th {
1.349     albertel 6807:   font-weight: bold;
                   6808:   background-color: $data_table_head;
1.801     tempelho 6809:   color:$fontmenu;
1.701     harmsja  6810:   font-size:90%;
1.347     albertel 6811: }
1.795     www      6812: 
1.879     raeburn  6813: table.LC_innerpickbox tr th,
                   6814: table.LC_innerpickbox tr td {
                   6815:   vertical-align: top;
                   6816: }
                   6817: 
1.711     raeburn  6818: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6819:   background-color: #CCCCCC;
1.711     raeburn  6820:   font-weight: bold;
                   6821:   text-align: left;
                   6822: }
1.795     www      6823: 
1.912     bisitz   6824: table.LC_data_table tr.LC_odd_row > td {
                   6825:   background-color: $data_table_light;
                   6826:   padding: 2px;
                   6827:   vertical-align: top;
                   6828: }
                   6829: 
1.809     bisitz   6830: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6831:   background-color: $data_table_light;
1.912     bisitz   6832:   vertical-align: top;
                   6833: }
                   6834: 
                   6835: table.LC_data_table tr.LC_even_row > td {
                   6836:   background-color: $data_table_dark;
1.425     albertel 6837:   padding: 2px;
1.900     bisitz   6838:   vertical-align: top;
1.347     albertel 6839: }
1.795     www      6840: 
1.809     bisitz   6841: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6842:   background-color: $data_table_dark;
1.900     bisitz   6843:   vertical-align: top;
1.347     albertel 6844: }
1.795     www      6845: 
1.425     albertel 6846: table.LC_data_table tr.LC_data_table_highlight td {
                   6847:   background-color: $data_table_darker;
                   6848: }
1.795     www      6849: 
1.639     raeburn  6850: table.LC_data_table tr td.LC_leftcol_header {
                   6851:   background-color: $data_table_head;
                   6852:   font-weight: bold;
                   6853: }
1.795     www      6854: 
1.451     albertel 6855: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6856: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6857:   font-weight: bold;
                   6858:   font-style: italic;
                   6859:   text-align: center;
                   6860:   padding: 8px;
1.347     albertel 6861: }
1.795     www      6862: 
1.1075.2.30  raeburn  6863: table.LC_data_table tr.LC_empty_row td,
                   6864: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6865:   background-color: $sidebg;
                   6866: }
                   6867: 
                   6868: table.LC_nested tr.LC_empty_row td {
                   6869:   background-color: #FFFFFF;
                   6870: }
                   6871: 
1.890     droeschl 6872: table.LC_caption {
                   6873: }
                   6874: 
1.507     raeburn  6875: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6876:   padding: 4ex
                   6877: }
1.795     www      6878: 
1.507     raeburn  6879: table.LC_nested_outer tr th {
                   6880:   font-weight: bold;
1.801     tempelho 6881:   color:$fontmenu;
1.507     raeburn  6882:   background-color: $data_table_head;
1.701     harmsja  6883:   font-size: small;
1.507     raeburn  6884:   border-bottom: 1px solid #000000;
                   6885: }
1.795     www      6886: 
1.507     raeburn  6887: table.LC_nested_outer tr td.LC_subheader {
                   6888:   background-color: $data_table_head;
                   6889:   font-weight: bold;
                   6890:   font-size: small;
                   6891:   border-bottom: 1px solid #000000;
                   6892:   text-align: right;
1.451     albertel 6893: }
1.795     www      6894: 
1.507     raeburn  6895: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6896:   background-color: #CCCCCC;
1.451     albertel 6897:   font-weight: bold;
                   6898:   font-size: small;
1.507     raeburn  6899:   text-align: center;
                   6900: }
1.795     www      6901: 
1.589     raeburn  6902: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6903: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6904:   text-align: left;
1.451     albertel 6905: }
1.795     www      6906: 
1.507     raeburn  6907: table.LC_nested td {
1.735     bisitz   6908:   background-color: #FFFFFF;
1.451     albertel 6909:   font-size: small;
1.507     raeburn  6910: }
1.795     www      6911: 
1.507     raeburn  6912: table.LC_nested_outer tr th.LC_right_item,
                   6913: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6914: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6915: table.LC_nested tr td.LC_right_item {
1.451     albertel 6916:   text-align: right;
                   6917: }
                   6918: 
1.507     raeburn  6919: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6920:   background-color: #EEEEEE;
1.451     albertel 6921: }
                   6922: 
1.473     raeburn  6923: table.LC_createuser {
                   6924: }
                   6925: 
                   6926: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6927:   font-size: small;
1.473     raeburn  6928: }
                   6929: 
                   6930: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6931:   background-color: #CCCCCC;
1.473     raeburn  6932:   font-weight: bold;
                   6933:   text-align: center;
                   6934: }
                   6935: 
1.349     albertel 6936: table.LC_calendar {
                   6937:   border: 1px solid #000000;
                   6938:   border-collapse: collapse;
1.917     raeburn  6939:   width: 98%;
1.349     albertel 6940: }
1.795     www      6941: 
1.349     albertel 6942: table.LC_calendar_pickdate {
                   6943:   font-size: xx-small;
                   6944: }
1.795     www      6945: 
1.349     albertel 6946: table.LC_calendar tr td {
                   6947:   border: 1px solid #000000;
                   6948:   vertical-align: top;
1.917     raeburn  6949:   width: 14%;
1.349     albertel 6950: }
1.795     www      6951: 
1.349     albertel 6952: table.LC_calendar tr td.LC_calendar_day_empty {
                   6953:   background-color: $data_table_dark;
                   6954: }
1.795     www      6955: 
1.779     bisitz   6956: table.LC_calendar tr td.LC_calendar_day_current {
                   6957:   background-color: $data_table_highlight;
1.777     tempelho 6958: }
1.795     www      6959: 
1.938     bisitz   6960: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6961:   background-color: $mail_new;
                   6962: }
1.795     www      6963: 
1.938     bisitz   6964: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6965:   background-color: $mail_new_hover;
                   6966: }
1.795     www      6967: 
1.938     bisitz   6968: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6969:   background-color: $mail_read;
                   6970: }
1.795     www      6971: 
1.938     bisitz   6972: /*
                   6973: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6974:   background-color: $mail_read_hover;
                   6975: }
1.938     bisitz   6976: */
1.795     www      6977: 
1.938     bisitz   6978: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6979:   background-color: $mail_replied;
                   6980: }
1.795     www      6981: 
1.938     bisitz   6982: /*
                   6983: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6984:   background-color: $mail_replied_hover;
                   6985: }
1.938     bisitz   6986: */
1.795     www      6987: 
1.938     bisitz   6988: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6989:   background-color: $mail_other;
                   6990: }
1.795     www      6991: 
1.938     bisitz   6992: /*
                   6993: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6994:   background-color: $mail_other_hover;
                   6995: }
1.938     bisitz   6996: */
1.494     raeburn  6997: 
1.777     tempelho 6998: table.LC_data_table tr > td.LC_browser_file,
                   6999: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7000:   background: #AAEE77;
1.389     albertel 7001: }
1.795     www      7002: 
1.777     tempelho 7003: table.LC_data_table tr > td.LC_browser_file_locked,
                   7004: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7005:   background: #FFAA99;
1.387     albertel 7006: }
1.795     www      7007: 
1.777     tempelho 7008: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7009:   background: #888888;
1.779     bisitz   7010: }
1.795     www      7011: 
1.777     tempelho 7012: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7013: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7014:   background: #F8F866;
1.777     tempelho 7015: }
1.795     www      7016: 
1.696     bisitz   7017: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7018:   background: #E0E8FF;
1.387     albertel 7019: }
1.696     bisitz   7020: 
1.707     bisitz   7021: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7022:   /* background: #77FF77; */
1.707     bisitz   7023: }
1.795     www      7024: 
1.707     bisitz   7025: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7026:   border-right: 8px solid #FFFF77;
1.707     bisitz   7027: }
1.795     www      7028: 
1.707     bisitz   7029: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7030:   border-right: 8px solid #FFAA77;
1.707     bisitz   7031: }
1.795     www      7032: 
1.707     bisitz   7033: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7034:   border-right: 8px solid #FF7777;
1.707     bisitz   7035: }
1.795     www      7036: 
1.707     bisitz   7037: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7038:   border-right: 8px solid #AAFF77;
1.707     bisitz   7039: }
1.795     www      7040: 
1.707     bisitz   7041: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7042:   border-right: 8px solid #11CC55;
1.707     bisitz   7043: }
                   7044: 
1.388     albertel 7045: span.LC_current_location {
1.701     harmsja  7046:   font-size:larger;
1.388     albertel 7047:   background: $pgbg;
                   7048: }
1.387     albertel 7049: 
1.1029    www      7050: span.LC_current_nav_location {
                   7051:   font-weight:bold;
                   7052:   background: $sidebg;
                   7053: }
                   7054: 
1.395     albertel 7055: span.LC_parm_menu_item {
                   7056:   font-size: larger;
                   7057: }
1.795     www      7058: 
1.395     albertel 7059: span.LC_parm_scope_all {
                   7060:   color: red;
                   7061: }
1.795     www      7062: 
1.395     albertel 7063: span.LC_parm_scope_folder {
                   7064:   color: green;
                   7065: }
1.795     www      7066: 
1.395     albertel 7067: span.LC_parm_scope_resource {
                   7068:   color: orange;
                   7069: }
1.795     www      7070: 
1.395     albertel 7071: span.LC_parm_part {
                   7072:   color: blue;
                   7073: }
1.795     www      7074: 
1.911     bisitz   7075: span.LC_parm_folder,
                   7076: span.LC_parm_symb {
1.395     albertel 7077:   font-size: x-small;
                   7078:   font-family: $mono;
                   7079:   color: #AAAAAA;
                   7080: }
                   7081: 
1.977     bisitz   7082: ul.LC_parm_parmlist li {
                   7083:   display: inline-block;
                   7084:   padding: 0.3em 0.8em;
                   7085:   vertical-align: top;
                   7086:   width: 150px;
                   7087:   border-top:1px solid $lg_border_color;
                   7088: }
                   7089: 
1.795     www      7090: td.LC_parm_overview_level_menu,
                   7091: td.LC_parm_overview_map_menu,
                   7092: td.LC_parm_overview_parm_selectors,
                   7093: td.LC_parm_overview_restrictions  {
1.396     albertel 7094:   border: 1px solid black;
                   7095:   border-collapse: collapse;
                   7096: }
1.795     www      7097: 
1.396     albertel 7098: table.LC_parm_overview_restrictions td {
                   7099:   border-width: 1px 4px 1px 4px;
                   7100:   border-style: solid;
                   7101:   border-color: $pgbg;
                   7102:   text-align: center;
                   7103: }
1.795     www      7104: 
1.396     albertel 7105: table.LC_parm_overview_restrictions th {
                   7106:   background: $tabbg;
                   7107:   border-width: 1px 4px 1px 4px;
                   7108:   border-style: solid;
                   7109:   border-color: $pgbg;
                   7110: }
1.795     www      7111: 
1.398     albertel 7112: table#LC_helpmenu {
1.803     bisitz   7113:   border: none;
1.398     albertel 7114:   height: 55px;
1.803     bisitz   7115:   border-spacing: 0;
1.398     albertel 7116: }
                   7117: 
                   7118: table#LC_helpmenu fieldset legend {
                   7119:   font-size: larger;
                   7120: }
1.795     www      7121: 
1.397     albertel 7122: table#LC_helpmenu_links {
                   7123:   width: 100%;
                   7124:   border: 1px solid black;
                   7125:   background: $pgbg;
1.803     bisitz   7126:   padding: 0;
1.397     albertel 7127:   border-spacing: 1px;
                   7128: }
1.795     www      7129: 
1.397     albertel 7130: table#LC_helpmenu_links tr td {
                   7131:   padding: 1px;
                   7132:   background: $tabbg;
1.399     albertel 7133:   text-align: center;
                   7134:   font-weight: bold;
1.397     albertel 7135: }
1.396     albertel 7136: 
1.795     www      7137: table#LC_helpmenu_links a:link,
                   7138: table#LC_helpmenu_links a:visited,
1.397     albertel 7139: table#LC_helpmenu_links a:active {
                   7140:   text-decoration: none;
                   7141:   color: $font;
                   7142: }
1.795     www      7143: 
1.397     albertel 7144: table#LC_helpmenu_links a:hover {
                   7145:   text-decoration: underline;
                   7146:   color: $vlink;
                   7147: }
1.396     albertel 7148: 
1.417     albertel 7149: .LC_chrt_popup_exists {
                   7150:   border: 1px solid #339933;
                   7151:   margin: -1px;
                   7152: }
1.795     www      7153: 
1.417     albertel 7154: .LC_chrt_popup_up {
                   7155:   border: 1px solid yellow;
                   7156:   margin: -1px;
                   7157: }
1.795     www      7158: 
1.417     albertel 7159: .LC_chrt_popup {
                   7160:   border: 1px solid #8888FF;
                   7161:   background: #CCCCFF;
                   7162: }
1.795     www      7163: 
1.421     albertel 7164: table.LC_pick_box {
                   7165:   border-collapse: separate;
                   7166:   background: white;
                   7167:   border: 1px solid black;
                   7168:   border-spacing: 1px;
                   7169: }
1.795     www      7170: 
1.421     albertel 7171: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7172:   background: $sidebg;
1.421     albertel 7173:   font-weight: bold;
1.900     bisitz   7174:   text-align: left;
1.740     bisitz   7175:   vertical-align: top;
1.421     albertel 7176:   width: 184px;
                   7177:   padding: 8px;
                   7178: }
1.795     www      7179: 
1.579     raeburn  7180: table.LC_pick_box td.LC_pick_box_value {
                   7181:   text-align: left;
                   7182:   padding: 8px;
                   7183: }
1.795     www      7184: 
1.579     raeburn  7185: table.LC_pick_box td.LC_pick_box_select {
                   7186:   text-align: left;
                   7187:   padding: 8px;
                   7188: }
1.795     www      7189: 
1.424     albertel 7190: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7191:   padding: 0;
1.421     albertel 7192:   height: 1px;
                   7193:   background: black;
                   7194: }
1.795     www      7195: 
1.421     albertel 7196: table.LC_pick_box td.LC_pick_box_submit {
                   7197:   text-align: right;
                   7198: }
1.795     www      7199: 
1.579     raeburn  7200: table.LC_pick_box td.LC_evenrow_value {
                   7201:   text-align: left;
                   7202:   padding: 8px;
                   7203:   background-color: $data_table_light;
                   7204: }
1.795     www      7205: 
1.579     raeburn  7206: table.LC_pick_box td.LC_oddrow_value {
                   7207:   text-align: left;
                   7208:   padding: 8px;
                   7209:   background-color: $data_table_light;
                   7210: }
1.795     www      7211: 
1.579     raeburn  7212: span.LC_helpform_receipt_cat {
                   7213:   font-weight: bold;
                   7214: }
1.795     www      7215: 
1.424     albertel 7216: table.LC_group_priv_box {
                   7217:   background: white;
                   7218:   border: 1px solid black;
                   7219:   border-spacing: 1px;
                   7220: }
1.795     www      7221: 
1.424     albertel 7222: table.LC_group_priv_box td.LC_pick_box_title {
                   7223:   background: $tabbg;
                   7224:   font-weight: bold;
                   7225:   text-align: right;
                   7226:   width: 184px;
                   7227: }
1.795     www      7228: 
1.424     albertel 7229: table.LC_group_priv_box td.LC_groups_fixed {
                   7230:   background: $data_table_light;
                   7231:   text-align: center;
                   7232: }
1.795     www      7233: 
1.424     albertel 7234: table.LC_group_priv_box td.LC_groups_optional {
                   7235:   background: $data_table_dark;
                   7236:   text-align: center;
                   7237: }
1.795     www      7238: 
1.424     albertel 7239: table.LC_group_priv_box td.LC_groups_functionality {
                   7240:   background: $data_table_darker;
                   7241:   text-align: center;
                   7242:   font-weight: bold;
                   7243: }
1.795     www      7244: 
1.424     albertel 7245: table.LC_group_priv td {
                   7246:   text-align: left;
1.803     bisitz   7247:   padding: 0;
1.424     albertel 7248: }
                   7249: 
                   7250: .LC_navbuttons {
                   7251:   margin: 2ex 0ex 2ex 0ex;
                   7252: }
1.795     www      7253: 
1.423     albertel 7254: .LC_topic_bar {
                   7255:   font-weight: bold;
                   7256:   background: $tabbg;
1.918     wenzelju 7257:   margin: 1em 0em 1em 2em;
1.805     bisitz   7258:   padding: 3px;
1.918     wenzelju 7259:   font-size: 1.2em;
1.423     albertel 7260: }
1.795     www      7261: 
1.423     albertel 7262: .LC_topic_bar span {
1.918     wenzelju 7263:   left: 0.5em;
                   7264:   position: absolute;
1.423     albertel 7265:   vertical-align: middle;
1.918     wenzelju 7266:   font-size: 1.2em;
1.423     albertel 7267: }
1.795     www      7268: 
1.423     albertel 7269: table.LC_course_group_status {
                   7270:   margin: 20px;
                   7271: }
1.795     www      7272: 
1.423     albertel 7273: table.LC_status_selector td {
                   7274:   vertical-align: top;
                   7275:   text-align: center;
1.424     albertel 7276:   padding: 4px;
                   7277: }
1.795     www      7278: 
1.599     albertel 7279: div.LC_feedback_link {
1.616     albertel 7280:   clear: both;
1.829     kalberla 7281:   background: $sidebg;
1.779     bisitz   7282:   width: 100%;
1.829     kalberla 7283:   padding-bottom: 10px;
                   7284:   border: 1px $tabbg solid;
1.833     kalberla 7285:   height: 22px;
                   7286:   line-height: 22px;
                   7287:   padding-top: 5px;
                   7288: }
                   7289: 
                   7290: div.LC_feedback_link img {
                   7291:   height: 22px;
1.867     kalberla 7292:   vertical-align:middle;
1.829     kalberla 7293: }
                   7294: 
1.911     bisitz   7295: div.LC_feedback_link a {
1.829     kalberla 7296:   text-decoration: none;
1.489     raeburn  7297: }
1.795     www      7298: 
1.867     kalberla 7299: div.LC_comblock {
1.911     bisitz   7300:   display:inline;
1.867     kalberla 7301:   color:$font;
                   7302:   font-size:90%;
                   7303: }
                   7304: 
                   7305: div.LC_feedback_link div.LC_comblock {
                   7306:   padding-left:5px;
                   7307: }
                   7308: 
                   7309: div.LC_feedback_link div.LC_comblock a {
                   7310:   color:$font;
                   7311: }
                   7312: 
1.489     raeburn  7313: span.LC_feedback_link {
1.858     bisitz   7314:   /* background: $feedback_link_bg; */
1.599     albertel 7315:   font-size: larger;
                   7316: }
1.795     www      7317: 
1.599     albertel 7318: span.LC_message_link {
1.858     bisitz   7319:   /* background: $feedback_link_bg; */
1.599     albertel 7320:   font-size: larger;
                   7321:   position: absolute;
                   7322:   right: 1em;
1.489     raeburn  7323: }
1.421     albertel 7324: 
1.515     albertel 7325: table.LC_prior_tries {
1.524     albertel 7326:   border: 1px solid #000000;
                   7327:   border-collapse: separate;
                   7328:   border-spacing: 1px;
1.515     albertel 7329: }
1.523     albertel 7330: 
1.515     albertel 7331: table.LC_prior_tries td {
1.524     albertel 7332:   padding: 2px;
1.515     albertel 7333: }
1.523     albertel 7334: 
                   7335: .LC_answer_correct {
1.795     www      7336:   background: lightgreen;
                   7337:   color: darkgreen;
                   7338:   padding: 6px;
1.523     albertel 7339: }
1.795     www      7340: 
1.523     albertel 7341: .LC_answer_charged_try {
1.797     www      7342:   background: #FFAAAA;
1.795     www      7343:   color: darkred;
                   7344:   padding: 6px;
1.523     albertel 7345: }
1.795     www      7346: 
1.779     bisitz   7347: .LC_answer_not_charged_try,
1.523     albertel 7348: .LC_answer_no_grade,
                   7349: .LC_answer_late {
1.795     www      7350:   background: lightyellow;
1.523     albertel 7351:   color: black;
1.795     www      7352:   padding: 6px;
1.523     albertel 7353: }
1.795     www      7354: 
1.523     albertel 7355: .LC_answer_previous {
1.795     www      7356:   background: lightblue;
                   7357:   color: darkblue;
                   7358:   padding: 6px;
1.523     albertel 7359: }
1.795     www      7360: 
1.779     bisitz   7361: .LC_answer_no_message {
1.777     tempelho 7362:   background: #FFFFFF;
                   7363:   color: black;
1.795     www      7364:   padding: 6px;
1.779     bisitz   7365: }
1.795     www      7366: 
1.1075.2.140  raeburn  7367: .LC_answer_unknown,
                   7368: .LC_answer_warning {
1.779     bisitz   7369:   background: orange;
                   7370:   color: black;
1.795     www      7371:   padding: 6px;
1.777     tempelho 7372: }
1.795     www      7373: 
1.529     albertel 7374: span.LC_prior_numerical,
                   7375: span.LC_prior_string,
                   7376: span.LC_prior_custom,
                   7377: span.LC_prior_reaction,
                   7378: span.LC_prior_math {
1.925     bisitz   7379:   font-family: $mono;
1.523     albertel 7380:   white-space: pre;
                   7381: }
                   7382: 
1.525     albertel 7383: span.LC_prior_string {
1.925     bisitz   7384:   font-family: $mono;
1.525     albertel 7385:   white-space: pre;
                   7386: }
                   7387: 
1.523     albertel 7388: table.LC_prior_option {
                   7389:   width: 100%;
                   7390:   border-collapse: collapse;
                   7391: }
1.795     www      7392: 
1.911     bisitz   7393: table.LC_prior_rank,
1.795     www      7394: table.LC_prior_match {
1.528     albertel 7395:   border-collapse: collapse;
                   7396: }
1.795     www      7397: 
1.528     albertel 7398: table.LC_prior_option tr td,
                   7399: table.LC_prior_rank tr td,
                   7400: table.LC_prior_match tr td {
1.524     albertel 7401:   border: 1px solid #000000;
1.515     albertel 7402: }
                   7403: 
1.855     bisitz   7404: .LC_nobreak {
1.544     albertel 7405:   white-space: nowrap;
1.519     raeburn  7406: }
                   7407: 
1.576     raeburn  7408: span.LC_cusr_emph {
                   7409:   font-style: italic;
                   7410: }
                   7411: 
1.633     raeburn  7412: span.LC_cusr_subheading {
                   7413:   font-weight: normal;
                   7414:   font-size: 85%;
                   7415: }
                   7416: 
1.861     bisitz   7417: div.LC_docs_entry_move {
1.859     bisitz   7418:   border: 1px solid #BBBBBB;
1.545     albertel 7419:   background: #DDDDDD;
1.861     bisitz   7420:   width: 22px;
1.859     bisitz   7421:   padding: 1px;
                   7422:   margin: 0;
1.545     albertel 7423: }
                   7424: 
1.861     bisitz   7425: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7426: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7427:   font-size: x-small;
                   7428: }
1.795     www      7429: 
1.861     bisitz   7430: .LC_docs_entry_parameter {
                   7431:   white-space: nowrap;
                   7432: }
                   7433: 
1.544     albertel 7434: .LC_docs_copy {
1.545     albertel 7435:   color: #000099;
1.544     albertel 7436: }
1.795     www      7437: 
1.544     albertel 7438: .LC_docs_cut {
1.545     albertel 7439:   color: #550044;
1.544     albertel 7440: }
1.795     www      7441: 
1.544     albertel 7442: .LC_docs_rename {
1.545     albertel 7443:   color: #009900;
1.544     albertel 7444: }
1.795     www      7445: 
1.544     albertel 7446: .LC_docs_remove {
1.545     albertel 7447:   color: #990000;
                   7448: }
                   7449: 
1.1075.2.134  raeburn  7450: .LC_domprefs_email,
1.547     albertel 7451: .LC_docs_reinit_warn,
                   7452: .LC_docs_ext_edit {
                   7453:   font-size: x-small;
                   7454: }
                   7455: 
1.545     albertel 7456: table.LC_docs_adddocs td,
                   7457: table.LC_docs_adddocs th {
                   7458:   border: 1px solid #BBBBBB;
                   7459:   padding: 4px;
                   7460:   background: #DDDDDD;
1.543     albertel 7461: }
                   7462: 
1.584     albertel 7463: table.LC_sty_begin {
                   7464:   background: #BBFFBB;
                   7465: }
1.795     www      7466: 
1.584     albertel 7467: table.LC_sty_end {
                   7468:   background: #FFBBBB;
                   7469: }
                   7470: 
1.589     raeburn  7471: table.LC_double_column {
1.803     bisitz   7472:   border-width: 0;
1.589     raeburn  7473:   border-collapse: collapse;
                   7474:   width: 100%;
                   7475:   padding: 2px;
                   7476: }
                   7477: 
                   7478: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7479:   top: 2px;
1.589     raeburn  7480:   left: 2px;
                   7481:   width: 47%;
                   7482:   vertical-align: top;
                   7483: }
                   7484: 
                   7485: table.LC_double_column tr td.LC_right_col {
                   7486:   top: 2px;
1.779     bisitz   7487:   right: 2px;
1.589     raeburn  7488:   width: 47%;
                   7489:   vertical-align: top;
                   7490: }
                   7491: 
1.591     raeburn  7492: div.LC_left_float {
                   7493:   float: left;
                   7494:   padding-right: 5%;
1.597     albertel 7495:   padding-bottom: 4px;
1.591     raeburn  7496: }
                   7497: 
                   7498: div.LC_clear_float_header {
1.597     albertel 7499:   padding-bottom: 2px;
1.591     raeburn  7500: }
                   7501: 
                   7502: div.LC_clear_float_footer {
1.597     albertel 7503:   padding-top: 10px;
1.591     raeburn  7504:   clear: both;
                   7505: }
                   7506: 
1.597     albertel 7507: div.LC_grade_show_user {
1.941     bisitz   7508: /*  border-left: 5px solid $sidebg; */
                   7509:   border-top: 5px solid #000000;
                   7510:   margin: 50px 0 0 0;
1.936     bisitz   7511:   padding: 15px 0 5px 10px;
1.597     albertel 7512: }
1.795     www      7513: 
1.936     bisitz   7514: div.LC_grade_show_user_odd_row {
1.941     bisitz   7515: /*  border-left: 5px solid #000000; */
                   7516: }
                   7517: 
                   7518: div.LC_grade_show_user div.LC_Box {
                   7519:   margin-right: 50px;
1.597     albertel 7520: }
                   7521: 
                   7522: div.LC_grade_submissions,
                   7523: div.LC_grade_message_center,
1.936     bisitz   7524: div.LC_grade_info_links {
1.597     albertel 7525:   margin: 5px;
                   7526:   width: 99%;
                   7527:   background: #FFFFFF;
                   7528: }
1.795     www      7529: 
1.597     albertel 7530: div.LC_grade_submissions_header,
1.936     bisitz   7531: div.LC_grade_message_center_header {
1.705     tempelho 7532:   font-weight: bold;
                   7533:   font-size: large;
1.597     albertel 7534: }
1.795     www      7535: 
1.597     albertel 7536: div.LC_grade_submissions_body,
1.936     bisitz   7537: div.LC_grade_message_center_body {
1.597     albertel 7538:   border: 1px solid black;
                   7539:   width: 99%;
                   7540:   background: #FFFFFF;
                   7541: }
1.795     www      7542: 
1.613     albertel 7543: table.LC_scantron_action {
                   7544:   width: 100%;
                   7545: }
1.795     www      7546: 
1.613     albertel 7547: table.LC_scantron_action tr th {
1.698     harmsja  7548:   font-weight:bold;
                   7549:   font-style:normal;
1.613     albertel 7550: }
1.795     www      7551: 
1.779     bisitz   7552: .LC_edit_problem_header,
1.614     albertel 7553: div.LC_edit_problem_footer {
1.705     tempelho 7554:   font-weight: normal;
                   7555:   font-size:  medium;
1.602     albertel 7556:   margin: 2px;
1.1060    bisitz   7557:   background-color: $sidebg;
1.600     albertel 7558: }
1.795     www      7559: 
1.600     albertel 7560: div.LC_edit_problem_header,
1.602     albertel 7561: div.LC_edit_problem_header div,
1.614     albertel 7562: div.LC_edit_problem_footer,
                   7563: div.LC_edit_problem_footer div,
1.602     albertel 7564: div.LC_edit_problem_editxml_header,
                   7565: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7566:   z-index: 100;
1.600     albertel 7567: }
1.795     www      7568: 
1.600     albertel 7569: div.LC_edit_problem_header_title {
1.705     tempelho 7570:   font-weight: bold;
                   7571:   font-size: larger;
1.602     albertel 7572:   background: $tabbg;
                   7573:   padding: 3px;
1.1060    bisitz   7574:   margin: 0 0 5px 0;
1.602     albertel 7575: }
1.795     www      7576: 
1.602     albertel 7577: table.LC_edit_problem_header_title {
                   7578:   width: 100%;
1.600     albertel 7579:   background: $tabbg;
1.602     albertel 7580: }
                   7581: 
1.1075.2.112  raeburn  7582: div.LC_edit_actionbar {
                   7583:     background-color: $sidebg;
                   7584:     margin: 0;
                   7585:     padding: 0;
                   7586:     line-height: 200%;
1.602     albertel 7587: }
1.795     www      7588: 
1.1075.2.112  raeburn  7589: div.LC_edit_actionbar div{
                   7590:     padding: 0;
                   7591:     margin: 0;
                   7592:     display: inline-block;
1.600     albertel 7593: }
1.795     www      7594: 
1.1075.2.34  raeburn  7595: .LC_edit_opt {
                   7596:   padding-left: 1em;
                   7597:   white-space: nowrap;
                   7598: }
                   7599: 
1.1075.2.57  raeburn  7600: .LC_edit_problem_latexhelper{
                   7601:     text-align: right;
                   7602: }
                   7603: 
                   7604: #LC_edit_problem_colorful div{
                   7605:     margin-left: 40px;
                   7606: }
                   7607: 
1.1075.2.112  raeburn  7608: #LC_edit_problem_codemirror div{
                   7609:     margin-left: 0px;
                   7610: }
                   7611: 
1.911     bisitz   7612: img.stift {
1.803     bisitz   7613:   border-width: 0;
                   7614:   vertical-align: middle;
1.677     riegler  7615: }
1.680     riegler  7616: 
1.923     bisitz   7617: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7618:   vertical-align: top;
1.777     tempelho 7619: }
1.795     www      7620: 
1.716     raeburn  7621: div.LC_createcourse {
1.911     bisitz   7622:   margin: 10px 10px 10px 10px;
1.716     raeburn  7623: }
                   7624: 
1.917     raeburn  7625: .LC_dccid {
1.1075.2.38  raeburn  7626:   float: right;
1.917     raeburn  7627:   margin: 0.2em 0 0 0;
                   7628:   padding: 0;
                   7629:   font-size: 90%;
                   7630:   display:none;
                   7631: }
                   7632: 
1.897     wenzelju 7633: ol.LC_primary_menu a:hover,
1.721     harmsja  7634: ol#LC_MenuBreadcrumbs a:hover,
                   7635: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7636: ul#LC_secondary_menu a:hover,
1.721     harmsja  7637: .LC_FormSectionClearButton input:hover
1.795     www      7638: ul.LC_TabContent   li:hover a {
1.952     onken    7639:   color:$button_hover;
1.911     bisitz   7640:   text-decoration:none;
1.693     droeschl 7641: }
                   7642: 
1.779     bisitz   7643: h1 {
1.911     bisitz   7644:   padding: 0;
                   7645:   line-height:130%;
1.693     droeschl 7646: }
1.698     harmsja  7647: 
1.911     bisitz   7648: h2,
                   7649: h3,
                   7650: h4,
                   7651: h5,
                   7652: h6 {
                   7653:   margin: 5px 0 5px 0;
                   7654:   padding: 0;
                   7655:   line-height:130%;
1.693     droeschl 7656: }
1.795     www      7657: 
                   7658: .LC_hcell {
1.911     bisitz   7659:   padding:3px 15px 3px 15px;
                   7660:   margin: 0;
                   7661:   background-color:$tabbg;
                   7662:   color:$fontmenu;
                   7663:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7664: }
1.795     www      7665: 
1.840     bisitz   7666: .LC_Box > .LC_hcell {
1.911     bisitz   7667:   margin: 0 -10px 10px -10px;
1.835     bisitz   7668: }
                   7669: 
1.721     harmsja  7670: .LC_noBorder {
1.911     bisitz   7671:   border: 0;
1.698     harmsja  7672: }
1.693     droeschl 7673: 
1.721     harmsja  7674: .LC_FormSectionClearButton input {
1.911     bisitz   7675:   background-color:transparent;
                   7676:   border: none;
                   7677:   cursor:pointer;
                   7678:   text-decoration:underline;
1.693     droeschl 7679: }
1.763     bisitz   7680: 
                   7681: .LC_help_open_topic {
1.911     bisitz   7682:   color: #FFFFFF;
                   7683:   background-color: #EEEEFF;
                   7684:   margin: 1px;
                   7685:   padding: 4px;
                   7686:   border: 1px solid #000033;
                   7687:   white-space: nowrap;
                   7688:   /* vertical-align: middle; */
1.759     neumanie 7689: }
1.693     droeschl 7690: 
1.911     bisitz   7691: dl,
                   7692: ul,
                   7693: div,
                   7694: fieldset {
                   7695:   margin: 10px 10px 10px 0;
                   7696:   /* overflow: hidden; */
1.693     droeschl 7697: }
1.795     www      7698: 
1.1075.2.161.  .18(raeb 7699:-23): fieldset#LC_selectuser {
                   7700:-23):     margin: 0;
                   7701:-23):     padding: 0;
                   7702:-23): }
                   7703:-23): 
1.1075.2.90  raeburn  7704: article.geogebraweb div {
                   7705:     margin: 0;
                   7706: }
                   7707: 
1.838     bisitz   7708: fieldset > legend {
1.911     bisitz   7709:   font-weight: bold;
                   7710:   padding: 0 5px 0 5px;
1.838     bisitz   7711: }
                   7712: 
1.813     bisitz   7713: #LC_nav_bar {
1.911     bisitz   7714:   float: left;
1.995     raeburn  7715:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7716:   margin: 0 0 2px 0;
1.807     droeschl 7717: }
                   7718: 
1.916     droeschl 7719: #LC_realm {
                   7720:   margin: 0.2em 0 0 0;
                   7721:   padding: 0;
                   7722:   font-weight: bold;
                   7723:   text-align: center;
1.995     raeburn  7724:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7725: }
                   7726: 
1.911     bisitz   7727: #LC_nav_bar em {
                   7728:   font-weight: bold;
                   7729:   font-style: normal;
1.807     droeschl 7730: }
                   7731: 
1.897     wenzelju 7732: ol.LC_primary_menu {
1.934     droeschl 7733:   margin: 0;
1.1075.2.2  raeburn  7734:   padding: 0;
1.807     droeschl 7735: }
                   7736: 
1.852     droeschl 7737: ol#LC_PathBreadcrumbs {
1.911     bisitz   7738:   margin: 0;
1.693     droeschl 7739: }
                   7740: 
1.897     wenzelju 7741: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7742:   color: RGB(80, 80, 80);
                   7743:   vertical-align: middle;
                   7744:   text-align: left;
                   7745:   list-style: none;
1.1075.2.112  raeburn  7746:   position: relative;
1.1075.2.2  raeburn  7747:   float: left;
1.1075.2.112  raeburn  7748:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7749:   line-height: 1.5em;
1.1075.2.2  raeburn  7750: }
                   7751: 
1.1075.2.113  raeburn  7752: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7753: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7754:   display: block;
                   7755:   margin: 0;
                   7756:   padding: 0 5px 0 10px;
                   7757:   text-decoration: none;
                   7758: }
                   7759: 
1.1075.2.112  raeburn  7760: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7761:   display: inline-block;
                   7762:   width: 95%;
                   7763:   text-align: left;
                   7764: }
                   7765: 
                   7766: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7767:   display: inline-block;
                   7768:   width: 5%;
                   7769:   float: right;
                   7770:   text-align: right;
                   7771:   font-size: 70%;
                   7772: }
                   7773: 
                   7774: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7775:   display: none;
1.1075.2.112  raeburn  7776:   width: 15em;
1.1075.2.2  raeburn  7777:   background-color: $data_table_light;
1.1075.2.112  raeburn  7778:   position: absolute;
                   7779:   top: 100%;
                   7780: }
                   7781: 
                   7782: ol.LC_primary_menu ul ul {
                   7783:   left: 100%;
                   7784:   top: 0;
1.1075.2.2  raeburn  7785: }
                   7786: 
1.1075.2.112  raeburn  7787: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7788:   display: block;
                   7789:   position: absolute;
                   7790:   margin: 0;
                   7791:   padding: 0;
1.1075.2.5  raeburn  7792:   z-index: 2;
1.1075.2.2  raeburn  7793: }
                   7794: 
                   7795: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7796: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7797:   font-size: 90%;
1.911     bisitz   7798:   vertical-align: top;
1.1075.2.2  raeburn  7799:   float: none;
1.1075.2.5  raeburn  7800:   border-left: 1px solid black;
                   7801:   border-right: 1px solid black;
1.1075.2.112  raeburn  7802: /* A dark bottom border to visualize different menu options;
                   7803: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7804:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7805: }
                   7806: 
1.1075.2.112  raeburn  7807: ol.LC_primary_menu li li p:hover {
                   7808:   color:$button_hover;
                   7809:   text-decoration:none;
                   7810:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7811: }
                   7812: 
                   7813: ol.LC_primary_menu li li a:hover {
                   7814:    color:$button_hover;
                   7815:    background-color:$data_table_dark;
1.693     droeschl 7816: }
                   7817: 
1.1075.2.112  raeburn  7818: /* Font-size equal to the size of the predecessors*/
                   7819: ol.LC_primary_menu li:hover li li {
                   7820:   font-size: 100%;
                   7821: }
                   7822: 
1.897     wenzelju 7823: ol.LC_primary_menu li img {
1.911     bisitz   7824:   vertical-align: bottom;
1.934     droeschl 7825:   height: 1.1em;
1.1075.2.3  raeburn  7826:   margin: 0.2em 0 0 0;
1.693     droeschl 7827: }
                   7828: 
1.897     wenzelju 7829: ol.LC_primary_menu a {
1.911     bisitz   7830:   color: RGB(80, 80, 80);
                   7831:   text-decoration: none;
1.693     droeschl 7832: }
1.795     www      7833: 
1.949     droeschl 7834: ol.LC_primary_menu a.LC_new_message {
                   7835:   font-weight:bold;
                   7836:   color: darkred;
                   7837: }
                   7838: 
1.975     raeburn  7839: ol.LC_docs_parameters {
                   7840:   margin-left: 0;
                   7841:   padding: 0;
                   7842:   list-style: none;
                   7843: }
                   7844: 
                   7845: ol.LC_docs_parameters li {
                   7846:   margin: 0;
                   7847:   padding-right: 20px;
                   7848:   display: inline;
                   7849: }
                   7850: 
1.976     raeburn  7851: ol.LC_docs_parameters li:before {
                   7852:   content: "\\002022 \\0020";
                   7853: }
                   7854: 
                   7855: li.LC_docs_parameters_title {
                   7856:   font-weight: bold;
                   7857: }
                   7858: 
                   7859: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7860:   content: "";
                   7861: }
                   7862: 
1.897     wenzelju 7863: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7864:   clear: right;
1.911     bisitz   7865:   color: $fontmenu;
                   7866:   background: $tabbg;
                   7867:   list-style: none;
                   7868:   padding: 0;
                   7869:   margin: 0;
                   7870:   width: 100%;
1.995     raeburn  7871:   text-align: left;
1.1075.2.4  raeburn  7872:   float: left;
1.808     droeschl 7873: }
                   7874: 
1.897     wenzelju 7875: ul#LC_secondary_menu li {
1.911     bisitz   7876:   font-weight: bold;
                   7877:   line-height: 1.8em;
                   7878:   border-right: 1px solid black;
1.1075.2.4  raeburn  7879:   float: left;
                   7880: }
                   7881: 
                   7882: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7883:   background-color: $data_table_light;
                   7884: }
                   7885: 
                   7886: ul#LC_secondary_menu li a {
                   7887:   padding: 0 0.8em;
                   7888: }
                   7889: 
                   7890: ul#LC_secondary_menu li ul {
                   7891:   display: none;
                   7892: }
                   7893: 
                   7894: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7895:   display: block;
                   7896:   position: absolute;
                   7897:   margin: 0;
                   7898:   padding: 0;
                   7899:   list-style:none;
                   7900:   float: none;
                   7901:   background-color: $data_table_light;
1.1075.2.5  raeburn  7902:   z-index: 2;
1.1075.2.10  raeburn  7903:   margin-left: -1px;
1.1075.2.4  raeburn  7904: }
                   7905: 
                   7906: ul#LC_secondary_menu li ul li {
                   7907:   font-size: 90%;
                   7908:   vertical-align: top;
                   7909:   border-left: 1px solid black;
                   7910:   border-right: 1px solid black;
1.1075.2.33  raeburn  7911:   background-color: $data_table_light;
1.1075.2.4  raeburn  7912:   list-style:none;
                   7913:   float: none;
                   7914: }
                   7915: 
                   7916: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7917:   background-color: $data_table_dark;
1.807     droeschl 7918: }
                   7919: 
1.847     tempelho 7920: ul.LC_TabContent {
1.911     bisitz   7921:   display:block;
                   7922:   background: $sidebg;
                   7923:   border-bottom: solid 1px $lg_border_color;
                   7924:   list-style:none;
1.1020    raeburn  7925:   margin: -1px -10px 0 -10px;
1.911     bisitz   7926:   padding: 0;
1.693     droeschl 7927: }
                   7928: 
1.795     www      7929: ul.LC_TabContent li,
                   7930: ul.LC_TabContentBigger li {
1.911     bisitz   7931:   float:left;
1.741     harmsja  7932: }
1.795     www      7933: 
1.897     wenzelju 7934: ul#LC_secondary_menu li a {
1.911     bisitz   7935:   color: $fontmenu;
                   7936:   text-decoration: none;
1.693     droeschl 7937: }
1.795     www      7938: 
1.721     harmsja  7939: ul.LC_TabContent {
1.952     onken    7940:   min-height:20px;
1.721     harmsja  7941: }
1.795     www      7942: 
                   7943: ul.LC_TabContent li {
1.911     bisitz   7944:   vertical-align:middle;
1.959     onken    7945:   padding: 0 16px 0 10px;
1.911     bisitz   7946:   background-color:$tabbg;
                   7947:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7948:   border-left: solid 1px $font;
1.721     harmsja  7949: }
1.795     www      7950: 
1.847     tempelho 7951: ul.LC_TabContent .right {
1.911     bisitz   7952:   float:right;
1.847     tempelho 7953: }
                   7954: 
1.911     bisitz   7955: ul.LC_TabContent li a,
                   7956: ul.LC_TabContent li {
                   7957:   color:rgb(47,47,47);
                   7958:   text-decoration:none;
                   7959:   font-size:95%;
                   7960:   font-weight:bold;
1.952     onken    7961:   min-height:20px;
                   7962: }
                   7963: 
1.959     onken    7964: ul.LC_TabContent li a:hover,
                   7965: ul.LC_TabContent li a:focus {
1.952     onken    7966:   color: $button_hover;
1.959     onken    7967:   background:none;
                   7968:   outline:none;
1.952     onken    7969: }
                   7970: 
                   7971: ul.LC_TabContent li:hover {
                   7972:   color: $button_hover;
                   7973:   cursor:pointer;
1.721     harmsja  7974: }
1.795     www      7975: 
1.911     bisitz   7976: ul.LC_TabContent li.active {
1.952     onken    7977:   color: $font;
1.911     bisitz   7978:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7979:   border-bottom:solid 1px #FFFFFF;
                   7980:   cursor: default;
1.744     ehlerst  7981: }
1.795     www      7982: 
1.959     onken    7983: ul.LC_TabContent li.active a {
                   7984:   color:$font;
                   7985:   background:#FFFFFF;
                   7986:   outline: none;
                   7987: }
1.1047    raeburn  7988: 
                   7989: ul.LC_TabContent li.goback {
                   7990:   float: left;
                   7991:   border-left: none;
                   7992: }
                   7993: 
1.870     tempelho 7994: #maincoursedoc {
1.911     bisitz   7995:   clear:both;
1.870     tempelho 7996: }
                   7997: 
                   7998: ul.LC_TabContentBigger {
1.911     bisitz   7999:   display:block;
                   8000:   list-style:none;
                   8001:   padding: 0;
1.870     tempelho 8002: }
                   8003: 
1.795     www      8004: ul.LC_TabContentBigger li {
1.911     bisitz   8005:   vertical-align:bottom;
                   8006:   height: 30px;
                   8007:   font-size:110%;
                   8008:   font-weight:bold;
                   8009:   color: #737373;
1.841     tempelho 8010: }
                   8011: 
1.957     onken    8012: ul.LC_TabContentBigger li.active {
                   8013:   position: relative;
                   8014:   top: 1px;
                   8015: }
                   8016: 
1.870     tempelho 8017: ul.LC_TabContentBigger li a {
1.911     bisitz   8018:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8019:   height: 30px;
                   8020:   line-height: 30px;
                   8021:   text-align: center;
                   8022:   display: block;
                   8023:   text-decoration: none;
1.958     onken    8024:   outline: none;  
1.741     harmsja  8025: }
1.795     www      8026: 
1.870     tempelho 8027: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8028:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8029:   color:$font;
1.744     ehlerst  8030: }
1.795     www      8031: 
1.870     tempelho 8032: ul.LC_TabContentBigger li b {
1.911     bisitz   8033:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8034:   display: block;
                   8035:   float: left;
                   8036:   padding: 0 30px;
1.957     onken    8037:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8038: }
                   8039: 
1.956     onken    8040: ul.LC_TabContentBigger li:hover b {
                   8041:   color:$button_hover;
                   8042: }
                   8043: 
1.870     tempelho 8044: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8045:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8046:   color:$font;
1.957     onken    8047:   border: 0;
1.741     harmsja  8048: }
1.693     droeschl 8049: 
1.870     tempelho 8050: 
1.862     bisitz   8051: ul.LC_CourseBreadcrumbs {
                   8052:   background: $sidebg;
1.1020    raeburn  8053:   height: 2em;
1.862     bisitz   8054:   padding-left: 10px;
1.1020    raeburn  8055:   margin: 0;
1.862     bisitz   8056:   list-style-position: inside;
                   8057: }
                   8058: 
1.911     bisitz   8059: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8060: ol#LC_PathBreadcrumbs {
1.911     bisitz   8061:   padding-left: 10px;
                   8062:   margin: 0;
1.933     droeschl 8063:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8064: }
                   8065: 
1.911     bisitz   8066: ol#LC_MenuBreadcrumbs li,
                   8067: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8068: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8069:   display: inline;
1.933     droeschl 8070:   white-space: normal;  
1.693     droeschl 8071: }
                   8072: 
1.823     bisitz   8073: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8074: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8075:   text-decoration: none;
                   8076:   font-size:90%;
1.693     droeschl 8077: }
1.795     www      8078: 
1.969     droeschl 8079: ol#LC_MenuBreadcrumbs h1 {
                   8080:   display: inline;
                   8081:   font-size: 90%;
                   8082:   line-height: 2.5em;
                   8083:   margin: 0;
                   8084:   padding: 0;
                   8085: }
                   8086: 
1.795     www      8087: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8088:   text-decoration:none;
                   8089:   font-size:100%;
                   8090:   font-weight:bold;
1.693     droeschl 8091: }
1.795     www      8092: 
1.840     bisitz   8093: .LC_Box {
1.911     bisitz   8094:   border: solid 1px $lg_border_color;
                   8095:   padding: 0 10px 10px 10px;
1.746     neumanie 8096: }
1.795     www      8097: 
1.1020    raeburn  8098: .LC_DocsBox {
                   8099:   border: solid 1px $lg_border_color;
                   8100:   padding: 0 0 10px 10px;
                   8101: }
                   8102: 
1.795     www      8103: .LC_AboutMe_Image {
1.911     bisitz   8104:   float:left;
                   8105:   margin-right:10px;
1.747     neumanie 8106: }
1.795     www      8107: 
                   8108: .LC_Clear_AboutMe_Image {
1.911     bisitz   8109:   clear:left;
1.747     neumanie 8110: }
1.795     www      8111: 
1.721     harmsja  8112: dl.LC_ListStyleClean dt {
1.911     bisitz   8113:   padding-right: 5px;
                   8114:   display: table-header-group;
1.693     droeschl 8115: }
                   8116: 
1.721     harmsja  8117: dl.LC_ListStyleClean dd {
1.911     bisitz   8118:   display: table-row;
1.693     droeschl 8119: }
                   8120: 
1.721     harmsja  8121: .LC_ListStyleClean,
                   8122: .LC_ListStyleSimple,
                   8123: .LC_ListStyleNormal,
1.795     www      8124: .LC_ListStyleSpecial {
1.911     bisitz   8125:   /* display:block; */
                   8126:   list-style-position: inside;
                   8127:   list-style-type: none;
                   8128:   overflow: hidden;
                   8129:   padding: 0;
1.693     droeschl 8130: }
                   8131: 
1.721     harmsja  8132: .LC_ListStyleSimple li,
                   8133: .LC_ListStyleSimple dd,
                   8134: .LC_ListStyleNormal li,
                   8135: .LC_ListStyleNormal dd,
                   8136: .LC_ListStyleSpecial li,
1.795     www      8137: .LC_ListStyleSpecial dd {
1.911     bisitz   8138:   margin: 0;
                   8139:   padding: 5px 5px 5px 10px;
                   8140:   clear: both;
1.693     droeschl 8141: }
                   8142: 
1.721     harmsja  8143: .LC_ListStyleClean li,
                   8144: .LC_ListStyleClean dd {
1.911     bisitz   8145:   padding-top: 0;
                   8146:   padding-bottom: 0;
1.693     droeschl 8147: }
                   8148: 
1.721     harmsja  8149: .LC_ListStyleSimple dd,
1.795     www      8150: .LC_ListStyleSimple li {
1.911     bisitz   8151:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8152: }
                   8153: 
1.721     harmsja  8154: .LC_ListStyleSpecial li,
                   8155: .LC_ListStyleSpecial dd {
1.911     bisitz   8156:   list-style-type: none;
                   8157:   background-color: RGB(220, 220, 220);
                   8158:   margin-bottom: 4px;
1.693     droeschl 8159: }
                   8160: 
1.721     harmsja  8161: table.LC_SimpleTable {
1.911     bisitz   8162:   margin:5px;
                   8163:   border:solid 1px $lg_border_color;
1.795     www      8164: }
1.693     droeschl 8165: 
1.721     harmsja  8166: table.LC_SimpleTable tr {
1.911     bisitz   8167:   padding: 0;
                   8168:   border:solid 1px $lg_border_color;
1.693     droeschl 8169: }
1.795     www      8170: 
                   8171: table.LC_SimpleTable thead {
1.911     bisitz   8172:   background:rgb(220,220,220);
1.693     droeschl 8173: }
                   8174: 
1.721     harmsja  8175: div.LC_columnSection {
1.911     bisitz   8176:   display: block;
                   8177:   clear: both;
                   8178:   overflow: hidden;
                   8179:   margin: 0;
1.693     droeschl 8180: }
                   8181: 
1.721     harmsja  8182: div.LC_columnSection>* {
1.911     bisitz   8183:   float: left;
                   8184:   margin: 10px 20px 10px 0;
                   8185:   overflow:hidden;
1.693     droeschl 8186: }
1.721     harmsja  8187: 
1.795     www      8188: table em {
1.911     bisitz   8189:   font-weight: bold;
                   8190:   font-style: normal;
1.748     schulted 8191: }
1.795     www      8192: 
1.779     bisitz   8193: table.LC_tableBrowseRes,
1.795     www      8194: table.LC_tableOfContent {
1.911     bisitz   8195:   border:none;
                   8196:   border-spacing: 1px;
                   8197:   padding: 3px;
                   8198:   background-color: #FFFFFF;
                   8199:   font-size: 90%;
1.753     droeschl 8200: }
1.789     droeschl 8201: 
1.911     bisitz   8202: table.LC_tableOfContent {
                   8203:   border-collapse: collapse;
1.789     droeschl 8204: }
                   8205: 
1.771     droeschl 8206: table.LC_tableBrowseRes a,
1.768     schulted 8207: table.LC_tableOfContent a {
1.911     bisitz   8208:   background-color: transparent;
                   8209:   text-decoration: none;
1.753     droeschl 8210: }
                   8211: 
1.795     www      8212: table.LC_tableOfContent img {
1.911     bisitz   8213:   border: none;
                   8214:   height: 1.3em;
                   8215:   vertical-align: text-bottom;
                   8216:   margin-right: 0.3em;
1.753     droeschl 8217: }
1.757     schulted 8218: 
1.795     www      8219: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8220:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8221: }
                   8222: 
1.795     www      8223: a#LC_content_toolbar_everything {
1.911     bisitz   8224:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8225: }
                   8226: 
1.795     www      8227: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8228:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8229: }
                   8230: 
1.795     www      8231: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8232:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8233: }
                   8234: 
1.795     www      8235: a#LC_content_toolbar_changefolder {
1.911     bisitz   8236:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8237: }
                   8238: 
1.795     www      8239: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8240:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8241: }
                   8242: 
1.1043    raeburn  8243: a#LC_content_toolbar_edittoplevel {
                   8244:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8245: }
                   8246: 
1.1075.2.161.  .12(raeb 8247:-23): a#LC_content_toolbar_printout {
                   8248:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8249:-23): }
                   8250:-23): 
1.795     www      8251: ul#LC_toolbar li a:hover {
1.911     bisitz   8252:   background-position: bottom center;
1.757     schulted 8253: }
                   8254: 
1.795     www      8255: ul#LC_toolbar {
1.911     bisitz   8256:   padding: 0;
                   8257:   margin: 2px;
                   8258:   list-style:none;
                   8259:   position:relative;
                   8260:   background-color:white;
1.1075.2.9  raeburn  8261:   overflow: auto;
1.757     schulted 8262: }
                   8263: 
1.795     www      8264: ul#LC_toolbar li {
1.911     bisitz   8265:   border:1px solid white;
                   8266:   padding: 0;
                   8267:   margin: 0;
                   8268:   float: left;
                   8269:   display:inline;
                   8270:   vertical-align:middle;
1.1075.2.9  raeburn  8271:   white-space: nowrap;
1.911     bisitz   8272: }
1.757     schulted 8273: 
1.783     amueller 8274: 
1.795     www      8275: a.LC_toolbarItem {
1.911     bisitz   8276:   display:block;
                   8277:   padding: 0;
                   8278:   margin: 0;
                   8279:   height: 32px;
                   8280:   width: 32px;
                   8281:   color:white;
                   8282:   border: none;
                   8283:   background-repeat:no-repeat;
                   8284:   background-color:transparent;
1.757     schulted 8285: }
                   8286: 
1.915     droeschl 8287: ul.LC_funclist {
                   8288:     margin: 0;
                   8289:     padding: 0.5em 1em 0.5em 0;
                   8290: }
                   8291: 
1.933     droeschl 8292: ul.LC_funclist > li:first-child {
                   8293:     font-weight:bold; 
                   8294:     margin-left:0.8em;
                   8295: }
                   8296: 
1.915     droeschl 8297: ul.LC_funclist + ul.LC_funclist {
                   8298:     /* 
                   8299:        left border as a seperator if we have more than
                   8300:        one list 
                   8301:     */
                   8302:     border-left: 1px solid $sidebg;
                   8303:     /* 
                   8304:        this hides the left border behind the border of the 
                   8305:        outer box if element is wrapped to the next 'line' 
                   8306:     */
                   8307:     margin-left: -1px;
                   8308: }
                   8309: 
1.843     bisitz   8310: ul.LC_funclist li {
1.915     droeschl 8311:   display: inline;
1.782     bisitz   8312:   white-space: nowrap;
1.915     droeschl 8313:   margin: 0 0 0 25px;
                   8314:   line-height: 150%;
1.782     bisitz   8315: }
                   8316: 
1.974     wenzelju 8317: .LC_hidden {
                   8318:   display: none;
                   8319: }
                   8320: 
1.1030    www      8321: .LCmodal-overlay {
                   8322: 		position:fixed;
                   8323: 		top:0;
                   8324: 		right:0;
                   8325: 		bottom:0;
                   8326: 		left:0;
                   8327: 		height:100%;
                   8328: 		width:100%;
                   8329: 		margin:0;
                   8330: 		padding:0;
                   8331: 		background:#999;
                   8332: 		opacity:.75;
                   8333: 		filter: alpha(opacity=75);
                   8334: 		-moz-opacity: 0.75;
                   8335: 		z-index:101;
                   8336: }
                   8337: 
                   8338: * html .LCmodal-overlay {   
                   8339: 		position: absolute;
                   8340: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8341: }
                   8342: 
                   8343: .LCmodal-window {
                   8344: 		position:fixed;
                   8345: 		top:50%;
                   8346: 		left:50%;
                   8347: 		margin:0;
                   8348: 		padding:0;
                   8349: 		z-index:102;
                   8350: 	}
                   8351: 
                   8352: * html .LCmodal-window {
                   8353: 		position:absolute;
                   8354: }
                   8355: 
                   8356: .LCclose-window {
                   8357: 		position:absolute;
                   8358: 		width:32px;
                   8359: 		height:32px;
                   8360: 		right:8px;
                   8361: 		top:8px;
                   8362: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8363: 		text-indent:-99999px;
                   8364: 		overflow:hidden;
                   8365: 		cursor:pointer;
                   8366: }
                   8367: 
1.1075.2.158  raeburn  8368: .LCisDisabled {
                   8369:   cursor: not-allowed;
                   8370:   opacity: 0.5;
                   8371: }
                   8372: 
                   8373: a[aria-disabled="true"] {
                   8374:   color: currentColor;
                   8375:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8376:   pointer-events: none;
                   8377:   text-decoration: none;
                   8378: }
                   8379: 
1.1075.2.141  raeburn  8380: pre.LC_wordwrap {
                   8381:   white-space: pre-wrap;
                   8382:   white-space: -moz-pre-wrap;
                   8383:   white-space: -pre-wrap;
                   8384:   white-space: -o-pre-wrap;
                   8385:   word-wrap: break-word;
                   8386: }
                   8387: 
1.1075.2.17  raeburn  8388: /*
                   8389:   styles used by TTH when "Default set of options to pass to tth/m
                   8390:   when converting TeX" in course settings has been set
                   8391: 
                   8392:   option passed: -t
                   8393: 
                   8394: */
                   8395: 
                   8396: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8397: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8398: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8399: td div.norm {line-height:normal;}
                   8400: 
                   8401: /*
                   8402:   option passed -y3
                   8403: */
                   8404: 
                   8405: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8406: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8407: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8408: 
1.1075.2.121  raeburn  8409: #LC_minitab_header {
                   8410:   float:left;
                   8411:   width:100%;
                   8412:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8413:   font-size:93%;
                   8414:   line-height:normal;
                   8415:   margin: 0.5em 0 0.5em 0;
                   8416: }
                   8417: #LC_minitab_header ul {
                   8418:   margin:0;
                   8419:   padding:10px 10px 0;
                   8420:   list-style:none;
                   8421: }
                   8422: #LC_minitab_header li {
                   8423:   float:left;
                   8424:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8425:   margin:0;
                   8426:   padding:0 0 0 9px;
                   8427: }
                   8428: #LC_minitab_header a {
                   8429:   display:block;
                   8430:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8431:   padding:5px 15px 4px 6px;
                   8432: }
                   8433: #LC_minitab_header #LC_current_minitab {
                   8434:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8435: }
                   8436: #LC_minitab_header #LC_current_minitab a {
                   8437:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8438:   padding-bottom:5px;
                   8439: }
                   8440: 
                   8441: 
1.343     albertel 8442: END
                   8443: }
                   8444: 
1.306     albertel 8445: =pod
                   8446: 
                   8447: =item * &headtag()
                   8448: 
                   8449: Returns a uniform footer for LON-CAPA web pages.
                   8450: 
1.307     albertel 8451: Inputs: $title - optional title for the head
                   8452:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8453:         $args - optional arguments
1.319     albertel 8454:             force_register - if is true call registerurl so the remote is 
                   8455:                              informed
1.415     albertel 8456:             redirect       -> array ref of
                   8457:                                    1- seconds before redirect occurs
                   8458:                                    2- url to redirect to
                   8459:                                    3- whether the side effect should occur
1.315     albertel 8460:                            (side effect of setting 
                   8461:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8462:22):                                redirected to)
                   8463:22):                                    4- whether the redirect target should be
                   8464:22):                                       the opener of the current (pop-up)
                   8465:22):                                       window (side effect of setting
                   8466:22):                                       $env{'internal.head.to_opener'} to
                   8467:22):                                       1, if true.
          .10(raeb 8468:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8469:             domain         -> force to color decorate a page for a specific
                   8470:                                domain
                   8471:             function       -> force usage of a specific rolish color scheme
                   8472:             bgcolor        -> override the default page bgcolor
1.460     albertel 8473:             no_auto_mt_title
                   8474:                            -> prevent &mt()ing the title arg
1.464     albertel 8475: 
1.306     albertel 8476: =cut
                   8477: 
                   8478: sub headtag {
1.313     albertel 8479:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8480:     
1.363     albertel 8481:     my $function = $args->{'function'} || &get_users_function();
                   8482:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8483:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8484:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8485:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8486: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8487: 		   #time(),
1.418     albertel 8488: 		   $env{'environment.color.timestamp'},
1.363     albertel 8489: 		   $function,$domain,$bgcolor);
                   8490: 
1.369     www      8491:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8492: 
1.308     albertel 8493:     my $result =
                   8494: 	'<head>'.
1.1075.2.56  raeburn  8495: 	&font_settings($args);
1.319     albertel 8496: 
1.1075.2.72  raeburn  8497:     my $inhibitprint;
                   8498:     if ($args->{'print_suppress'}) {
                   8499:         $inhibitprint = &print_suppression();
                   8500:     }
1.1064    raeburn  8501: 
1.461     albertel 8502:     if (!$args->{'frameset'}) {
                   8503: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8504:     }
1.1075.2.12  raeburn  8505:     if ($args->{'force_register'}) {
                   8506:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8507:     }
1.436     albertel 8508:     if (!$args->{'no_nav_bar'} 
                   8509: 	&& !$args->{'only_body'}
                   8510: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8511: 	$result .= &help_menu_js($httphost);
1.1032    www      8512:         $result.=&modal_window();
1.1038    www      8513:         $result.=&togglebox_script();
1.1034    www      8514:         $result.=&wishlist_window();
1.1041    www      8515:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8516:     } else {
                   8517:         if ($args->{'add_modal'}) {
                   8518:            $result.=&modal_window();
                   8519:         }
                   8520:         if ($args->{'add_wishlist'}) {
                   8521:            $result.=&wishlist_window();
                   8522:         }
1.1038    www      8523:         if ($args->{'add_togglebox'}) {
                   8524:            $result.=&togglebox_script();
                   8525:         }
1.1041    www      8526:         if ($args->{'add_progressbar'}) {
                   8527:            $result.=&LCprogressbarUpdate_script();
                   8528:         }
1.436     albertel 8529:     }
1.314     albertel 8530:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8531:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8532:-22):         if (!$skip_enc_check) {
                   8533:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8534:-22):         }
1.414     albertel 8535: 	if (!$inhibit_continue) {
                   8536: 	    $env{'internal.head.redirect'} = $url;
                   8537: 	}
1.1075.2.161.  .9(raebu 8538:22):         $result.=<<"ADDMETA";
1.313     albertel 8539: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8540:22): ADDMETA
                   8541:22):         if ($to_opener) {
                   8542:22):             $env{'internal.head.to_opener'} = 1;
                   8543:22):             my $dest = &js_escape($url);
                   8544:22):             my $timeout = int($time * 1000);
                   8545:22):             $result .=<<"ENDJS";
                   8546:22): <script type="text/javascript">
                   8547:22): // <![CDATA[
                   8548:22): function LC_To_Opener() {
                   8549:22):     var dest = '$dest';
                   8550:22):     if (dest != '') {
                   8551:22):         if (window.opener != null && !window.opener.closed) {
                   8552:22):             window.opener.location.href=dest;
                   8553:22):             window.close();
                   8554:22):         } else {
                   8555:22):             window.location.href=dest;
                   8556:22):         }
                   8557:22):     }
                   8558:22): }
                   8559:22): \$(document).ready(function () {
                   8560:22):     setTimeout('LC_To_Opener()',$timeout);
                   8561:22): });
                   8562:22): // ]]>
                   8563:22): </script>
                   8564:22): ENDJS
                   8565:22):         } else {
                   8566:22):             $result.=<<"ADDMETA";
1.344     albertel 8567: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8568: ADDMETA
1.1075.2.161.  .9(raebu 8569:22):         }
1.1075.2.89  raeburn  8570:     } else {
                   8571:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8572:             my $requrl = $env{'request.uri'};
                   8573:             if ($requrl eq '') {
                   8574:                 $requrl = $ENV{'REQUEST_URI'};
                   8575:                 $requrl =~ s/\?.+$//;
                   8576:             }
                   8577:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8578:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8579:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8580:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8581:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8582:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8583:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8584:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8585:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8586:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8587:                             $offload = 1;
1.1075.2.151  raeburn  8588:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8589:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8590:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8591:                                     $offloadoth = 1;
                   8592:                                     $dom_in_use = $env{'user.domain'};
                   8593:                                 }
                   8594:                             }
1.1075.2.145  raeburn  8595:                         }
                   8596:                     }
                   8597:                     unless ($offload) {
                   8598:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8599:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8600:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8601:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8602:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8603:                                         $offload = 1;
1.1075.2.151  raeburn  8604:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8605:                                         $dom_in_use = $env{'user.domain'};
                   8606:                                     }
1.1075.2.89  raeburn  8607:                                 }
1.1075.2.145  raeburn  8608:                             }
                   8609:                         }
                   8610:                     }
                   8611:                     if ($offload) {
1.1075.2.158  raeburn  8612:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8613:                         if (($newserver eq '') && ($offloadoth)) {
                   8614:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 8615:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  8616:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8617:                             }
                   8618:                         }
1.1075.2.145  raeburn  8619:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8620:                             my $numsec = 5;
                   8621:                             my $timeout = $numsec * 1000;
                   8622:                             my ($newurl,$locknum,%locks,$msg);
                   8623:                             if ($env{'request.role.adv'}) {
                   8624:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8625:                             }
                   8626:                             my $disable_submit = 0;
                   8627:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8628:                                 $disable_submit = 1;
                   8629:                             }
                   8630:                             if ($locknum) {
                   8631:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8632:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8633:                                        join(", ",sort(values(%locks)))."\n";
                   8634:                                 if (&show_course()) {
                   8635:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8636:                                 } else {
1.1075.2.145  raeburn  8637:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8638:                                 }
                   8639:                             } else {
                   8640:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8641:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8642:                                 }
                   8643:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8644:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8645:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8646:                                     $newurl .= '&role='.$env{'request.role'};
                   8647:                                 }
                   8648:                                 if ($env{'request.symb'}) {
                   8649:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8650:                                     if ($shownsymb =~ m{^/enc/}) {
                   8651:                                         my $reqdmajor = 2;
                   8652:                                         my $reqdminor = 11;
                   8653:                                         my $reqdsubminor = 3;
                   8654:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8655:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8656:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8657:                                         if (($major eq '' && $minor eq '') ||
                   8658:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8659:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8660:                                              ($reqdsubminor > $subminor))))) {
                   8661:                                             undef($shownsymb);
                   8662:                                         }
1.1075.2.89  raeburn  8663:                                     }
1.1075.2.145  raeburn  8664:                                     if ($shownsymb) {
                   8665:                                         &js_escape(\$shownsymb);
                   8666:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8667:                                     }
1.1075.2.145  raeburn  8668:                                 } else {
                   8669:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8670:                                     &js_escape(\$shownurl);
                   8671:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8672:                                 }
1.1075.2.145  raeburn  8673:                             }
                   8674:                             &js_escape(\$msg);
                   8675:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8676: <meta http-equiv="pragma" content="no-cache" />
                   8677: <script type="text/javascript">
1.1075.2.92  raeburn  8678: // <![CDATA[
1.1075.2.89  raeburn  8679: function LC_Offload_Now() {
                   8680:     var dest = "$newurl";
                   8681:     if (dest != '') {
                   8682:         window.location.href="$newurl";
                   8683:     }
                   8684: }
1.1075.2.92  raeburn  8685: \$(document).ready(function () {
                   8686:     window.alert('$msg');
                   8687:     if ($disable_submit) {
1.1075.2.89  raeburn  8688:         \$(".LC_hwk_submit").prop("disabled", true);
                   8689:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8690:     }
                   8691:     setTimeout('LC_Offload_Now()', $timeout);
                   8692: });
                   8693: // ]]>
1.1075.2.89  raeburn  8694: </script>
                   8695: OFFLOAD
                   8696:                         }
                   8697:                     }
                   8698:                 }
                   8699:             }
                   8700:         }
1.313     albertel 8701:     }
1.306     albertel 8702:     if (!defined($title)) {
                   8703: 	$title = 'The LearningOnline Network with CAPA';
                   8704:     }
1.460     albertel 8705:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8706:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8707: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8708:     if (!$args->{'frameset'}) {
                   8709:         $result .= ' /';
                   8710:     }
                   8711:     $result .= '>'
1.1064    raeburn  8712:         .$inhibitprint
1.414     albertel 8713: 	.$head_extra;
1.1075.2.108  raeburn  8714:     my $clientmobile;
                   8715:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8716:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8717:     } else {
                   8718:         $clientmobile = $env{'browser.mobile'};
                   8719:     }
                   8720:     if ($clientmobile) {
1.1075.2.42  raeburn  8721:         $result .= '
                   8722: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8723: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8724:     }
1.1075.2.126  raeburn  8725:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8726:     return $result.'</head>';
1.306     albertel 8727: }
                   8728: 
                   8729: =pod
                   8730: 
1.340     albertel 8731: =item * &font_settings()
                   8732: 
                   8733: Returns neccessary <meta> to set the proper encoding
                   8734: 
1.1075.2.56  raeburn  8735: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8736: 
                   8737: =cut
                   8738: 
                   8739: sub font_settings {
1.1075.2.56  raeburn  8740:     my ($args) = @_;
1.340     albertel 8741:     my $headerstring='';
1.1075.2.56  raeburn  8742:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8743:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8744: 	$headerstring.=
1.1075.2.61  raeburn  8745: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8746:         if (!$args->{'frameset'}) {
                   8747:             $headerstring.= ' /';
                   8748:         }
                   8749:         $headerstring .= '>'."\n";
1.340     albertel 8750:     }
                   8751:     return $headerstring;
                   8752: }
                   8753: 
1.341     albertel 8754: =pod
                   8755: 
1.1064    raeburn  8756: =item * &print_suppression()
                   8757: 
                   8758: In course context returns css which causes the body to be blank when media="print",
                   8759: if printout generation is unavailable for the current resource.
                   8760: 
                   8761: This could be because:
                   8762: 
                   8763: (a) printstartdate is in the future
                   8764: 
                   8765: (b) printenddate is in the past
                   8766: 
                   8767: (c) there is an active exam block with "printout"
                   8768: functionality blocked
                   8769: 
                   8770: Users with pav, pfo or evb privileges are exempt.
                   8771: 
                   8772: Inputs: none
                   8773: 
                   8774: =cut
                   8775: 
                   8776: 
                   8777: sub print_suppression {
                   8778:     my $noprint;
                   8779:     if ($env{'request.course.id'}) {
                   8780:         my $scope = $env{'request.course.id'};
                   8781:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8782:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8783:             return;
                   8784:         }
                   8785:         if ($env{'request.course.sec'} ne '') {
                   8786:             $scope .= "/$env{'request.course.sec'}";
                   8787:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8788:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8789:                 return;
1.1064    raeburn  8790:             }
                   8791:         }
                   8792:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8793:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  8794:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   8795:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8796:         if ($blocked) {
                   8797:             my $checkrole = "cm./$cdom/$cnum";
                   8798:             if ($env{'request.course.sec'} ne '') {
                   8799:                 $checkrole .= "/$env{'request.course.sec'}";
                   8800:             }
                   8801:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8802:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8803:                 $noprint = 1;
                   8804:             }
                   8805:         }
                   8806:         unless ($noprint) {
                   8807:             my $symb = &Apache::lonnet::symbread();
                   8808:             if ($symb ne '') {
                   8809:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8810:                 if (ref($navmap)) {
                   8811:                     my $res = $navmap->getBySymb($symb);
                   8812:                     if (ref($res)) {
                   8813:                         if (!$res->resprintable()) {
                   8814:                             $noprint = 1;
                   8815:                         }
                   8816:                     }
                   8817:                 }
                   8818:             }
                   8819:         }
                   8820:         if ($noprint) {
                   8821:             return <<"ENDSTYLE";
                   8822: <style type="text/css" media="print">
                   8823:     body { display:none }
                   8824: </style>
                   8825: ENDSTYLE
                   8826:         }
                   8827:     }
                   8828:     return;
                   8829: }
                   8830: 
                   8831: =pod
                   8832: 
1.341     albertel 8833: =item * &xml_begin()
                   8834: 
                   8835: Returns the needed doctype and <html>
                   8836: 
                   8837: Inputs: none
                   8838: 
                   8839: =cut
                   8840: 
                   8841: sub xml_begin {
1.1075.2.61  raeburn  8842:     my ($is_frameset) = @_;
1.341     albertel 8843:     my $output='';
                   8844: 
                   8845:     if ($env{'browser.mathml'}) {
                   8846: 	$output='<?xml version="1.0"?>'
                   8847:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8848: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8849:             
                   8850: #	    .'<!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">] >'
                   8851: 	    .'<!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">'
                   8852:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8853: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8854:     } elsif ($is_frameset) {
                   8855:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8856:                 '<html>'."\n";
1.341     albertel 8857:     } else {
1.1075.2.61  raeburn  8858: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8859:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8860:     }
                   8861:     return $output;
                   8862: }
1.340     albertel 8863: 
                   8864: =pod
                   8865: 
1.306     albertel 8866: =item * &start_page()
                   8867: 
                   8868: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8869: 
1.648     raeburn  8870: Inputs:
                   8871: 
                   8872: =over 4
                   8873: 
                   8874: $title - optional title for the page
                   8875: 
                   8876: $head_extra - optional extra HTML to incude inside the <head>
                   8877: 
                   8878: $args - additional optional args supported are:
                   8879: 
                   8880: =over 8
                   8881: 
                   8882:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8883:                                     arg on
1.814     bisitz   8884:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8885:              add_entries    -> additional attributes to add to the  <body>
                   8886:              domain         -> force to color decorate a page for a 
1.317     albertel 8887:                                     specific domain
1.648     raeburn  8888:              function       -> force usage of a specific rolish color
1.317     albertel 8889:                                     scheme
1.648     raeburn  8890:              redirect       -> see &headtag()
                   8891:              bgcolor        -> override the default page bg color
                   8892:              js_ready       -> return a string ready for being used in 
1.317     albertel 8893:                                     a javascript writeln
1.648     raeburn  8894:              html_encode    -> return a string ready for being used in 
1.320     albertel 8895:                                     a html attribute
1.648     raeburn  8896:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8897:                                     $forcereg arg
1.648     raeburn  8898:              frameset       -> if true will start with a <frameset>
1.330     albertel 8899:                                     rather than <body>
1.648     raeburn  8900:              skip_phases    -> hash ref of 
1.338     albertel 8901:                                     head -> skip the <html><head> generation
                   8902:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8903:              no_inline_link -> if true and in remote mode, don't show the
                   8904:                                     'Switch To Inline Menu' link
1.648     raeburn  8905:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8906:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8907:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8908:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8909:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8910:              group          -> includes the current group, if page is for a
                   8911:                                specific group
1.1075.2.133  raeburn  8912:              use_absolute   -> for request for external resource or syllabus, this
                   8913:                                will contain https://<hostname> if server uses
                   8914:                                https (as per hosts.tab), but request is for http
                   8915:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  8916:              links_disabled -> Links in primary and secondary menus are disabled
                   8917:                                (Can enable them once page has loaded - see lonroles.pm
                   8918:                                for an example).
1.1075.2.161.  .6(raebu 8919:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 8920: 
1.648     raeburn  8921: =back
1.460     albertel 8922: 
1.648     raeburn  8923: =back
1.562     albertel 8924: 
1.306     albertel 8925: =cut
                   8926: 
                   8927: sub start_page {
1.309     albertel 8928:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8929:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8930: 
1.315     albertel 8931:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 8932:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8933: 
1.338     albertel 8934:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8935:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8936:     }
1.1075.2.161.  .1(raebu 8937:21): 
                   8938:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   8939:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8940:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8941:21):                 $args->{'no_primary_menu'} = 1;
                   8942:21):             }
                   8943:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8944:21):                 $args->{'no_inline_menu'} = 1;
                   8945:21):             }
                   8946:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8947:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8948:21):             }
                   8949:21):         } else {
                   8950:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8951:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8952:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8953:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8954:21):                     $args->{'no_primary_menu'} = 1;
                   8955:21):                 }
                   8956:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8957:21):                     $args->{'no_inline_menu'} = 1;
                   8958:21):                 }
                   8959:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8960:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8961:21):                 }
                   8962:21):             }
                   8963:21):         }
                   8964:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8965:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8966:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8967:21):     } elsif ($env{'request.course.id'}) {
                   8968:21):         my $expiretime=600;
                   8969:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   8970:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   8971:21):         }
                   8972:21):         my ($deeplinkmenu,$menuref);
                   8973:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   8974:21):         if ($menucoll) {
                   8975:21):             if (ref($menuref) eq 'HASH') {
                   8976:21):                 %menu = %{$menuref};
                   8977:21):             }
                   8978:21):             if ($menu{'top'} eq 'n') {
                   8979:21):                 $args->{'no_primary_menu'} = 1;
                   8980:21):             }
                   8981:21):             if ($menu{'inline'} eq 'n') {
                   8982:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   8983:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8984:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8985:21):                     my $crstype = &course_type();
                   8986:21):                     my $now = time;
                   8987:21):                     my $ccrole;
                   8988:21):                     if ($crstype eq 'Community') {
                   8989:21):                         $ccrole = 'co';
                   8990:21):                     } else {
                   8991:21):                         $ccrole = 'cc';
                   8992:21):                     }
                   8993:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   8994:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   8995:21):                         if ((($start) && ($start<0)) ||
                   8996:21):                             (($end) && ($end<$now))  ||
                   8997:21):                             (($start) && ($now<$start))) {
                   8998:21):                             $args->{'no_inline_menu'} = 1;
                   8999:21):                         }
                   9000:21):                     } else {
                   9001:21):                         $args->{'no_inline_menu'} = 1;
                   9002:21):                     }
                   9003:21):                 }
                   9004:21):             }
                   9005:21):         }
                   9006:21):     }
          .4(raebu 9007:22): 
          .8(raebu 9008:22):     my $showncrumbs;
1.338     albertel 9009:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9010: 	if ($args->{'frameset'}) {
                   9011: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9012: 						$args->{'add_entries'});
                   9013: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9014:         } else {
                   9015:             $result .=
                   9016:                 &bodytag($title, 
                   9017:                          $args->{'function'},       $args->{'add_entries'},
                   9018:                          $args->{'only_body'},      $args->{'domain'},
                   9019:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  9020:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 9021:21):                          $args,                     \@advtools,
          .8(raebu 9022:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   9023:         }
1.330     albertel 9024:     }
1.338     albertel 9025: 
1.315     albertel 9026:     if ($args->{'js_ready'}) {
1.713     kaisler  9027: 		$result = &js_ready($result);
1.315     albertel 9028:     }
1.320     albertel 9029:     if ($args->{'html_encode'}) {
1.713     kaisler  9030: 		$result = &html_encode($result);
                   9031:     }
                   9032: 
1.813     bisitz   9033:     # Preparation for new and consistent functionlist at top of screen
                   9034:     # if ($args->{'functionlist'}) {
                   9035:     #            $result .= &build_functionlist();
                   9036:     #}
                   9037: 
1.964     droeschl 9038:     # Don't add anything more if only_body wanted or in const space
                   9039:     return $result if    $args->{'only_body'} 
                   9040:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9041: 
                   9042:     #Breadcrumbs
1.758     kaisler  9043:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 9044:22):         unless ($showncrumbs) {
1.758     kaisler  9045: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9046: 		#if any br links exists, add them to the breadcrumbs
                   9047: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9048: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9049: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9050: 			}
                   9051: 		}
1.1075.2.19  raeburn  9052:                 # if @advtools array contains items add then to the breadcrumbs
                   9053:                 if (@advtools > 0) {
                   9054:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9055:                 }
1.1075.2.123  raeburn  9056:                 my $menulink;
                   9057:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 9058:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   9059:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  9060:                     $menulink = 0;
                   9061:                 } else {
                   9062:                     undef($menulink);
                   9063:                 }
1.1075.2.161.  .8(raebu 9064:22):                 my $linkprotout;
                   9065:22):                 if ($env{'request.deeplink.login'}) {
                   9066:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9067:22):                     if ($linkprotout) {
                   9068:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9069:22):                     }
                   9070:22):                 }
1.758     kaisler  9071: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9072: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  9073: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 9074:21): 		} else {
1.1075.2.123  raeburn  9075: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9076: 		}
1.1075.2.161.  .8(raebu 9077:22):         }
1.1075.2.24  raeburn  9078:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9079:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9080:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9081:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9082:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9083:     }
1.315     albertel 9084:     return $result;
1.306     albertel 9085: }
                   9086: 
                   9087: sub end_page {
1.315     albertel 9088:     my ($args) = @_;
                   9089:     $env{'internal.end_page'}++;
1.330     albertel 9090:     my $result;
1.335     albertel 9091:     if ($args->{'discussion'}) {
                   9092: 	my ($target,$parser);
                   9093: 	if (ref($args->{'discussion'})) {
                   9094: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9095: 				$args->{'discussion'}{'parser'});
                   9096: 	}
                   9097: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9098:     }
1.330     albertel 9099:     if ($args->{'frameset'}) {
                   9100: 	$result .= '</frameset>';
                   9101:     } else {
1.635     raeburn  9102: 	$result .= &endbodytag($args);
1.330     albertel 9103:     }
1.1075.2.6  raeburn  9104:     unless ($args->{'notbody'}) {
                   9105:         $result .= "\n</html>";
                   9106:     }
1.330     albertel 9107: 
1.315     albertel 9108:     if ($args->{'js_ready'}) {
1.317     albertel 9109: 	$result = &js_ready($result);
1.315     albertel 9110:     }
1.335     albertel 9111: 
1.320     albertel 9112:     if ($args->{'html_encode'}) {
                   9113: 	$result = &html_encode($result);
                   9114:     }
1.335     albertel 9115: 
1.315     albertel 9116:     return $result;
                   9117: }
                   9118: 
1.1075.2.161.  .1(raebu 9119:21): sub menucoll_in_effect {
                   9120:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9121:21):     if ($env{'request.course.id'}) {
                   9122:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9123:21):         if ($env{'request.deeplink.login'}) {
                   9124:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9125:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9126:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9127:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9128:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9129:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9130:21):                     if (ref($navmap)) {
                   9131:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9132:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9133:21):                                                           '0.deeplink');
                   9134:21):                     } else {
                   9135:21):                         $check_login_symb = 1;
                   9136:21):                     }
                   9137:21):                 } else {
                   9138:21):                     my $symb=&Apache::lonnet::symbread();
                   9139:21):                     if ($symb) {
                   9140:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9141:21):                     } else {
                   9142:21):                         $check_login_symb = 1;
                   9143:21):                     }
                   9144:21):                 }
                   9145:21):             } else {
                   9146:21):                 $check_login_symb = 1;
                   9147:21):             }
                   9148:21):             if ($check_login_symb) {
                   9149:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9150:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9151:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9152:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9153:21):                     if (ref($navmap)) {
                   9154:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9155:21):                     }
                   9156:21):                 } else {
                   9157:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9158:21):                 }
                   9159:21):             }
                   9160:21):             if ($deeplink ne '') {
          .6(raebu 9161:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9162:21):                 if ($display =~ /^\d+$/) {
                   9163:21):                     $deeplinkmenu = 1;
                   9164:21):                     $menucoll = $display;
                   9165:21):                 }
                   9166:21):             }
                   9167:21):         }
                   9168:21):         if ($menucoll) {
                   9169:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9170:21):         }
                   9171:21):     }
                   9172:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9173:21): }
                   9174:21): 
                   9175:21): sub deeplink_login_symb {
                   9176:21):     my ($cnum,$cdom) = @_;
                   9177:21):     my $login_symb;
                   9178:21):     if ($env{'request.deeplink.login'}) {
                   9179:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9180:21):     }
                   9181:21):     return $login_symb;
                   9182:21): }
                   9183:21): 
                   9184:21): sub symb_from_tinyurl {
                   9185:21):     my ($url,$cnum,$cdom) = @_;
                   9186:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9187:21):         my $key = $1;
                   9188:21):         my ($tinyurl,$login);
                   9189:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9190:21):         if (defined($cached)) {
                   9191:21):             $tinyurl = $result;
                   9192:21):         } else {
                   9193:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9194:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9195:21):             if ($currtiny{$key} ne '') {
                   9196:21):                 $tinyurl = $currtiny{$key};
                   9197:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9198:21):             }
                   9199:21):         }
                   9200:21):         if ($tinyurl ne '') {
                   9201:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9202:21):             if (wantarray) {
                   9203:21):                 return ($cnumreq,$symb);
                   9204:21):             } elsif ($cnumreq eq $cnum) {
                   9205:21):                 return $symb;
                   9206:21):             }
                   9207:21):         }
                   9208:21):     }
                   9209:21):     if (wantarray) {
                   9210:21):         return ();
                   9211:21):     } else {
                   9212:21):         return;
                   9213:21):     }
                   9214:21): }
                   9215:21): 
          .17(raeb 9216:-23): sub usable_exttools {
                   9217:-23):     my %tooltypes;
                   9218:-23):     if ($env{'request.course.id'}) {
                   9219:-23):         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9220:-23):            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9221:-23):                %tooltypes = (
                   9222:-23):                              crs => 1,
                   9223:-23):                              dom => 1,
                   9224:-23):                             );
                   9225:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9226:-23):                $tooltypes{'crs'} = 1;
                   9227:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9228:-23):                $tooltypes{'dom'} = 1;
                   9229:-23):            }
                   9230:-23):         } else {
                   9231:-23):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9232:-23):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9233:-23):             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9234:-23):             if ($crstype eq '') {
                   9235:-23):                 $crstype = 'course';
                   9236:-23):             }
                   9237:-23):             if ($crstype eq 'course') {
                   9238:-23):                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9239:-23):                     $crstype = 'official';
                   9240:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9241:-23):                     $crstype = 'textbook';
                   9242:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9243:-23):                     $crstype = 'lti';
                   9244:-23):                 } else {
                   9245:-23):                     $crstype = 'unofficial';
                   9246:-23):                 }
                   9247:-23):             }
                   9248:-23):             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9249:-23):             if ($domdefaults{$crstype.'domexttool'}) {
                   9250:-23):                 $tooltypes{'dom'} = 1;
                   9251:-23):             }
                   9252:-23):             if ($domdefaults{$crstype.'exttool'}) {
                   9253:-23):                 $tooltypes{'crs'} = 1;
                   9254:-23):             }
                   9255:-23):         }
                   9256:-23):     }
                   9257:-23):     return %tooltypes;
                   9258:-23): }
                   9259:-23): 
1.1034    www      9260: sub wishlist_window {
                   9261:     return(<<'ENDWISHLIST');
1.1046    raeburn  9262: <script type="text/javascript">
1.1034    www      9263: // <![CDATA[
                   9264: // <!-- BEGIN LON-CAPA Internal
                   9265: function set_wishlistlink(title, path) {
                   9266:     if (!title) {
                   9267:         title = document.title;
                   9268:         title = title.replace(/^LON-CAPA /,'');
                   9269:     }
1.1075.2.65  raeburn  9270:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9271:     title = title.replace("'","\\\'");
1.1034    www      9272:     if (!path) {
                   9273:         path = location.pathname;
                   9274:     }
1.1075.2.65  raeburn  9275:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9276:     path = path.replace("'","\\\'");
1.1034    www      9277:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9278:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9279: }
                   9280: // END LON-CAPA Internal -->
                   9281: // ]]>
                   9282: </script>
                   9283: ENDWISHLIST
                   9284: }
                   9285: 
1.1030    www      9286: sub modal_window {
                   9287:     return(<<'ENDMODAL');
1.1046    raeburn  9288: <script type="text/javascript">
1.1030    www      9289: // <![CDATA[
                   9290: // <!-- BEGIN LON-CAPA Internal
                   9291: var modalWindow = {
                   9292: 	parent:"body",
                   9293: 	windowId:null,
                   9294: 	content:null,
                   9295: 	width:null,
                   9296: 	height:null,
                   9297: 	close:function()
                   9298: 	{
                   9299: 	        $(".LCmodal-window").remove();
                   9300: 	        $(".LCmodal-overlay").remove();
                   9301: 	},
                   9302: 	open:function()
                   9303: 	{
                   9304: 		var modal = "";
                   9305: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9306: 		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;\">";
                   9307: 		modal += this.content;
                   9308: 		modal += "</div>";	
                   9309: 
                   9310: 		$(this.parent).append(modal);
                   9311: 
                   9312: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9313: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9314: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9315: 	}
                   9316: };
1.1075.2.42  raeburn  9317: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9318: 	{
1.1075.2.119  raeburn  9319:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9320: 		modalWindow.windowId = "myModal";
                   9321: 		modalWindow.width = width;
                   9322: 		modalWindow.height = height;
1.1075.2.80  raeburn  9323: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9324: 		modalWindow.open();
1.1075.2.87  raeburn  9325: 	};
1.1030    www      9326: // END LON-CAPA Internal -->
                   9327: // ]]>
                   9328: </script>
                   9329: ENDMODAL
                   9330: }
                   9331: 
                   9332: sub modal_link {
1.1075.2.42  raeburn  9333:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9334:     unless ($width) { $width=480; }
                   9335:     unless ($height) { $height=400; }
1.1031    www      9336:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9337:     unless ($transparency) { $transparency='true'; }
                   9338: 
1.1074    raeburn  9339:     my $target_attr;
                   9340:     if (defined($target)) {
                   9341:         $target_attr = 'target="'.$target.'"';
                   9342:     }
                   9343:     return <<"ENDLINK";
1.1075.2.143  raeburn  9344: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9345: ENDLINK
1.1030    www      9346: }
                   9347: 
1.1032    www      9348: sub modal_adhoc_script {
1.1075.2.155  raeburn  9349:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9350:     my $mathjax;
                   9351:     if ($possmathjax) {
                   9352:         $mathjax = <<'ENDJAX';
                   9353:                if (typeof MathJax == 'object') {
                   9354:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9355:                }
                   9356: ENDJAX
                   9357:     }
1.1032    www      9358:     return (<<ENDADHOC);
1.1046    raeburn  9359: <script type="text/javascript">
1.1032    www      9360: // <![CDATA[
                   9361:         var $funcname = function()
                   9362:         {
                   9363:                 modalWindow.windowId = "myModal";
                   9364:                 modalWindow.width = $width;
                   9365:                 modalWindow.height = $height;
                   9366:                 modalWindow.content = '$content';
                   9367:                 modalWindow.open();
1.1075.2.155  raeburn  9368:                 $mathjax
1.1032    www      9369:         };  
                   9370: // ]]>
                   9371: </script>
                   9372: ENDADHOC
                   9373: }
                   9374: 
1.1041    www      9375: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9376:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9377:     my $innerwidth=$width-20;
                   9378:     $content=&js_ready(
1.1042    www      9379:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9380:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9381:                  $content.
1.1041    www      9382:                  &end_scrollbox().
1.1075.2.42  raeburn  9383:                  &end_page()
1.1041    www      9384:              );
1.1075.2.155  raeburn  9385:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9386: }
                   9387: 
                   9388: sub modal_adhoc_window {
1.1075.2.155  raeburn  9389:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9390:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9391:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9392: }
                   9393: 
                   9394: sub modal_adhoc_launch {
                   9395:     my ($funcname,$width,$height,$content)=@_;
                   9396:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9397: <script type="text/javascript">
                   9398: // <![CDATA[
                   9399: $funcname();
                   9400: // ]]>
                   9401: </script>
                   9402: ENDLAUNCH
                   9403: }
                   9404: 
                   9405: sub modal_adhoc_close {
                   9406:     return (<<ENDCLOSE);
                   9407: <script type="text/javascript">
                   9408: // <![CDATA[
                   9409: modalWindow.close();
                   9410: // ]]>
                   9411: </script>
                   9412: ENDCLOSE
                   9413: }
                   9414: 
1.1038    www      9415: sub togglebox_script {
                   9416:    return(<<ENDTOGGLE);
                   9417: <script type="text/javascript"> 
                   9418: // <![CDATA[
                   9419: function LCtoggleDisplay(id,hidetext,showtext) {
                   9420:    link = document.getElementById(id + "link").childNodes[0];
                   9421:    with (document.getElementById(id).style) {
                   9422:       if (display == "none" ) {
                   9423:           display = "inline";
                   9424:           link.nodeValue = hidetext;
                   9425:         } else {
                   9426:           display = "none";
                   9427:           link.nodeValue = showtext;
                   9428:        }
                   9429:    }
                   9430: }
                   9431: // ]]>
                   9432: </script>
                   9433: ENDTOGGLE
                   9434: }
                   9435: 
1.1039    www      9436: sub start_togglebox {
                   9437:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9438:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9439:     unless ($showtext) { $showtext=&mt('show'); }
                   9440:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9441:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9442:     return &start_data_table().
                   9443:            &start_data_table_header_row().
                   9444:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9445:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9446:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9447:            &end_data_table_header_row().
                   9448:            '<tr id="'.$id.'" style="display:none""><td>';
                   9449: }
                   9450: 
                   9451: sub end_togglebox {
                   9452:     return '</td></tr>'.&end_data_table();
                   9453: }
                   9454: 
1.1041    www      9455: sub LCprogressbar_script {
1.1075.2.130  raeburn  9456:    my ($id,$number_to_do)=@_;
                   9457:    if ($number_to_do) {
                   9458:        return(<<ENDPROGRESS);
1.1041    www      9459: <script type="text/javascript">
                   9460: // <![CDATA[
1.1045    www      9461: \$('#progressbar$id').progressbar({
1.1041    www      9462:   value: 0,
                   9463:   change: function(event, ui) {
                   9464:     var newVal = \$(this).progressbar('option', 'value');
                   9465:     \$('.pblabel', this).text(LCprogressTxt);
                   9466:   }
                   9467: });
                   9468: // ]]>
                   9469: </script>
                   9470: ENDPROGRESS
1.1075.2.130  raeburn  9471:    } else {
                   9472:        return(<<ENDPROGRESS);
                   9473: <script type="text/javascript">
                   9474: // <![CDATA[
                   9475: \$('#progressbar$id').progressbar({
                   9476:   value: false,
                   9477:   create: function(event, ui) {
                   9478:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9479:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9480:   }
                   9481: });
                   9482: // ]]>
                   9483: </script>
                   9484: ENDPROGRESS
                   9485:    }
1.1041    www      9486: }
                   9487: 
                   9488: sub LCprogressbarUpdate_script {
                   9489:    return(<<ENDPROGRESSUPDATE);
                   9490: <style type="text/css">
                   9491: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9492: .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      9493: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9494: </style>
                   9495: <script type="text/javascript">
                   9496: // <![CDATA[
1.1045    www      9497: var LCprogressTxt='---';
                   9498: 
1.1075.2.130  raeburn  9499: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9500:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9501:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9502:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9503:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9504:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9505:    } else {
                   9506:        \$('#progressbar'+id).progressbar('value',percent);
                   9507:    }
1.1041    www      9508: }
                   9509: // ]]>
                   9510: </script>
                   9511: ENDPROGRESSUPDATE
                   9512: }
                   9513: 
1.1042    www      9514: my $LClastpercent;
1.1045    www      9515: my $LCidcnt;
                   9516: my $LCcurrentid;
1.1042    www      9517: 
1.1041    www      9518: sub LCprogressbar {
1.1075.2.130  raeburn  9519:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9520:     $LClastpercent=0;
1.1045    www      9521:     $LCidcnt++;
                   9522:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9523:     my ($starting,$content);
                   9524:     if ($number_to_do) {
                   9525:         $starting=&mt('Starting');
                   9526:         $content=(<<ENDPROGBAR);
                   9527: $preamble
1.1045    www      9528:   <div id="progressbar$LCcurrentid">
1.1041    www      9529:     <span class="pblabel">$starting</span>
                   9530:   </div>
                   9531: ENDPROGBAR
1.1075.2.130  raeburn  9532:     } else {
                   9533:         $starting=&mt('Loading...');
                   9534:         $LClastpercent='false';
                   9535:         $content=(<<ENDPROGBAR);
                   9536: $preamble
                   9537:   <div id="progressbar$LCcurrentid">
                   9538:       <div class="progress-label">$starting</div>
                   9539:   </div>
                   9540: ENDPROGBAR
                   9541:     }
                   9542:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9543: }
                   9544: 
                   9545: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9546:     my ($r,$val,$text,$number_to_do)=@_;
                   9547:     if ($number_to_do) {
                   9548:         unless ($val) { 
                   9549:             if ($LClastpercent) {
                   9550:                 $val=$LClastpercent;
                   9551:             } else {
                   9552:                 $val=0;
                   9553:             }
                   9554:         }
                   9555:         if ($val<0) { $val=0; }
                   9556:         if ($val>100) { $val=0; }
                   9557:         $LClastpercent=$val;
                   9558:         unless ($text) { $text=$val.'%'; }
                   9559:     } else {
                   9560:         $val = 'false';
1.1042    www      9561:     }
1.1041    www      9562:     $text=&js_ready($text);
1.1044    www      9563:     &r_print($r,<<ENDUPDATE);
1.1041    www      9564: <script type="text/javascript">
                   9565: // <![CDATA[
1.1075.2.130  raeburn  9566: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9567: // ]]>
                   9568: </script>
                   9569: ENDUPDATE
1.1035    www      9570: }
                   9571: 
1.1042    www      9572: sub LCprogressbarClose {
                   9573:     my ($r)=@_;
                   9574:     $LClastpercent=0;
1.1044    www      9575:     &r_print($r,<<ENDCLOSE);
1.1042    www      9576: <script type="text/javascript">
                   9577: // <![CDATA[
1.1045    www      9578: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9579: // ]]>
                   9580: </script>
                   9581: ENDCLOSE
1.1044    www      9582: }
                   9583: 
                   9584: sub r_print {
                   9585:     my ($r,$to_print)=@_;
                   9586:     if ($r) {
                   9587:       $r->print($to_print);
                   9588:       $r->rflush();
                   9589:     } else {
                   9590:       print($to_print);
                   9591:     }
1.1042    www      9592: }
                   9593: 
1.320     albertel 9594: sub html_encode {
                   9595:     my ($result) = @_;
                   9596: 
1.322     albertel 9597:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9598:     
                   9599:     return $result;
                   9600: }
1.1044    www      9601: 
1.317     albertel 9602: sub js_ready {
                   9603:     my ($result) = @_;
                   9604: 
1.323     albertel 9605:     $result =~ s/[\n\r]/ /xmsg;
                   9606:     $result =~ s/\\/\\\\/xmsg;
                   9607:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9608:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9609:     
                   9610:     return $result;
                   9611: }
                   9612: 
1.315     albertel 9613: sub validate_page {
                   9614:     if (  exists($env{'internal.start_page'})
1.316     albertel 9615: 	  &&     $env{'internal.start_page'} > 1) {
                   9616: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9617: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9618: 				 $ENV{'request.filename'});
1.315     albertel 9619:     }
                   9620:     if (  exists($env{'internal.end_page'})
1.316     albertel 9621: 	  &&     $env{'internal.end_page'} > 1) {
                   9622: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9623: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9624: 				 $env{'request.filename'});
1.315     albertel 9625:     }
                   9626:     if (     exists($env{'internal.start_page'})
                   9627: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9628: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9629: 				 $env{'request.filename'});
1.315     albertel 9630:     }
                   9631:     if (   ! exists($env{'internal.start_page'})
                   9632: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9633: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9634: 				 $env{'request.filename'});
1.315     albertel 9635:     }
1.306     albertel 9636: }
1.315     albertel 9637: 
1.996     www      9638: 
                   9639: sub start_scrollbox {
1.1075.2.56  raeburn  9640:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9641:     unless ($outerwidth) { $outerwidth='520px'; }
                   9642:     unless ($width) { $width='500px'; }
                   9643:     unless ($height) { $height='200px'; }
1.1075    raeburn  9644:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9645:     if ($id ne '') {
1.1075.2.42  raeburn  9646:         $table_id = ' id="table_'.$id.'"';
                   9647:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9648:     }
1.1075    raeburn  9649:     if ($bgcolor ne '') {
                   9650:         $tdcol = "background-color: $bgcolor;";
                   9651:     }
1.1075.2.42  raeburn  9652:     my $nicescroll_js;
                   9653:     if ($env{'browser.mobile'}) {
                   9654:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9655:     }
1.1075    raeburn  9656:     return <<"END";
1.1075.2.42  raeburn  9657: $nicescroll_js
                   9658: 
                   9659: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  9660: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  9661: END
1.996     www      9662: }
                   9663: 
                   9664: sub end_scrollbox {
1.1036    www      9665:     return '</div></td></tr></table>';
1.996     www      9666: }
                   9667: 
1.1075.2.42  raeburn  9668: sub nicescroll_javascript {
                   9669:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9670:     my %options;
                   9671:     if (ref($cursor) eq 'HASH') {
                   9672:         %options = %{$cursor};
                   9673:     }
                   9674:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9675:         $options{'railalign'} = 'left';
                   9676:     }
                   9677:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9678:         my $function  = &get_users_function();
                   9679:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   9680:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9681:             $options{'cursorcolor'} = '#00F';
                   9682:         }
                   9683:     }
                   9684:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9685:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   9686:             $options{'cursoropacity'}='1.0';
                   9687:         }
                   9688:     } else {
                   9689:         $options{'cursoropacity'}='1.0';
                   9690:     }
                   9691:     if ($options{'cursorfixedheight'} eq 'none') {
                   9692:         delete($options{'cursorfixedheight'});
                   9693:     } else {
                   9694:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9695:     }
                   9696:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9697:         delete($options{'railoffset'});
                   9698:     }
                   9699:     my @niceoptions;
                   9700:     while (my($key,$value) = each(%options)) {
                   9701:         if ($value =~ /^\{.+\}$/) {
                   9702:             push(@niceoptions,$key.':'.$value);
                   9703:         } else {
                   9704:             push(@niceoptions,$key.':"'.$value.'"');
                   9705:         }
                   9706:     }
                   9707:     my $nicescroll_js = '
                   9708: $(document).ready(
                   9709:       function() {
                   9710:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9711:       }
                   9712: );
                   9713: ';
                   9714:     if ($framecheck) {
                   9715:         $nicescroll_js .= '
                   9716: function expand_div(caller) {
                   9717:     if (top === self) {
                   9718:         document.getElementById("'.$id.'").style.width = "auto";
                   9719:         document.getElementById("'.$id.'").style.height = "auto";
                   9720:     } else {
                   9721:         try {
                   9722:             if (parent.frames) {
                   9723:                 if (parent.frames.length > 1) {
                   9724:                     var framesrc = parent.frames[1].location.href;
                   9725:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9726:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9727:                         document.getElementById("'.$id.'").style.width = "auto";
                   9728:                         document.getElementById("'.$id.'").style.height = "auto";
                   9729:                     }
                   9730:                 }
                   9731:             }
                   9732:         } catch (e) {
                   9733:             return;
                   9734:         }
                   9735:     }
                   9736:     return;
                   9737: }
                   9738: ';
                   9739:     }
                   9740:     if ($needjsready) {
                   9741:         $nicescroll_js = '
                   9742: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9743:     } else {
                   9744:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9745:     }
                   9746:     return $nicescroll_js;
                   9747: }
                   9748: 
1.318     albertel 9749: sub simple_error_page {
1.1075.2.49  raeburn  9750:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 9751:22):     my %displayargs;
1.1075.2.49  raeburn  9752:     if (ref($args) eq 'HASH') {
                   9753:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 9754:22):         if ($args->{'only_body'}) {
                   9755:22):             $displayargs{'only_body'} = 1;
                   9756:22):         }
                   9757:22):         if ($args->{'no_nav_bar'}) {
                   9758:22):             $displayargs{'no_nav_bar'} = 1;
                   9759:22):         }
1.1075.2.49  raeburn  9760:     } else {
                   9761:         $msg = &mt($msg);
                   9762:     }
                   9763: 
1.318     albertel 9764:     my $page =
1.1075.2.161.  .4(raebu 9765:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  9766: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9767: 	&Apache::loncommon::end_page();
                   9768:     if (ref($r)) {
                   9769: 	$r->print($page);
1.327     albertel 9770: 	return;
1.318     albertel 9771:     }
                   9772:     return $page;
                   9773: }
1.347     albertel 9774: 
                   9775: {
1.610     albertel 9776:     my @row_count;
1.961     onken    9777: 
                   9778:     sub start_data_table_count {
                   9779:         unshift(@row_count, 0);
                   9780:         return;
                   9781:     }
                   9782: 
                   9783:     sub end_data_table_count {
                   9784:         shift(@row_count);
                   9785:         return;
                   9786:     }
                   9787: 
1.347     albertel 9788:     sub start_data_table {
1.1018    raeburn  9789: 	my ($add_class,$id) = @_;
1.422     albertel 9790: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9791:         my $table_id;
                   9792:         if (defined($id)) {
                   9793:             $table_id = ' id="'.$id.'"';
                   9794:         }
1.961     onken    9795: 	&start_data_table_count();
1.1018    raeburn  9796: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9797:     }
                   9798: 
                   9799:     sub end_data_table {
1.961     onken    9800: 	&end_data_table_count();
1.389     albertel 9801: 	return '</table>'."\n";;
1.347     albertel 9802:     }
                   9803: 
                   9804:     sub start_data_table_row {
1.974     wenzelju 9805: 	my ($add_class, $id) = @_;
1.610     albertel 9806: 	$row_count[0]++;
                   9807: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9808: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9809:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9810:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9811:     }
1.471     banghart 9812:     
                   9813:     sub continue_data_table_row {
1.974     wenzelju 9814: 	my ($add_class, $id) = @_;
1.610     albertel 9815: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9816: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9817:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9818:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9819:     }
1.347     albertel 9820: 
                   9821:     sub end_data_table_row {
1.389     albertel 9822: 	return '</tr>'."\n";;
1.347     albertel 9823:     }
1.367     www      9824: 
1.421     albertel 9825:     sub start_data_table_empty_row {
1.707     bisitz   9826: #	$row_count[0]++;
1.421     albertel 9827: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9828:     }
                   9829: 
                   9830:     sub end_data_table_empty_row {
                   9831: 	return '</tr>'."\n";;
                   9832:     }
                   9833: 
1.367     www      9834:     sub start_data_table_header_row {
1.389     albertel 9835: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9836:     }
                   9837: 
                   9838:     sub end_data_table_header_row {
1.389     albertel 9839: 	return '</tr>'."\n";;
1.367     www      9840:     }
1.890     droeschl 9841: 
                   9842:     sub data_table_caption {
                   9843:         my $caption = shift;
                   9844:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9845:     }
1.347     albertel 9846: }
                   9847: 
1.548     albertel 9848: =pod
                   9849: 
                   9850: =item * &inhibit_menu_check($arg)
                   9851: 
                   9852: Checks for a inhibitmenu state and generates output to preserve it
                   9853: 
                   9854: Inputs:         $arg - can be any of
                   9855:                      - undef - in which case the return value is a string 
                   9856:                                to add  into arguments list of a uri
                   9857:                      - 'input' - in which case the return value is a HTML
                   9858:                                  <form> <input> field of type hidden to
                   9859:                                  preserve the value
                   9860:                      - a url - in which case the return value is the url with
                   9861:                                the neccesary cgi args added to preserve the
                   9862:                                inhibitmenu state
                   9863:                      - a ref to a url - no return value, but the string is
                   9864:                                         updated to include the neccessary cgi
                   9865:                                         args to preserve the inhibitmenu state
                   9866: 
                   9867: =cut
                   9868: 
                   9869: sub inhibit_menu_check {
                   9870:     my ($arg) = @_;
                   9871:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9872:     if ($arg eq 'input') {
                   9873: 	if ($env{'form.inhibitmenu'}) {
                   9874: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9875: 	} else {
                   9876: 	    return
                   9877: 	}
                   9878:     }
                   9879:     if ($env{'form.inhibitmenu'}) {
                   9880: 	if (ref($arg)) {
                   9881: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9882: 	} elsif ($arg eq '') {
                   9883: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9884: 	} else {
                   9885: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9886: 	}
                   9887:     }
                   9888:     if (!ref($arg)) {
                   9889: 	return $arg;
                   9890:     }
                   9891: }
                   9892: 
1.251     albertel 9893: ###############################################
1.182     matthew  9894: 
                   9895: =pod
                   9896: 
1.549     albertel 9897: =back
                   9898: 
                   9899: =head1 User Information Routines
                   9900: 
                   9901: =over 4
                   9902: 
1.405     albertel 9903: =item * &get_users_function()
1.182     matthew  9904: 
                   9905: Used by &bodytag to determine the current users primary role.
                   9906: Returns either 'student','coordinator','admin', or 'author'.
                   9907: 
                   9908: =cut
                   9909: 
                   9910: ###############################################
                   9911: sub get_users_function {
1.815     tempelho 9912:     my $function = 'norole';
1.818     tempelho 9913:     if ($env{'request.role'}=~/^(st)/) {
                   9914:         $function='student';
                   9915:     }
1.907     raeburn  9916:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9917:         $function='coordinator';
                   9918:     }
1.258     albertel 9919:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9920:         $function='admin';
                   9921:     }
1.826     bisitz   9922:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9923:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9924:         $function='author';
                   9925:     }
                   9926:     return $function;
1.54      www      9927: }
1.99      www      9928: 
                   9929: ###############################################
                   9930: 
1.233     raeburn  9931: =pod
                   9932: 
1.821     raeburn  9933: =item * &show_course()
                   9934: 
                   9935: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9936: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9937: 
                   9938: Inputs:
                   9939: None
                   9940: 
                   9941: Outputs:
                   9942: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9943: 
                   9944: =cut
                   9945: 
                   9946: ###############################################
                   9947: sub show_course {
                   9948:     my $course = !$env{'user.adv'};
                   9949:     if (!$env{'user.adv'}) {
                   9950:         foreach my $env (keys(%env)) {
                   9951:             next if ($env !~ m/^user\.priv\./);
                   9952:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9953:                 $course = 0;
                   9954:                 last;
                   9955:             }
                   9956:         }
                   9957:     }
                   9958:     return $course;
                   9959: }
                   9960: 
                   9961: ###############################################
                   9962: 
                   9963: =pod
                   9964: 
1.542     raeburn  9965: =item * &check_user_status()
1.274     raeburn  9966: 
                   9967: Determines current status of supplied role for a
                   9968: specific user. Roles can be active, previous or future.
                   9969: 
                   9970: Inputs: 
                   9971: user's domain, user's username, course's domain,
1.375     raeburn  9972: course's number, optional section ID.
1.274     raeburn  9973: 
                   9974: Outputs:
                   9975: role status: active, previous or future. 
                   9976: 
                   9977: =cut
                   9978: 
                   9979: sub check_user_status {
1.412     raeburn  9980:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9981:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9982:     my @uroles = keys(%userinfo);
1.274     raeburn  9983:     my $srchstr;
                   9984:     my $active_chk = 'none';
1.412     raeburn  9985:     my $now = time;
1.274     raeburn  9986:     if (@uroles > 0) {
1.908     raeburn  9987:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9988:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9989:         } else {
1.412     raeburn  9990:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9991:         }
                   9992:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9993:             my $role_end = 0;
                   9994:             my $role_start = 0;
                   9995:             $active_chk = 'active';
1.412     raeburn  9996:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9997:                 $role_end = $1;
                   9998:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9999:                     $role_start = $1;
1.274     raeburn  10000:                 }
                   10001:             }
                   10002:             if ($role_start > 0) {
1.412     raeburn  10003:                 if ($now < $role_start) {
1.274     raeburn  10004:                     $active_chk = 'future';
                   10005:                 }
                   10006:             }
                   10007:             if ($role_end > 0) {
1.412     raeburn  10008:                 if ($now > $role_end) {
1.274     raeburn  10009:                     $active_chk = 'previous';
                   10010:                 }
                   10011:             }
                   10012:         }
                   10013:     }
                   10014:     return $active_chk;
                   10015: }
                   10016: 
                   10017: ###############################################
                   10018: 
                   10019: =pod
                   10020: 
1.405     albertel 10021: =item * &get_sections()
1.233     raeburn  10022: 
                   10023: Determines all the sections for a course including
                   10024: sections with students and sections containing other roles.
1.419     raeburn  10025: Incoming parameters: 
                   10026: 
                   10027: 1. domain
                   10028: 2. course number 
                   10029: 3. reference to array containing roles for which sections should 
                   10030: be gathered (optional).
                   10031: 4. reference to array containing status types for which sections 
                   10032: should be gathered (optional).
                   10033: 
                   10034: If the third argument is undefined, sections are gathered for any role. 
                   10035: If the fourth argument is undefined, sections are gathered for any status.
                   10036: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10037:  
1.374     raeburn  10038: Returns section hash (keys are section IDs, values are
                   10039: number of users in each section), subject to the
1.419     raeburn  10040: optional roles filter, optional status filter 
1.233     raeburn  10041: 
                   10042: =cut
                   10043: 
                   10044: ###############################################
                   10045: sub get_sections {
1.419     raeburn  10046:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10047:     if (!defined($cdom) || !defined($cnum)) {
                   10048:         my $cid =  $env{'request.course.id'};
                   10049: 
                   10050: 	return if (!defined($cid));
                   10051: 
                   10052:         $cdom = $env{'course.'.$cid.'.domain'};
                   10053:         $cnum = $env{'course.'.$cid.'.num'};
                   10054:     }
                   10055: 
                   10056:     my %sectioncount;
1.419     raeburn  10057:     my $now = time;
1.240     albertel 10058: 
1.1075.2.33  raeburn  10059:     my $check_students = 1;
                   10060:     my $only_students = 0;
                   10061:     if (ref($possible_roles) eq 'ARRAY') {
                   10062:         if (grep(/^st$/,@{$possible_roles})) {
                   10063:             if (@{$possible_roles} == 1) {
                   10064:                 $only_students = 1;
                   10065:             }
                   10066:         } else {
                   10067:             $check_students = 0;
                   10068:         }
                   10069:     }
                   10070: 
                   10071:     if ($check_students) {
1.276     albertel 10072: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10073: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10074: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10075:         my $start_index = &Apache::loncoursedata::CL_START();
                   10076:         my $end_index = &Apache::loncoursedata::CL_END();
                   10077:         my $status;
1.366     albertel 10078: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10079: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10080: 				                     $data->[$status_index],
                   10081:                                                      $data->[$start_index],
                   10082:                                                      $data->[$end_index]);
                   10083:             if ($stu_status eq 'Active') {
                   10084:                 $status = 'active';
                   10085:             } elsif ($end < $now) {
                   10086:                 $status = 'previous';
                   10087:             } elsif ($start > $now) {
                   10088:                 $status = 'future';
                   10089:             } 
                   10090: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10091:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10092:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10093: 		    $sectioncount{$section}++;
                   10094:                 }
1.240     albertel 10095: 	    }
                   10096: 	}
                   10097:     }
1.1075.2.33  raeburn  10098:     if ($only_students) {
                   10099:         return %sectioncount;
                   10100:     }
1.240     albertel 10101:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10102:     foreach my $user (sort(keys(%courseroles))) {
                   10103: 	if ($user !~ /^(\w{2})/) { next; }
                   10104: 	my ($role) = ($user =~ /^(\w{2})/);
                   10105: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10106: 	my ($section,$status);
1.240     albertel 10107: 	if ($role eq 'cr' &&
                   10108: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10109: 	    $section=$1;
                   10110: 	}
                   10111: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10112: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10113:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10114:         if ($end == -1 && $start == -1) {
                   10115:             next; #deleted role
                   10116:         }
                   10117:         if (!defined($possible_status)) { 
                   10118:             $sectioncount{$section}++;
                   10119:         } else {
                   10120:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10121:                 $status = 'active';
                   10122:             } elsif ($end < $now) {
                   10123:                 $status = 'future';
                   10124:             } elsif ($start > $now) {
                   10125:                 $status = 'previous';
                   10126:             }
                   10127:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10128:                 $sectioncount{$section}++;
                   10129:             }
                   10130:         }
1.233     raeburn  10131:     }
1.366     albertel 10132:     return %sectioncount;
1.233     raeburn  10133: }
                   10134: 
1.274     raeburn  10135: ###############################################
1.294     raeburn  10136: 
                   10137: =pod
1.405     albertel 10138: 
                   10139: =item * &get_course_users()
                   10140: 
1.275     raeburn  10141: Retrieves usernames:domains for users in the specified course
                   10142: with specific role(s), and access status. 
                   10143: 
                   10144: Incoming parameters:
1.277     albertel 10145: 1. course domain
                   10146: 2. course number
                   10147: 3. access status: users must have - either active, 
1.275     raeburn  10148: previous, future, or all.
1.277     albertel 10149: 4. reference to array of permissible roles
1.288     raeburn  10150: 5. reference to array of section restrictions (optional)
                   10151: 6. reference to results object (hash of hashes).
                   10152: 7. reference to optional userdata hash
1.609     raeburn  10153: 8. reference to optional statushash
1.630     raeburn  10154: 9. flag if privileged users (except those set to unhide in
                   10155:    course settings) should be excluded    
1.609     raeburn  10156: Keys of top level results hash are roles.
1.275     raeburn  10157: Keys of inner hashes are username:domain, with 
                   10158: values set to access type.
1.288     raeburn  10159: Optional userdata hash returns an array with arguments in the 
                   10160: same order as loncoursedata::get_classlist() for student data.
                   10161: 
1.609     raeburn  10162: Optional statushash returns
                   10163: 
1.288     raeburn  10164: Entries for end, start, section and status are blank because
                   10165: of the possibility of multiple values for non-student roles.
                   10166: 
1.275     raeburn  10167: =cut
1.405     albertel 10168: 
1.275     raeburn  10169: ###############################################
1.405     albertel 10170: 
1.275     raeburn  10171: sub get_course_users {
1.630     raeburn  10172:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10173:     my %idx = ();
1.419     raeburn  10174:     my %seclists;
1.288     raeburn  10175: 
                   10176:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10177:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10178:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10179:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10180:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10181:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10182:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10183:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10184: 
1.290     albertel 10185:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10186:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10187:         my $now = time;
1.277     albertel 10188:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10189:             my $match = 0;
1.412     raeburn  10190:             my $secmatch = 0;
1.419     raeburn  10191:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10192:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10193:             if ($section eq '') {
                   10194:                 $section = 'none';
                   10195:             }
1.291     albertel 10196:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10197:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10198:                     $secmatch = 1;
                   10199:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10200:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10201:                         $secmatch = 1;
                   10202:                     }
                   10203:                 } else {  
1.419     raeburn  10204: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10205: 		        $secmatch = 1;
                   10206:                     }
1.290     albertel 10207: 		}
1.412     raeburn  10208:                 if (!$secmatch) {
                   10209:                     next;
                   10210:                 }
1.419     raeburn  10211:             }
1.275     raeburn  10212:             if (defined($$types{'active'})) {
1.288     raeburn  10213:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10214:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10215:                     $match = 1;
1.275     raeburn  10216:                 }
                   10217:             }
                   10218:             if (defined($$types{'previous'})) {
1.609     raeburn  10219:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10220:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10221:                     $match = 1;
1.275     raeburn  10222:                 }
                   10223:             }
                   10224:             if (defined($$types{'future'})) {
1.609     raeburn  10225:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10226:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10227:                     $match = 1;
1.275     raeburn  10228:                 }
                   10229:             }
1.609     raeburn  10230:             if ($match) {
                   10231:                 push(@{$seclists{$student}},$section);
                   10232:                 if (ref($userdata) eq 'HASH') {
                   10233:                     $$userdata{$student} = $$classlist{$student};
                   10234:                 }
                   10235:                 if (ref($statushash) eq 'HASH') {
                   10236:                     $statushash->{$student}{'st'}{$section} = $status;
                   10237:                 }
1.288     raeburn  10238:             }
1.275     raeburn  10239:         }
                   10240:     }
1.412     raeburn  10241:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10242:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10243:         my $now = time;
1.609     raeburn  10244:         my %displaystatus = ( previous => 'Expired',
                   10245:                               active   => 'Active',
                   10246:                               future   => 'Future',
                   10247:                             );
1.1075.2.36  raeburn  10248:         my (%nothide,@possdoms);
1.630     raeburn  10249:         if ($hidepriv) {
                   10250:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10251:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10252:                 if ($user !~ /:/) {
                   10253:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10254:                 } else {
                   10255:                     $nothide{$user} = 1;
                   10256:                 }
                   10257:             }
1.1075.2.36  raeburn  10258:             my @possdoms = ($cdom);
                   10259:             if ($coursehash{'checkforpriv'}) {
                   10260:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10261:             }
1.630     raeburn  10262:         }
1.439     raeburn  10263:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10264:             my $match = 0;
1.412     raeburn  10265:             my $secmatch = 0;
1.439     raeburn  10266:             my $status;
1.412     raeburn  10267:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10268:             $user =~ s/:$//;
1.439     raeburn  10269:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10270:             if ($end == -1 || $start == -1) {
                   10271:                 next;
                   10272:             }
                   10273:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10274:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10275:                 my ($uname,$udom) = split(/:/,$user);
                   10276:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10277:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10278:                         $secmatch = 1;
                   10279:                     } elsif ($usec eq '') {
1.420     albertel 10280:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10281:                             $secmatch = 1;
                   10282:                         }
                   10283:                     } else {
                   10284:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10285:                             $secmatch = 1;
                   10286:                         }
                   10287:                     }
                   10288:                     if (!$secmatch) {
                   10289:                         next;
                   10290:                     }
1.288     raeburn  10291:                 }
1.419     raeburn  10292:                 if ($usec eq '') {
                   10293:                     $usec = 'none';
                   10294:                 }
1.275     raeburn  10295:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10296:                     if ($hidepriv) {
1.1075.2.36  raeburn  10297:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10298:                             (!$nothide{$uname.':'.$udom})) {
                   10299:                             next;
                   10300:                         }
                   10301:                     }
1.503     raeburn  10302:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10303:                         $status = 'previous';
                   10304:                     } elsif ($start > $now) {
                   10305:                         $status = 'future';
                   10306:                     } else {
                   10307:                         $status = 'active';
                   10308:                     }
1.277     albertel 10309:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10310:                         if ($status eq $type) {
1.420     albertel 10311:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10312:                                 push(@{$$users{$role}{$user}},$type);
                   10313:                             }
1.288     raeburn  10314:                             $match = 1;
                   10315:                         }
                   10316:                     }
1.419     raeburn  10317:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10318:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10319: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10320:                         }
1.420     albertel 10321:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10322:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10323:                         }
1.609     raeburn  10324:                         if (ref($statushash) eq 'HASH') {
                   10325:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10326:                         }
1.275     raeburn  10327:                     }
                   10328:                 }
                   10329:             }
                   10330:         }
1.290     albertel 10331:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10332:             if ((defined($cdom)) && (defined($cnum))) {
                   10333:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10334:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10335:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10336:                     next if ($owner eq '');
                   10337:                     my ($ownername,$ownerdom);
                   10338:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10339:                         $ownername = $1;
                   10340:                         $ownerdom = $2;
                   10341:                     } else {
                   10342:                         $ownername = $owner;
                   10343:                         $ownerdom = $cdom;
                   10344:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10345:                     }
                   10346:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10347:                     if (defined($userdata) && 
1.609     raeburn  10348: 			!exists($$userdata{$owner})) {
                   10349: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10350:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10351:                             push(@{$seclists{$owner}},'none');
                   10352:                         }
                   10353:                         if (ref($statushash) eq 'HASH') {
                   10354:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10355:                         }
1.290     albertel 10356: 		    }
1.279     raeburn  10357:                 }
                   10358:             }
                   10359:         }
1.419     raeburn  10360:         foreach my $user (keys(%seclists)) {
                   10361:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10362:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10363:         }
1.275     raeburn  10364:     }
                   10365:     return;
                   10366: }
                   10367: 
1.288     raeburn  10368: sub get_user_info {
                   10369:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10370:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10371: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10372:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10373:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10374:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10375:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10376:     return;
                   10377: }
1.275     raeburn  10378: 
1.472     raeburn  10379: ###############################################
                   10380: 
                   10381: =pod
                   10382: 
                   10383: =item * &get_user_quota()
                   10384: 
1.1075.2.41  raeburn  10385: Retrieves quota assigned for storage of user files.
                   10386: Default is to report quota for portfolio files.
1.472     raeburn  10387: 
                   10388: Incoming parameters:
                   10389: 1. user's username
                   10390: 2. user's domain
1.1075.2.41  raeburn  10391: 3. quota name - portfolio, author, or course
                   10392:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10393: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10394:    course
1.472     raeburn  10395: 
                   10396: Returns:
1.1075.2.58  raeburn  10397: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10398: 2. (Optional) Type of setting: custom or default
                   10399:    (individually assigned or default for user's 
                   10400:    institutional status).
                   10401: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10402:    or student - types as defined in localenroll::inst_usertypes 
                   10403:    for user's domain, which determines default quota for user.
                   10404: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10405: 
                   10406: If a value has been stored in the user's environment, 
1.536     raeburn  10407: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10408: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10409: 
                   10410: =cut
                   10411: 
                   10412: ###############################################
                   10413: 
                   10414: 
                   10415: sub get_user_quota {
1.1075.2.42  raeburn  10416:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10417:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10418:     if (!defined($udom)) {
                   10419:         $udom = $env{'user.domain'};
                   10420:     }
                   10421:     if (!defined($uname)) {
                   10422:         $uname = $env{'user.name'};
                   10423:     }
                   10424:     if (($udom eq '' || $uname eq '') ||
                   10425:         ($udom eq 'public') && ($uname eq 'public')) {
                   10426:         $quota = 0;
1.536     raeburn  10427:         $quotatype = 'default';
                   10428:         $defquota = 0; 
1.472     raeburn  10429:     } else {
1.536     raeburn  10430:         my $inststatus;
1.1075.2.41  raeburn  10431:         if ($quotaname eq 'course') {
                   10432:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10433:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10434:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10435:             } else {
                   10436:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10437:                 $quota = $cenv{'internal.uploadquota'};
                   10438:             }
1.536     raeburn  10439:         } else {
1.1075.2.41  raeburn  10440:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10441:                 if ($quotaname eq 'author') {
                   10442:                     $quota = $env{'environment.authorquota'};
                   10443:                 } else {
                   10444:                     $quota = $env{'environment.portfolioquota'};
                   10445:                 }
                   10446:                 $inststatus = $env{'environment.inststatus'};
                   10447:             } else {
                   10448:                 my %userenv = 
                   10449:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10450:                                          'authorquota','inststatus'],$udom,$uname);
                   10451:                 my ($tmp) = keys(%userenv);
                   10452:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10453:                     if ($quotaname eq 'author') {
                   10454:                         $quota = $userenv{'authorquota'};
                   10455:                     } else {
                   10456:                         $quota = $userenv{'portfolioquota'};
                   10457:                     }
                   10458:                     $inststatus = $userenv{'inststatus'};
                   10459:                 } else {
                   10460:                     undef(%userenv);
                   10461:                 }
                   10462:             }
                   10463:         }
                   10464:         if ($quota eq '' || wantarray) {
                   10465:             if ($quotaname eq 'course') {
                   10466:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10467:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10468:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10469:                     $defquota = $domdefs{$crstype.'quota'};
                   10470:                 }
                   10471:                 if ($defquota eq '') {
                   10472:                     $defquota = 500;
                   10473:                 }
1.1075.2.41  raeburn  10474:             } else {
                   10475:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10476:             }
                   10477:             if ($quota eq '') {
                   10478:                 $quota = $defquota;
                   10479:                 $quotatype = 'default';
                   10480:             } else {
                   10481:                 $quotatype = 'custom';
                   10482:             }
1.472     raeburn  10483:         }
                   10484:     }
1.536     raeburn  10485:     if (wantarray) {
                   10486:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10487:     } else {
                   10488:         return $quota;
                   10489:     }
1.472     raeburn  10490: }
                   10491: 
                   10492: ###############################################
                   10493: 
                   10494: =pod
                   10495: 
                   10496: =item * &default_quota()
                   10497: 
1.536     raeburn  10498: Retrieves default quota assigned for storage of user portfolio files,
                   10499: given an (optional) user's institutional status.
1.472     raeburn  10500: 
                   10501: Incoming parameters:
1.1075.2.42  raeburn  10502: 
1.472     raeburn  10503: 1. domain
1.536     raeburn  10504: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10505:    status types (e.g., faculty, staff, student etc.)
                   10506:    which apply to the user for whom the default is being retrieved.
                   10507:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10508:    default quota will be returned.
                   10509: 3.  quota name - portfolio, author, or course
                   10510:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10511: 
                   10512: Returns:
1.1075.2.42  raeburn  10513: 
1.1075.2.58  raeburn  10514: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10515: 2. (Optional) institutional type which determined the value of the
                   10516:    default quota.
1.472     raeburn  10517: 
                   10518: If a value has been stored in the domain's configuration db,
                   10519: it will return that, otherwise it returns 20 (for backwards 
                   10520: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10521: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10522: 
1.536     raeburn  10523: If the user's status includes multiple types (e.g., staff and student),
                   10524: the largest default quota which applies to the user determines the
                   10525: default quota returned.
                   10526: 
1.472     raeburn  10527: =cut
                   10528: 
                   10529: ###############################################
                   10530: 
                   10531: 
                   10532: sub default_quota {
1.1075.2.41  raeburn  10533:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10534:     my ($defquota,$settingstatus);
                   10535:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10536:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10537:     my $key = 'defaultquota';
                   10538:     if ($quotaname eq 'author') {
                   10539:         $key = 'authorquota';
                   10540:     }
1.622     raeburn  10541:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10542:         if ($inststatus ne '') {
1.765     raeburn  10543:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10544:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10545:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10546:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10547:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10548:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10549:                             $settingstatus = $item;
1.1075.2.41  raeburn  10550:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10551:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10552:                             $settingstatus = $item;
                   10553:                         }
                   10554:                     }
1.1075.2.41  raeburn  10555:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10556:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10557:                         if ($defquota eq '') {
                   10558:                             $defquota = $quotahash{'quotas'}{$item};
                   10559:                             $settingstatus = $item;
                   10560:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10561:                             $defquota = $quotahash{'quotas'}{$item};
                   10562:                             $settingstatus = $item;
                   10563:                         }
1.536     raeburn  10564:                     }
                   10565:                 }
                   10566:             }
                   10567:         }
                   10568:         if ($defquota eq '') {
1.1075.2.41  raeburn  10569:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10570:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10571:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10572:                 $defquota = $quotahash{'quotas'}{'default'};
                   10573:             }
1.536     raeburn  10574:             $settingstatus = 'default';
1.1075.2.42  raeburn  10575:             if ($defquota eq '') {
                   10576:                 if ($quotaname eq 'author') {
                   10577:                     $defquota = 500;
                   10578:                 }
                   10579:             }
1.536     raeburn  10580:         }
                   10581:     } else {
                   10582:         $settingstatus = 'default';
1.1075.2.41  raeburn  10583:         if ($quotaname eq 'author') {
                   10584:             $defquota = 500;
                   10585:         } else {
                   10586:             $defquota = 20;
                   10587:         }
1.536     raeburn  10588:     }
                   10589:     if (wantarray) {
                   10590:         return ($defquota,$settingstatus);
1.472     raeburn  10591:     } else {
1.536     raeburn  10592:         return $defquota;
1.472     raeburn  10593:     }
                   10594: }
                   10595: 
1.1075.2.41  raeburn  10596: ###############################################
                   10597: 
                   10598: =pod
                   10599: 
1.1075.2.42  raeburn  10600: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  10601: 
                   10602: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  10603: of existing file within authoring space will cause quota for the authoring
                   10604: space to be exceeded.
                   10605: 
                   10606: Same, if upload of a file directly to a course/community via Course Editor
                   10607: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  10608: 
1.1075.2.61  raeburn  10609: Inputs: 7 
1.1075.2.42  raeburn  10610: 1. username or coursenum
1.1075.2.41  raeburn  10611: 2. domain
1.1075.2.42  raeburn  10612: 3. context ('author' or 'course')
1.1075.2.41  raeburn  10613: 4. filename of file for which action is being requested
                   10614: 5. filesize (kB) of file
                   10615: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  10616: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  10617: 
                   10618: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   10619:          otherwise return null.
                   10620: 
1.1075.2.42  raeburn  10621: =back
                   10622: 
1.1075.2.41  raeburn  10623: =cut
                   10624: 
1.1075.2.42  raeburn  10625: sub excess_filesize_warning {
1.1075.2.59  raeburn  10626:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  10627:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  10628:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  10629:     if ($context eq 'author') {
                   10630:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10631:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10632:     } else {
                   10633:         foreach my $subdir ('docs','supplemental') {
                   10634:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10635:         }
                   10636:     }
1.1075.2.41  raeburn  10637:     $disk_quota = int($disk_quota * 1000);
                   10638:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  10639:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  10640:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  10641:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10642:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  10643:                             $disk_quota,$current_disk_usage).
                   10644:                '</p>';
                   10645:     }
                   10646:     return;
                   10647: }
                   10648: 
                   10649: ###############################################
                   10650: 
                   10651: 
1.384     raeburn  10652: sub get_secgrprole_info {
                   10653:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10654:     my %sections_count = &get_sections($cdom,$cnum);
                   10655:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10656:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10657:     my @groups = sort(keys(%curr_groups));
                   10658:     my $allroles = [];
                   10659:     my $rolehash;
                   10660:     my $accesshash = {
                   10661:                      active => 'Currently has access',
                   10662:                      future => 'Will have future access',
                   10663:                      previous => 'Previously had access',
                   10664:                   };
                   10665:     if ($needroles) {
                   10666:         $rolehash = {'all' => 'all'};
1.385     albertel 10667:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10668: 	if (&Apache::lonnet::error(%user_roles)) {
                   10669: 	    undef(%user_roles);
                   10670: 	}
                   10671:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10672:             my ($role)=split(/\:/,$item,2);
                   10673:             if ($role eq 'cr') { next; }
                   10674:             if ($role =~ /^cr/) {
                   10675:                 $$rolehash{$role} = (split('/',$role))[3];
                   10676:             } else {
                   10677:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10678:             }
                   10679:         }
                   10680:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10681:             push(@{$allroles},$key);
                   10682:         }
                   10683:         push (@{$allroles},'st');
                   10684:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10685:     }
                   10686:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10687: }
                   10688: 
1.555     raeburn  10689: sub user_picker {
1.1075.2.127  raeburn  10690:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10691:     my $currdom = $dom;
1.1075.2.114  raeburn  10692:     my @alldoms = &Apache::lonnet::all_domains();
                   10693:     if (@alldoms == 1) {
                   10694:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10695:                                                ['directorysrch'],$alldoms[0]);
                   10696:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10697:         my $showdom = $domdesc;
                   10698:         if ($showdom eq '') {
                   10699:             $showdom = $dom;
                   10700:         }
                   10701:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10702:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10703:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10704:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10705:             }
                   10706:         }
                   10707:     }
1.555     raeburn  10708:     my %curr_selected = (
                   10709:                         srchin => 'dom',
1.580     raeburn  10710:                         srchby => 'lastname',
1.555     raeburn  10711:                       );
                   10712:     my $srchterm;
1.625     raeburn  10713:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10714:         if ($srch->{'srchby'} ne '') {
                   10715:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10716:         }
                   10717:         if ($srch->{'srchin'} ne '') {
                   10718:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10719:         }
                   10720:         if ($srch->{'srchtype'} ne '') {
                   10721:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10722:         }
                   10723:         if ($srch->{'srchdomain'} ne '') {
                   10724:             $currdom = $srch->{'srchdomain'};
                   10725:         }
                   10726:         $srchterm = $srch->{'srchterm'};
                   10727:     }
1.1075.2.98  raeburn  10728:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10729:                     'usr'       => 'Search criteria',
1.563     raeburn  10730:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10731:                     'uname'     => 'username',
                   10732:                     'lastname'  => 'last name',
1.555     raeburn  10733:                     'lastfirst' => 'last name, first name',
1.558     albertel 10734:                     'crs'       => 'in this course',
1.576     raeburn  10735:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10736:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10737:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10738:                     'exact'     => 'is',
                   10739:                     'contains'  => 'contains',
1.569     raeburn  10740:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  10741:                                        );
                   10742:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10743:                     'youm'      => "You must include some text to search for.",
                   10744:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10745:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10746:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10747:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10748:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10749:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10750:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10751:                                        );
1.1075.2.98  raeburn  10752:     &html_escape(\%html_lt);
                   10753:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  10754:     my $domform;
1.1075.2.126  raeburn  10755:     my $allow_blank = 1;
1.1075.2.115  raeburn  10756:     if ($fixeddom) {
1.1075.2.126  raeburn  10757:         $allow_blank = 0;
                   10758:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  10759:     } else {
1.1075.2.126  raeburn  10760:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  10761:     }
1.563     raeburn  10762:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10763: 
                   10764:     my @srchins = ('crs','dom','alc','instd');
                   10765: 
                   10766:     foreach my $option (@srchins) {
                   10767:         # FIXME 'alc' option unavailable until 
                   10768:         #       loncreateuser::print_user_query_page()
                   10769:         #       has been completed.
                   10770:         next if ($option eq 'alc');
1.880     raeburn  10771:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10772:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  10773:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10774:         if ($curr_selected{'srchin'} eq $option) {
                   10775:             $srchinsel .= ' 
1.1075.2.98  raeburn  10776:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10777:         } else {
                   10778:             $srchinsel .= '
1.1075.2.98  raeburn  10779:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10780:         }
1.555     raeburn  10781:     }
1.563     raeburn  10782:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10783: 
                   10784:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10785:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10786:         if ($curr_selected{'srchby'} eq $option) {
                   10787:             $srchbysel .= '
1.1075.2.98  raeburn  10788:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10789:         } else {
                   10790:             $srchbysel .= '
1.1075.2.98  raeburn  10791:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10792:          }
                   10793:     }
                   10794:     $srchbysel .= "\n  </select>\n";
                   10795: 
                   10796:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10797:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10798:         if ($curr_selected{'srchtype'} eq $option) {
                   10799:             $srchtypesel .= '
1.1075.2.98  raeburn  10800:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10801:         } else {
                   10802:             $srchtypesel .= '
1.1075.2.98  raeburn  10803:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10804:         }
                   10805:     }
                   10806:     $srchtypesel .= "\n  </select>\n";
                   10807: 
1.558     albertel 10808:     my ($newuserscript,$new_user_create);
1.994     raeburn  10809:     my $context_dom = $env{'request.role.domain'};
                   10810:     if ($context eq 'requestcrs') {
                   10811:         if ($env{'form.coursedom'} ne '') { 
                   10812:             $context_dom = $env{'form.coursedom'};
                   10813:         }
                   10814:     }
1.556     raeburn  10815:     if ($forcenewuser) {
1.576     raeburn  10816:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10817:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10818:                 if ($cancreate) {
                   10819:                     $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>';
                   10820:                 } else {
1.799     bisitz   10821:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10822:                     my %usertypetext = (
                   10823:                         official   => 'institutional',
                   10824:                         unofficial => 'non-institutional',
                   10825:                     );
1.799     bisitz   10826:                     $new_user_create = '<p class="LC_warning">'
                   10827:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10828:                                       .' '
                   10829:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10830:                                           ,'<a href="'.$helplink.'">','</a>')
                   10831:                                       .'</p><br />';
1.627     raeburn  10832:                 }
1.576     raeburn  10833:             }
                   10834:         }
                   10835: 
1.556     raeburn  10836:         $newuserscript = <<"ENDSCRIPT";
                   10837: 
1.570     raeburn  10838: function setSearch(createnew,callingForm) {
1.556     raeburn  10839:     if (createnew == 1) {
1.570     raeburn  10840:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10841:             if (callingForm.srchby.options[i].value == 'uname') {
                   10842:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10843:             }
                   10844:         }
1.570     raeburn  10845:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10846:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10847: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10848:             }
                   10849:         }
1.570     raeburn  10850:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10851:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10852:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10853:             }
                   10854:         }
1.570     raeburn  10855:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10856:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10857:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10858:             }
                   10859:         }
                   10860:     }
                   10861: }
                   10862: ENDSCRIPT
1.558     albertel 10863: 
1.556     raeburn  10864:     }
                   10865: 
1.555     raeburn  10866:     my $output = <<"END_BLOCK";
1.556     raeburn  10867: <script type="text/javascript">
1.824     bisitz   10868: // <![CDATA[
1.570     raeburn  10869: function validateEntry(callingForm) {
1.558     albertel 10870: 
1.556     raeburn  10871:     var checkok = 1;
1.558     albertel 10872:     var srchin;
1.570     raeburn  10873:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10874: 	if ( callingForm.srchin[i].checked ) {
                   10875: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10876: 	}
                   10877:     }
                   10878: 
1.570     raeburn  10879:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10880:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10881:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10882:     var srchterm =  callingForm.srchterm.value;
                   10883:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10884:     var msg = "";
                   10885: 
                   10886:     if (srchterm == "") {
                   10887:         checkok = 0;
1.1075.2.98  raeburn  10888:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10889:     }
                   10890: 
1.569     raeburn  10891:     if (srchtype== 'begins') {
                   10892:         if (srchterm.length < 2) {
                   10893:             checkok = 0;
1.1075.2.98  raeburn  10894:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10895:         }
                   10896:     }
                   10897: 
1.556     raeburn  10898:     if (srchtype== 'contains') {
                   10899:         if (srchterm.length < 3) {
                   10900:             checkok = 0;
1.1075.2.98  raeburn  10901:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10902:         }
                   10903:     }
                   10904:     if (srchin == 'instd') {
                   10905:         if (srchdomain == '') {
                   10906:             checkok = 0;
1.1075.2.98  raeburn  10907:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10908:         }
                   10909:     }
                   10910:     if (srchin == 'dom') {
                   10911:         if (srchdomain == '') {
                   10912:             checkok = 0;
1.1075.2.98  raeburn  10913:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10914:         }
                   10915:     }
                   10916:     if (srchby == 'lastfirst') {
                   10917:         if (srchterm.indexOf(",") == -1) {
                   10918:             checkok = 0;
1.1075.2.98  raeburn  10919:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10920:         }
                   10921:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10922:             checkok = 0;
1.1075.2.98  raeburn  10923:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10924:         }
                   10925:     }
                   10926:     if (checkok == 0) {
1.1075.2.98  raeburn  10927:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10928:         return;
                   10929:     }
                   10930:     if (checkok == 1) {
1.570     raeburn  10931:         callingForm.submit();
1.556     raeburn  10932:     }
                   10933: }
                   10934: 
                   10935: $newuserscript
                   10936: 
1.824     bisitz   10937: // ]]>
1.556     raeburn  10938: </script>
1.558     albertel 10939: 
                   10940: $new_user_create
                   10941: 
1.555     raeburn  10942: END_BLOCK
1.558     albertel 10943: 
1.876     raeburn  10944:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10945:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10946:                $domform.
                   10947:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10948:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10949:                $srchbysel.
                   10950:                $srchtypesel. 
                   10951:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10952:                $srchinsel.
                   10953:                &Apache::lonhtmlcommon::row_closure(1). 
                   10954:                &Apache::lonhtmlcommon::end_pick_box().
                   10955:                '<br />';
1.1075.2.114  raeburn  10956:     return ($output,1);
1.555     raeburn  10957: }
                   10958: 
1.612     raeburn  10959: sub user_rule_check {
1.615     raeburn  10960:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10961:     my ($response,%inst_response);
1.612     raeburn  10962:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10963:         if (keys(%{$usershash}) > 1) {
                   10964:             my (%by_username,%by_id,%userdoms);
                   10965:             my $checkid;
1.612     raeburn  10966:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10967:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10968:                     $checkid = 1;
                   10969:                 }
                   10970:             }
                   10971:             foreach my $user (keys(%{$usershash})) {
                   10972:                 my ($uname,$udom) = split(/:/,$user);
                   10973:                 if ($checkid) {
                   10974:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10975:                         if ($usershash->{$user}->{'id'} ne '') {
                   10976:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10977:                             $userdoms{$udom} = 1;
                   10978:                             if (ref($inst_results) eq 'HASH') {
                   10979:                                 $inst_results->{$uname.':'.$udom} = {};
                   10980:                             }
                   10981:                         }
                   10982:                     }
                   10983:                 } else {
                   10984:                     $by_username{$udom}{$uname} = 1;
                   10985:                     $userdoms{$udom} = 1;
                   10986:                     if (ref($inst_results) eq 'HASH') {
                   10987:                         $inst_results->{$uname.':'.$udom} = {};
                   10988:                     }
                   10989:                 }
                   10990:             }
                   10991:             foreach my $udom (keys(%userdoms)) {
                   10992:                 if (!$got_rules->{$udom}) {
                   10993:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10994:                                                              ['usercreation'],$udom);
                   10995:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10996:                         foreach my $item ('username','id') {
                   10997:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10998:                                 $$curr_rules{$udom}{$item} =
                   10999:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   11000:                             }
                   11001:                         }
                   11002:                     }
                   11003:                     $got_rules->{$udom} = 1;
                   11004:                 }
                   11005:             }
                   11006:             if ($checkid) {
                   11007:                 foreach my $udom (keys(%by_id)) {
                   11008:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11009:                     if ($outcome eq 'ok') {
                   11010:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11011:                             my $uname = $by_id{$udom}{$id};
                   11012:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11013:                         }
                   11014:                         if (ref($results) eq 'HASH') {
                   11015:                             foreach my $uname (keys(%{$results})) {
                   11016:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11017:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11018:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11019:                                 }
                   11020:                             }
                   11021:                         }
                   11022:                     }
1.612     raeburn  11023:                 }
1.615     raeburn  11024:             } else {
1.1075.2.99  raeburn  11025:                 foreach my $udom (keys(%by_username)) {
                   11026:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11027:                     if ($outcome eq 'ok') {
                   11028:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11029:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11030:                         }
                   11031:                         if (ref($results) eq 'HASH') {
                   11032:                             foreach my $uname (keys(%{$results})) {
                   11033:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11034:                             }
                   11035:                         }
                   11036:                     }
                   11037:                 }
1.612     raeburn  11038:             }
1.1075.2.99  raeburn  11039:         } elsif (keys(%{$usershash}) == 1) {
                   11040:             my $user = (keys(%{$usershash}))[0];
                   11041:             my ($uname,$udom) = split(/:/,$user);
                   11042:             if (($udom ne '') && ($uname ne '')) {
                   11043:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11044:                     if (ref($checks) eq 'HASH') {
                   11045:                         if (defined($checks->{'username'})) {
                   11046:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   11047:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11048:                         } elsif (defined($checks->{'id'})) {
                   11049:                             if ($usershash->{$user}->{'id'} ne '') {
                   11050:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11051:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11052:                                                                   $usershash->{$user}->{'id'});
                   11053:                             } else {
                   11054:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11055:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11056:                             }
                   11057:                         }
                   11058:                     } else {
                   11059:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11060:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11061:                        return;
                   11062:                     }
                   11063:                     if (!$got_rules->{$udom}) {
                   11064:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11065:                                                                  ['usercreation'],$udom);
                   11066:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11067:                             foreach my $item ('username','id') {
                   11068:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11069:                                    $$curr_rules{$udom}{$item} =
                   11070:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11071:                                 }
                   11072:                             }
1.585     raeburn  11073:                         }
1.1075.2.99  raeburn  11074:                         $got_rules->{$udom} = 1;
1.585     raeburn  11075:                     }
                   11076:                 }
1.1075.2.99  raeburn  11077:             } else {
                   11078:                 return;
                   11079:             }
                   11080:         } else {
                   11081:             return;
                   11082:         }
                   11083:         foreach my $user (keys(%{$usershash})) {
                   11084:             my ($uname,$udom) = split(/:/,$user);
                   11085:             next if (($udom eq '') || ($uname eq ''));
                   11086:             my $id;
                   11087:             if (ref($inst_results) eq 'HASH') {
                   11088:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11089:                     $id = $inst_results->{$user}->{'id'};
                   11090:                 }
                   11091:             }
                   11092:             if ($id eq '') {
                   11093:                 if (ref($usershash->{$user})) {
                   11094:                     $id = $usershash->{$user}->{'id'};
                   11095:                 }
1.585     raeburn  11096:             }
1.612     raeburn  11097:             foreach my $item (keys(%{$checks})) {
                   11098:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11099:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11100:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  11101:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11102:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11103:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11104:                                 if ($rule_check{$rule}) {
                   11105:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  11106:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11107:                                         if (ref($inst_results) eq 'HASH') {
                   11108:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11109:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11110:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  11111:                                                 } elsif ($item eq 'id') {
                   11112:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11113:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11114:                                                     }
1.615     raeburn  11115:                                                 }
1.612     raeburn  11116:                                             }
                   11117:                                         }
1.615     raeburn  11118:                                     }
                   11119:                                     last;
1.585     raeburn  11120:                                 }
                   11121:                             }
                   11122:                         }
                   11123:                     }
                   11124:                 }
                   11125:             }
                   11126:         }
                   11127:     }
1.612     raeburn  11128:     return;
                   11129: }
                   11130: 
                   11131: sub user_rule_formats {
                   11132:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11133:     my %text = ( 
                   11134:                  'username' => 'Usernames',
                   11135:                  'id'       => 'IDs',
                   11136:                );
                   11137:     my $output;
                   11138:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11139:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11140:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11141:             $output = '<br />'.
                   11142:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11143:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11144:                       ' <ul>';
1.612     raeburn  11145:             foreach my $rule (@{$ruleorder}) {
                   11146:                 if (ref($curr_rules) eq 'ARRAY') {
                   11147:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11148:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11149:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11150:                                         $rules->{$rule}{'desc'}.'</li>';
                   11151:                         }
                   11152:                     }
                   11153:                 }
                   11154:             }
                   11155:             $output .= '</ul>';
                   11156:         }
                   11157:     }
                   11158:     return $output;
                   11159: }
                   11160: 
                   11161: sub instrule_disallow_msg {
1.615     raeburn  11162:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11163:     my $response;
                   11164:     my %text = (
                   11165:                   item   => 'username',
                   11166:                   items  => 'usernames',
                   11167:                   match  => 'matches',
                   11168:                   do     => 'does',
                   11169:                   action => 'a username',
                   11170:                   one    => 'one',
                   11171:                );
                   11172:     if ($count > 1) {
                   11173:         $text{'item'} = 'usernames';
                   11174:         $text{'match'} ='match';
                   11175:         $text{'do'} = 'do';
                   11176:         $text{'action'} = 'usernames',
                   11177:         $text{'one'} = 'ones';
                   11178:     }
                   11179:     if ($checkitem eq 'id') {
                   11180:         $text{'items'} = 'IDs';
                   11181:         $text{'item'} = 'ID';
                   11182:         $text{'action'} = 'an ID';
1.615     raeburn  11183:         if ($count > 1) {
                   11184:             $text{'item'} = 'IDs';
                   11185:             $text{'action'} = 'IDs';
                   11186:         }
1.612     raeburn  11187:     }
1.674     bisitz   11188:     $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  11189:     if ($mode eq 'upload') {
                   11190:         if ($checkitem eq 'username') {
                   11191:             $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'}.");
                   11192:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11193:             $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  11194:         }
1.669     raeburn  11195:     } elsif ($mode eq 'selfcreate') {
                   11196:         if ($checkitem eq 'id') {
                   11197:             $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.");
                   11198:         }
1.615     raeburn  11199:     } else {
                   11200:         if ($checkitem eq 'username') {
                   11201:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11202:         } elsif ($checkitem eq 'id') {
                   11203:             $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.");
                   11204:         }
1.612     raeburn  11205:     }
                   11206:     return $response;
1.585     raeburn  11207: }
                   11208: 
1.624     raeburn  11209: sub personal_data_fieldtitles {
                   11210:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11211:                         id => 'Student/Employee ID',
                   11212:                         permanentemail => 'E-mail address',
                   11213:                         lastname => 'Last Name',
                   11214:                         firstname => 'First Name',
                   11215:                         middlename => 'Middle Name',
                   11216:                         generation => 'Generation',
                   11217:                         gen => 'Generation',
1.765     raeburn  11218:                         inststatus => 'Affiliation',
1.624     raeburn  11219:                    );
                   11220:     return %fieldtitles;
                   11221: }
                   11222: 
1.642     raeburn  11223: sub sorted_inst_types {
                   11224:     my ($dom) = @_;
1.1075.2.70  raeburn  11225:     my ($usertypes,$order);
                   11226:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11227:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11228:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11229:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11230:     } else {
                   11231:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11232:     }
1.642     raeburn  11233:     my $othertitle = &mt('All users');
                   11234:     if ($env{'request.course.id'}) {
1.668     raeburn  11235:         $othertitle  = &mt('Any users');
1.642     raeburn  11236:     }
                   11237:     my @types;
                   11238:     if (ref($order) eq 'ARRAY') {
                   11239:         @types = @{$order};
                   11240:     }
                   11241:     if (@types == 0) {
                   11242:         if (ref($usertypes) eq 'HASH') {
                   11243:             @types = sort(keys(%{$usertypes}));
                   11244:         }
                   11245:     }
                   11246:     if (keys(%{$usertypes}) > 0) {
                   11247:         $othertitle = &mt('Other users');
                   11248:     }
                   11249:     return ($othertitle,$usertypes,\@types);
                   11250: }
                   11251: 
1.645     raeburn  11252: sub get_institutional_codes {
1.1075.2.157  raeburn  11253:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11254: # Get complete list of course sections to update
                   11255:     my @currsections = ();
                   11256:     my @currxlists = ();
1.1075.2.157  raeburn  11257:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11258:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11259:     my $crskey = $crs.':'.$coursecode;
                   11260:     @{$unclutteredsec{$crskey}} = ();
                   11261:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11262: 
                   11263:     if ($$settings{'internal.sectionnums'} ne '') {
                   11264:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11265:     }
                   11266: 
                   11267:     if ($$settings{'internal.crosslistings'} ne '') {
                   11268:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11269:     }
                   11270: 
                   11271:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11272:         foreach my $xl (@currxlists) {
                   11273:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11274:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11275:                     push(@{$allcourses},$1);
1.645     raeburn  11276:                     $$LC_code{$1} = $2;
                   11277:                 }
                   11278:             }
                   11279:         }
                   11280:     }
1.1075.2.157  raeburn  11281: 
1.645     raeburn  11282:     if (@currsections > 0) {
1.1075.2.157  raeburn  11283:         foreach my $sec (@currsections) {
                   11284:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11285:                 my $instsec = $1;
1.645     raeburn  11286:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11287:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11288:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11289:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11290:                 }
                   11291:             }
                   11292:         }
                   11293:     }
                   11294: 
                   11295:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11296:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11297:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11298:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11299:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11300:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11301:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11302:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11303:                 }
                   11304:             }
                   11305:         }
                   11306:     }
                   11307:     return;
                   11308: }
                   11309: 
1.971     raeburn  11310: sub get_standard_codeitems {
                   11311:     return ('Year','Semester','Department','Number','Section');
                   11312: }
                   11313: 
1.112     bowersj2 11314: =pod
                   11315: 
1.780     raeburn  11316: =head1 Slot Helpers
                   11317: 
                   11318: =over 4
                   11319: 
                   11320: =item * sorted_slots()
                   11321: 
1.1040    raeburn  11322: Sorts an array of slot names in order of an optional sort key,
                   11323: default sort is by slot start time (earliest first). 
1.780     raeburn  11324: 
                   11325: Inputs:
                   11326: 
                   11327: =over 4
                   11328: 
                   11329: slotsarr  - Reference to array of unsorted slot names.
                   11330: 
                   11331: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11332: 
1.1040    raeburn  11333: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11334: 
1.549     albertel 11335: =back
                   11336: 
1.780     raeburn  11337: Returns:
                   11338: 
                   11339: =over 4
                   11340: 
1.1040    raeburn  11341: sorted   - An array of slot names sorted by a specified sort key 
                   11342:            (default sort key is start time of the slot).
1.780     raeburn  11343: 
                   11344: =back
                   11345: 
                   11346: =cut
                   11347: 
                   11348: 
                   11349: sub sorted_slots {
1.1040    raeburn  11350:     my ($slotsarr,$slots,$sortkey) = @_;
                   11351:     if ($sortkey eq '') {
                   11352:         $sortkey = 'starttime';
                   11353:     }
1.780     raeburn  11354:     my @sorted;
                   11355:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11356:         @sorted =
                   11357:             sort {
                   11358:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11359:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11360:                      }
                   11361:                      if (ref($slots->{$a})) { return -1;}
                   11362:                      if (ref($slots->{$b})) { return 1;}
                   11363:                      return 0;
                   11364:                  } @{$slotsarr};
                   11365:     }
                   11366:     return @sorted;
                   11367: }
                   11368: 
1.1040    raeburn  11369: =pod
                   11370: 
                   11371: =item * get_future_slots()
                   11372: 
                   11373: Inputs:
                   11374: 
                   11375: =over 4
                   11376: 
                   11377: cnum - course number
                   11378: 
                   11379: cdom - course domain
                   11380: 
                   11381: now - current UNIX time
                   11382: 
                   11383: symb - optional symb
                   11384: 
                   11385: =back
                   11386: 
                   11387: Returns:
                   11388: 
                   11389: =over 4
                   11390: 
                   11391: sorted_reservable - ref to array of student_schedulable slots currently 
                   11392:                     reservable, ordered by end date of reservation period.
                   11393: 
                   11394: reservable_now - ref to hash of student_schedulable slots currently
                   11395:                  reservable.
                   11396: 
                   11397:     Keys in inner hash are:
                   11398:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11399:     (b) endreserve: end date of reservation period.
                   11400:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11401:         selected.
1.1040    raeburn  11402: 
                   11403: sorted_future - ref to array of student_schedulable slots reservable in
                   11404:                 the future, ordered by start date of reservation period.
                   11405: 
                   11406: future_reservable - ref to hash of student_schedulable slots reservable
                   11407:                     in the future.
                   11408: 
                   11409:     Keys in inner hash are:
                   11410:     (a) symb: either blank or symb to which slot use is restricted.
                   11411:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11412:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11413:         selected.
1.1040    raeburn  11414: 
                   11415: =back
                   11416: 
                   11417: =cut
                   11418: 
                   11419: sub get_future_slots {
                   11420:     my ($cnum,$cdom,$now,$symb) = @_;
                   11421:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11422:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11423:     foreach my $slot (keys(%slots)) {
                   11424:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11425:         if ($symb) {
                   11426:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11427:                      ($slots{$slot}->{'symb'} ne $symb));
                   11428:         }
                   11429:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11430:             ($slots{$slot}->{'endtime'} > $now)) {
                   11431:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11432:                 my $userallowed = 0;
                   11433:                 if ($slots{$slot}->{'allowedsections'}) {
                   11434:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11435:                     if (!defined($env{'request.role.sec'})
                   11436:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11437:                         $userallowed=1;
                   11438:                     } else {
                   11439:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11440:                             $userallowed=1;
                   11441:                         }
                   11442:                     }
                   11443:                     unless ($userallowed) {
                   11444:                         if (defined($env{'request.course.groups'})) {
                   11445:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11446:                             foreach my $group (@groups) {
                   11447:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11448:                                     $userallowed=1;
                   11449:                                     last;
                   11450:                                 }
                   11451:                             }
                   11452:                         }
                   11453:                     }
                   11454:                 }
                   11455:                 if ($slots{$slot}->{'allowedusers'}) {
                   11456:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11457:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11458:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11459:                         $userallowed = 1;
                   11460:                     }
                   11461:                 }
                   11462:                 next unless($userallowed);
                   11463:             }
                   11464:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11465:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11466:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11467:             my $uniqueperiod;
                   11468:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11469:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11470:             }
1.1040    raeburn  11471:             if (($startreserve < $now) &&
                   11472:                 (!$endreserve || $endreserve > $now)) {
                   11473:                 my $lastres = $endreserve;
                   11474:                 if (!$lastres) {
                   11475:                     $lastres = $slots{$slot}->{'starttime'};
                   11476:                 }
                   11477:                 $reservable_now{$slot} = {
                   11478:                                            symb       => $symb,
1.1075.2.104  raeburn  11479:                                            endreserve => $lastres,
                   11480:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11481:                                          };
                   11482:             } elsif (($startreserve > $now) &&
                   11483:                      (!$endreserve || $endreserve > $startreserve)) {
                   11484:                 $future_reservable{$slot} = {
                   11485:                                               symb         => $symb,
1.1075.2.104  raeburn  11486:                                               startreserve => $startreserve,
                   11487:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11488:                                             };
                   11489:             }
                   11490:         }
                   11491:     }
                   11492:     my @unsorted_reservable = keys(%reservable_now);
                   11493:     if (@unsorted_reservable > 0) {
                   11494:         @sorted_reservable = 
                   11495:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11496:     }
                   11497:     my @unsorted_future = keys(%future_reservable);
                   11498:     if (@unsorted_future > 0) {
                   11499:         @sorted_future =
                   11500:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11501:     }
                   11502:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11503: }
1.780     raeburn  11504: 
                   11505: =pod
                   11506: 
1.1057    foxr     11507: =back
                   11508: 
1.549     albertel 11509: =head1 HTTP Helpers
                   11510: 
                   11511: =over 4
                   11512: 
1.648     raeburn  11513: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11514: 
1.258     albertel 11515: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11516: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11517: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11518: 
                   11519: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11520: $possible_names is an ref to an array of form element names.  As an example:
                   11521: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11522: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11523: 
                   11524: =cut
1.1       albertel 11525: 
1.6       albertel 11526: sub get_unprocessed_cgi {
1.25      albertel 11527:   my ($query,$possible_names)= @_;
1.26      matthew  11528:   # $Apache::lonxml::debug=1;
1.356     albertel 11529:   foreach my $pair (split(/&/,$query)) {
                   11530:     my ($name, $value) = split(/=/,$pair);
1.369     www      11531:     $name = &unescape($name);
1.25      albertel 11532:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11533:       $value =~ tr/+/ /;
                   11534:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11535:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11536:     }
1.16      harris41 11537:   }
1.6       albertel 11538: }
                   11539: 
1.112     bowersj2 11540: =pod
                   11541: 
1.648     raeburn  11542: =item * &cacheheader() 
1.112     bowersj2 11543: 
                   11544: returns cache-controlling header code
                   11545: 
                   11546: =cut
                   11547: 
1.7       albertel 11548: sub cacheheader {
1.258     albertel 11549:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11550:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11551:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11552:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11553:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11554:     return $output;
1.7       albertel 11555: }
                   11556: 
1.112     bowersj2 11557: =pod
                   11558: 
1.648     raeburn  11559: =item * &no_cache($r) 
1.112     bowersj2 11560: 
                   11561: specifies header code to not have cache
                   11562: 
                   11563: =cut
                   11564: 
1.9       albertel 11565: sub no_cache {
1.216     albertel 11566:     my ($r) = @_;
                   11567:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11568: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11569:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11570:     $r->no_cache(1);
                   11571:     $r->header_out("Expires" => $date);
                   11572:     $r->header_out("Pragma" => "no-cache");
1.123     www      11573: }
                   11574: 
                   11575: sub content_type {
1.181     albertel 11576:     my ($r,$type,$charset) = @_;
1.299     foxr     11577:     if ($r) {
                   11578: 	#  Note that printout.pl calls this with undef for $r.
                   11579: 	&no_cache($r);
                   11580:     }
1.258     albertel 11581:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11582:     unless ($charset) {
                   11583: 	$charset=&Apache::lonlocal::current_encoding;
                   11584:     }
                   11585:     if ($charset) { $type.='; charset='.$charset; }
                   11586:     if ($r) {
                   11587: 	$r->content_type($type);
                   11588:     } else {
                   11589: 	print("Content-type: $type\n\n");
                   11590:     }
1.9       albertel 11591: }
1.25      albertel 11592: 
1.112     bowersj2 11593: =pod
                   11594: 
1.648     raeburn  11595: =item * &add_to_env($name,$value) 
1.112     bowersj2 11596: 
1.258     albertel 11597: adds $name to the %env hash with value
1.112     bowersj2 11598: $value, if $name already exists, the entry is converted to an array
                   11599: reference and $value is added to the array.
                   11600: 
                   11601: =cut
                   11602: 
1.25      albertel 11603: sub add_to_env {
                   11604:   my ($name,$value)=@_;
1.258     albertel 11605:   if (defined($env{$name})) {
                   11606:     if (ref($env{$name})) {
1.25      albertel 11607:       #already have multiple values
1.258     albertel 11608:       push(@{ $env{$name} },$value);
1.25      albertel 11609:     } else {
                   11610:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11611:       my $first=$env{$name};
                   11612:       undef($env{$name});
                   11613:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11614:     }
                   11615:   } else {
1.258     albertel 11616:     $env{$name}=$value;
1.25      albertel 11617:   }
1.31      albertel 11618: }
1.149     albertel 11619: 
                   11620: =pod
                   11621: 
1.648     raeburn  11622: =item * &get_env_multiple($name) 
1.149     albertel 11623: 
1.258     albertel 11624: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11625: values may be defined and end up as an array ref.
                   11626: 
                   11627: returns an array of values
                   11628: 
                   11629: =cut
                   11630: 
                   11631: sub get_env_multiple {
                   11632:     my ($name) = @_;
                   11633:     my @values;
1.258     albertel 11634:     if (defined($env{$name})) {
1.149     albertel 11635:         # exists is it an array
1.258     albertel 11636:         if (ref($env{$name})) {
                   11637:             @values=@{ $env{$name} };
1.149     albertel 11638:         } else {
1.258     albertel 11639:             $values[0]=$env{$name};
1.149     albertel 11640:         }
                   11641:     }
                   11642:     return(@values);
                   11643: }
                   11644: 
1.660     raeburn  11645: sub ask_for_embedded_content {
                   11646:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11647:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  11648:         %currsubfile,%unused,$rem);
1.1071    raeburn  11649:     my $counter = 0;
                   11650:     my $numnew = 0;
1.987     raeburn  11651:     my $numremref = 0;
                   11652:     my $numinvalid = 0;
                   11653:     my $numpathchg = 0;
                   11654:     my $numexisting = 0;
1.1071    raeburn  11655:     my $numunused = 0;
                   11656:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  11657:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11658:     my $heading = &mt('Upload embedded files');
                   11659:     my $buttontext = &mt('Upload');
                   11660: 
1.1075.2.11  raeburn  11661:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  11662:         if ($actionurl eq '/adm/dependencies') {
                   11663:             $navmap = Apache::lonnavmaps::navmap->new();
                   11664:         }
                   11665:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11666:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  11667:     }
1.1075.2.35  raeburn  11668:     if (($actionurl eq '/adm/portfolio') ||
                   11669:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11670:         my $current_path='/';
                   11671:         if ($env{'form.currentpath'}) {
                   11672:             $current_path = $env{'form.currentpath'};
                   11673:         }
                   11674:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  11675:             $udom = $cdom;
                   11676:             $uname = $cnum;
1.984     raeburn  11677:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11678:         } else {
                   11679:             $udom = $env{'user.domain'};
                   11680:             $uname = $env{'user.name'};
                   11681:             $url = '/userfiles/portfolio';
                   11682:         }
1.987     raeburn  11683:         $toplevel = $url.'/';
1.984     raeburn  11684:         $url .= $current_path;
                   11685:         $getpropath = 1;
1.987     raeburn  11686:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11687:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11688:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11689:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11690:         $toplevel = $url;
1.984     raeburn  11691:         if ($rest ne '') {
1.987     raeburn  11692:             $url .= $rest;
                   11693:         }
                   11694:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11695:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11696:             $url = $args->{'docs_url'};
                   11697:             $toplevel = $url;
1.1075.2.11  raeburn  11698:             if ($args->{'context'} eq 'paste') {
                   11699:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11700:                 ($path) =
                   11701:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11702:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11703:                 $fileloc =~ s{^/}{};
                   11704:             }
1.1071    raeburn  11705:         }
                   11706:     } elsif ($actionurl eq '/adm/dependencies') {
                   11707:         if ($env{'request.course.id'} ne '') {
                   11708:             if (ref($args) eq 'HASH') {
                   11709:                 $url = $args->{'docs_url'};
                   11710:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  11711:                 $toplevel = $url;
                   11712:                 unless ($toplevel =~ m{^/}) {
                   11713:                     $toplevel = "/$url";
                   11714:                 }
1.1075.2.11  raeburn  11715:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  11716:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11717:                     $path = $1;
                   11718:                 } else {
                   11719:                     ($path) =
                   11720:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11721:                 }
1.1075.2.79  raeburn  11722:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11723:                     $fileloc = $toplevel;
                   11724:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11725:                     my ($udom,$uname,$fname) =
                   11726:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11727:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11728:                 } else {
                   11729:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11730:                 }
1.1071    raeburn  11731:                 $fileloc =~ s{^/}{};
                   11732:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11733:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11734:             }
1.987     raeburn  11735:         }
1.1075.2.35  raeburn  11736:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11737:         $udom = $cdom;
                   11738:         $uname = $cnum;
                   11739:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11740:         $toplevel = $url;
                   11741:         $path = $url;
                   11742:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11743:         $fileloc =~ s{^/}{};
                   11744:     }
                   11745:     foreach my $file (keys(%{$allfiles})) {
                   11746:         my $embed_file;
                   11747:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11748:             $embed_file = $1;
                   11749:         } else {
                   11750:             $embed_file = $file;
                   11751:         }
1.1075.2.55  raeburn  11752:         my ($absolutepath,$cleaned_file);
                   11753:         if ($embed_file =~ m{^\w+://}) {
                   11754:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  11755:             $newfiles{$cleaned_file} = 1;
                   11756:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11757:         } else {
1.1075.2.55  raeburn  11758:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11759:             if ($embed_file =~ m{^/}) {
                   11760:                 $absolutepath = $embed_file;
                   11761:             }
1.1075.2.47  raeburn  11762:             if ($cleaned_file =~ m{/}) {
                   11763:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11764:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11765:                 my $item = $fname;
                   11766:                 if ($path ne '') {
                   11767:                     $item = $path.'/'.$fname;
                   11768:                     $subdependencies{$path}{$fname} = 1;
                   11769:                 } else {
                   11770:                     $dependencies{$item} = 1;
                   11771:                 }
                   11772:                 if ($absolutepath) {
                   11773:                     $mapping{$item} = $absolutepath;
                   11774:                 } else {
                   11775:                     $mapping{$item} = $embed_file;
                   11776:                 }
                   11777:             } else {
                   11778:                 $dependencies{$embed_file} = 1;
                   11779:                 if ($absolutepath) {
1.1075.2.47  raeburn  11780:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11781:                 } else {
1.1075.2.47  raeburn  11782:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11783:                 }
                   11784:             }
1.984     raeburn  11785:         }
                   11786:     }
1.1071    raeburn  11787:     my $dirptr = 16384;
1.984     raeburn  11788:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11789:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  11790:         if (($actionurl eq '/adm/portfolio') ||
                   11791:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  11792:             my ($sublistref,$listerror) =
                   11793:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11794:             if (ref($sublistref) eq 'ARRAY') {
                   11795:                 foreach my $line (@{$sublistref}) {
                   11796:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11797:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11798:                 }
1.984     raeburn  11799:             }
1.987     raeburn  11800:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11801:             if (opendir(my $dir,$url.'/'.$path)) {
                   11802:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11803:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11804:             }
1.1075.2.11  raeburn  11805:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11806:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11807:                   ($args->{'context'} eq 'paste')) ||
                   11808:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11809:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  11810:                 my $dir;
                   11811:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11812:                     $dir = $fileloc;
                   11813:                 } else {
                   11814:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11815:                 }
1.1071    raeburn  11816:                 if ($dir ne '') {
                   11817:                     my ($sublistref,$listerror) =
                   11818:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11819:                     if (ref($sublistref) eq 'ARRAY') {
                   11820:                         foreach my $line (@{$sublistref}) {
                   11821:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11822:                                 undef,$mtime)=split(/\&/,$line,12);
                   11823:                             unless (($testdir&$dirptr) ||
                   11824:                                     ($file_name =~ /^\.\.?$/)) {
                   11825:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11826:                             }
                   11827:                         }
                   11828:                     }
                   11829:                 }
1.984     raeburn  11830:             }
                   11831:         }
                   11832:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11833:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11834:                 my $item = $path.'/'.$file;
                   11835:                 unless ($mapping{$item} eq $item) {
                   11836:                     $pathchanges{$item} = 1;
                   11837:                 }
                   11838:                 $existing{$item} = 1;
                   11839:                 $numexisting ++;
                   11840:             } else {
                   11841:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11842:             }
                   11843:         }
1.1071    raeburn  11844:         if ($actionurl eq '/adm/dependencies') {
                   11845:             foreach my $path (keys(%currsubfile)) {
                   11846:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11847:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11848:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11849:                              next if (($rem ne '') &&
                   11850:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11851:                                        (ref($navmap) &&
                   11852:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11853:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11854:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11855:                              $unused{$path.'/'.$file} = 1; 
                   11856:                          }
                   11857:                     }
                   11858:                 }
                   11859:             }
                   11860:         }
1.984     raeburn  11861:     }
1.987     raeburn  11862:     my %currfile;
1.1075.2.35  raeburn  11863:     if (($actionurl eq '/adm/portfolio') ||
                   11864:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11865:         my ($dirlistref,$listerror) =
                   11866:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11867:         if (ref($dirlistref) eq 'ARRAY') {
                   11868:             foreach my $line (@{$dirlistref}) {
                   11869:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11870:                 $currfile{$file_name} = 1;
                   11871:             }
1.984     raeburn  11872:         }
1.987     raeburn  11873:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11874:         if (opendir(my $dir,$url)) {
1.987     raeburn  11875:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11876:             map {$currfile{$_} = 1;} @dir_list;
                   11877:         }
1.1075.2.11  raeburn  11878:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11879:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11880:               ($args->{'context'} eq 'paste')) ||
                   11881:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11882:         if ($env{'request.course.id'} ne '') {
                   11883:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11884:             if ($dir ne '') {
                   11885:                 my ($dirlistref,$listerror) =
                   11886:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11887:                 if (ref($dirlistref) eq 'ARRAY') {
                   11888:                     foreach my $line (@{$dirlistref}) {
                   11889:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11890:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11891:                         unless (($testdir&$dirptr) ||
                   11892:                                 ($file_name =~ /^\.\.?$/)) {
                   11893:                             $currfile{$file_name} = [$size,$mtime];
                   11894:                         }
                   11895:                     }
                   11896:                 }
                   11897:             }
                   11898:         }
1.984     raeburn  11899:     }
                   11900:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11901:         if (exists($currfile{$file})) {
1.987     raeburn  11902:             unless ($mapping{$file} eq $file) {
                   11903:                 $pathchanges{$file} = 1;
                   11904:             }
                   11905:             $existing{$file} = 1;
                   11906:             $numexisting ++;
                   11907:         } else {
1.984     raeburn  11908:             $newfiles{$file} = 1;
                   11909:         }
                   11910:     }
1.1071    raeburn  11911:     foreach my $file (keys(%currfile)) {
                   11912:         unless (($file eq $filename) ||
                   11913:                 ($file eq $filename.'.bak') ||
                   11914:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11915:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11916:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11917:                     next if (($rem ne '') &&
                   11918:                              (($env{"httpref.$rem".$file} ne '') ||
                   11919:                               (ref($navmap) &&
                   11920:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11921:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11922:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11923:                 }
1.1075.2.11  raeburn  11924:             }
1.1071    raeburn  11925:             $unused{$file} = 1;
                   11926:         }
                   11927:     }
1.1075.2.11  raeburn  11928:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11929:         ($args->{'context'} eq 'paste')) {
                   11930:         $counter = scalar(keys(%existing));
                   11931:         $numpathchg = scalar(keys(%pathchanges));
                   11932:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11933:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11934:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11935:         $counter = scalar(keys(%existing));
                   11936:         $numpathchg = scalar(keys(%pathchanges));
                   11937:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11938:     }
1.984     raeburn  11939:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11940:         if ($actionurl eq '/adm/dependencies') {
                   11941:             next if ($embed_file =~ m{^\w+://});
                   11942:         }
1.660     raeburn  11943:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11944:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11945:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11946:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11947:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11948:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11949:         }
1.1075.2.35  raeburn  11950:         $upload_output .= '</td>';
1.1071    raeburn  11951:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11952:             $upload_output.='<td align="right">'.
                   11953:                             '<span class="LC_info LC_fontsize_medium">'.
                   11954:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11955:             $numremref++;
1.660     raeburn  11956:         } elsif ($args->{'error_on_invalid_names'}
                   11957:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11958:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11959:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11960:             $numinvalid++;
1.660     raeburn  11961:         } else {
1.1075.2.35  raeburn  11962:             $upload_output .= '<td>'.
                   11963:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11964:                                                      $embed_file,\%mapping,
1.1071    raeburn  11965:                                                      $allfiles,$codebase,'upload');
                   11966:             $counter ++;
                   11967:             $numnew ++;
1.987     raeburn  11968:         }
                   11969:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11970:     }
                   11971:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11972:         if ($actionurl eq '/adm/dependencies') {
                   11973:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11974:             $modify_output .= &start_data_table_row().
                   11975:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11976:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11977:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11978:                               '<td>'.$size.'</td>'.
                   11979:                               '<td>'.$mtime.'</td>'.
                   11980:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11981:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11982:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11983:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11984:                               &embedded_file_element('upload_embedded',$counter,
                   11985:                                                      $embed_file,\%mapping,
                   11986:                                                      $allfiles,$codebase,'modify').
                   11987:                               '</div></td>'.
                   11988:                               &end_data_table_row()."\n";
                   11989:             $counter ++;
                   11990:         } else {
                   11991:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11992:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11993:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11994:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11995:                               &Apache::loncommon::end_data_table_row()."\n";
                   11996:         }
                   11997:     }
                   11998:     my $delidx = $counter;
                   11999:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12000:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12001:         $delete_output .= &start_data_table_row().
                   12002:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12003:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12004:                           '<td>'.$size.'</td>'.
                   12005:                           '<td>'.$mtime.'</td>'.
                   12006:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12007:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12008:                           &embedded_file_element('upload_embedded',$delidx,
                   12009:                                                  $oldfile,\%mapping,$allfiles,
                   12010:                                                  $codebase,'delete').'</td>'.
                   12011:                           &end_data_table_row()."\n"; 
                   12012:         $numunused ++;
                   12013:         $delidx ++;
1.987     raeburn  12014:     }
                   12015:     if ($upload_output) {
                   12016:         $upload_output = &start_data_table().
                   12017:                          $upload_output.
                   12018:                          &end_data_table()."\n";
                   12019:     }
1.1071    raeburn  12020:     if ($modify_output) {
                   12021:         $modify_output = &start_data_table().
                   12022:                          &start_data_table_header_row().
                   12023:                          '<th>'.&mt('File').'</th>'.
                   12024:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12025:                          '<th>'.&mt('Modified').'</th>'.
                   12026:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12027:                          &end_data_table_header_row().
                   12028:                          $modify_output.
                   12029:                          &end_data_table()."\n";
                   12030:     }
                   12031:     if ($delete_output) {
                   12032:         $delete_output = &start_data_table().
                   12033:                          &start_data_table_header_row().
                   12034:                          '<th>'.&mt('File').'</th>'.
                   12035:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12036:                          '<th>'.&mt('Modified').'</th>'.
                   12037:                          '<th>'.&mt('Delete?').'</th>'.
                   12038:                          &end_data_table_header_row().
                   12039:                          $delete_output.
                   12040:                          &end_data_table()."\n";
                   12041:     }
1.987     raeburn  12042:     my $applies = 0;
                   12043:     if ($numremref) {
                   12044:         $applies ++;
                   12045:     }
                   12046:     if ($numinvalid) {
                   12047:         $applies ++;
                   12048:     }
                   12049:     if ($numexisting) {
                   12050:         $applies ++;
                   12051:     }
1.1071    raeburn  12052:     if ($counter || $numunused) {
1.987     raeburn  12053:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12054:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12055:                   $state.'<h3>'.$heading.'</h3>'; 
                   12056:         if ($actionurl eq '/adm/dependencies') {
                   12057:             if ($numnew) {
                   12058:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12059:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12060:                            $upload_output.'<br />'."\n";
                   12061:             }
                   12062:             if ($numexisting) {
                   12063:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12064:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12065:                            $modify_output.'<br />'."\n";
                   12066:                            $buttontext = &mt('Save changes');
                   12067:             }
                   12068:             if ($numunused) {
                   12069:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12070:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12071:                            $delete_output.'<br />'."\n";
                   12072:                            $buttontext = &mt('Save changes');
                   12073:             }
                   12074:         } else {
                   12075:             $output .= $upload_output.'<br />'."\n";
                   12076:         }
                   12077:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12078:                    $counter.'" />'."\n";
                   12079:         if ($actionurl eq '/adm/dependencies') { 
                   12080:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12081:                        $numnew.'" />'."\n";
                   12082:         } elsif ($actionurl eq '') {
1.987     raeburn  12083:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12084:         }
                   12085:     } elsif ($applies) {
                   12086:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12087:         if ($applies > 1) {
                   12088:             $output .=  
1.1075.2.35  raeburn  12089:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12090:             if ($numremref) {
                   12091:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12092:             }
                   12093:             if ($numinvalid) {
                   12094:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12095:             }
                   12096:             if ($numexisting) {
                   12097:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12098:             }
                   12099:             $output .= '</ul><br />';
                   12100:         } elsif ($numremref) {
                   12101:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12102:         } elsif ($numinvalid) {
                   12103:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12104:         } elsif ($numexisting) {
                   12105:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12106:         }
                   12107:         $output .= $upload_output.'<br />';
                   12108:     }
                   12109:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12110:     $chgcount = $counter;
1.987     raeburn  12111:     if (keys(%pathchanges) > 0) {
                   12112:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12113:             if ($counter) {
1.987     raeburn  12114:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12115:                                                   $embed_file,\%mapping,
1.1071    raeburn  12116:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12117:             } else {
                   12118:                 $pathchange_output .= 
                   12119:                     &start_data_table_row().
                   12120:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12121:                     $chgcount.'" checked="checked" /></td>'.
                   12122:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12123:                     '<td>'.$embed_file.
                   12124:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12125:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12126:                     '</td>'.&end_data_table_row();
1.660     raeburn  12127:             }
1.987     raeburn  12128:             $numpathchg ++;
                   12129:             $chgcount ++;
1.660     raeburn  12130:         }
                   12131:     }
1.1075.2.35  raeburn  12132:     if (($counter) || ($numunused)) {
1.987     raeburn  12133:         if ($numpathchg) {
                   12134:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12135:                        $numpathchg.'" />'."\n";
                   12136:         }
                   12137:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12138:             ($actionurl eq '/adm/imsimport')) {
                   12139:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12140:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12141:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12142:         } elsif ($actionurl eq '/adm/dependencies') {
                   12143:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12144:         }
1.1075.2.35  raeburn  12145:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12146:     } elsif ($numpathchg) {
                   12147:         my %pathchange = ();
                   12148:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12149:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12150:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12151:         }
1.987     raeburn  12152:     }
1.1071    raeburn  12153:     return ($output,$counter,$numpathchg);
1.987     raeburn  12154: }
                   12155: 
1.1075.2.47  raeburn  12156: =pod
                   12157: 
                   12158: =item * clean_path($name)
                   12159: 
                   12160: Performs clean-up of directories, subdirectories and filename in an
                   12161: embedded object, referenced in an HTML file which is being uploaded
                   12162: to a course or portfolio, where
                   12163: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12164: checked.
                   12165: 
                   12166: Clean-up is similar to replacements in lonnet::clean_filename()
                   12167: except each / between sub-directory and next level is preserved.
                   12168: 
                   12169: =cut
                   12170: 
                   12171: sub clean_path {
                   12172:     my ($embed_file) = @_;
                   12173:     $embed_file =~s{^/+}{};
                   12174:     my @contents;
                   12175:     if ($embed_file =~ m{/}) {
                   12176:         @contents = split(/\//,$embed_file);
                   12177:     } else {
                   12178:         @contents = ($embed_file);
                   12179:     }
                   12180:     my $lastidx = scalar(@contents)-1;
                   12181:     for (my $i=0; $i<=$lastidx; $i++) {
                   12182:         $contents[$i]=~s{\\}{/}g;
                   12183:         $contents[$i]=~s/\s+/\_/g;
                   12184:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12185:         if ($i == $lastidx) {
                   12186:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12187:         }
                   12188:     }
                   12189:     if ($lastidx > 0) {
                   12190:         return join('/',@contents);
                   12191:     } else {
                   12192:         return $contents[0];
                   12193:     }
                   12194: }
                   12195: 
1.987     raeburn  12196: sub embedded_file_element {
1.1071    raeburn  12197:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12198:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12199:                    (ref($codebase) eq 'HASH'));
                   12200:     my $output;
1.1071    raeburn  12201:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12202:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12203:     }
                   12204:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12205:                &escape($embed_file).'" />';
                   12206:     unless (($context eq 'upload_embedded') && 
                   12207:             ($mapping->{$embed_file} eq $embed_file)) {
                   12208:         $output .='
                   12209:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12210:     }
                   12211:     my $attrib;
                   12212:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12213:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12214:     }
                   12215:     $output .=
                   12216:         "\n\t\t".
                   12217:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12218:         $attrib.'" />';
                   12219:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12220:         $output .=
                   12221:             "\n\t\t".
                   12222:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12223:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12224:     }
1.987     raeburn  12225:     return $output;
1.660     raeburn  12226: }
                   12227: 
1.1071    raeburn  12228: sub get_dependency_details {
                   12229:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12230:     my ($size,$mtime,$showsize,$showmtime);
                   12231:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12232:         if ($embed_file =~ m{/}) {
                   12233:             my ($path,$fname) = split(/\//,$embed_file);
                   12234:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12235:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12236:             }
                   12237:         } else {
                   12238:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12239:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12240:             }
                   12241:         }
                   12242:         $showsize = $size/1024.0;
                   12243:         $showsize = sprintf("%.1f",$showsize);
                   12244:         if ($mtime > 0) {
                   12245:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12246:         }
                   12247:     }
                   12248:     return ($showsize,$showmtime);
                   12249: }
                   12250: 
                   12251: sub ask_embedded_js {
                   12252:     return <<"END";
                   12253: <script type="text/javascript"">
                   12254: // <![CDATA[
                   12255: function toggleBrowse(counter) {
                   12256:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12257:     var fileid = document.getElementById('embedded_item_'+counter);
                   12258:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12259:     if (chkboxid.checked == true) {
                   12260:         uploaddivid.style.display='block';
                   12261:     } else {
                   12262:         uploaddivid.style.display='none';
                   12263:         fileid.value = '';
                   12264:     }
                   12265: }
                   12266: // ]]>
                   12267: </script>
                   12268: 
                   12269: END
                   12270: }
                   12271: 
1.661     raeburn  12272: sub upload_embedded {
                   12273:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12274:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12275:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12276:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12277:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12278:         my $orig_uploaded_filename =
                   12279:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12280:         foreach my $type ('orig','ref','attrib','codebase') {
                   12281:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12282:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12283:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12284:             }
                   12285:         }
1.661     raeburn  12286:         my ($path,$fname) =
                   12287:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12288:         # no path, whole string is fname
                   12289:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12290:         $fname = &Apache::lonnet::clean_filename($fname);
                   12291:         # See if there is anything left
                   12292:         next if ($fname eq '');
                   12293: 
                   12294:         # Check if file already exists as a file or directory.
                   12295:         my ($state,$msg);
                   12296:         if ($context eq 'portfolio') {
                   12297:             my $port_path = $dirpath;
                   12298:             if ($group ne '') {
                   12299:                 $port_path = "groups/$group/$port_path";
                   12300:             }
1.987     raeburn  12301:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12302:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12303:                                               $dir_root,$port_path,$disk_quota,
                   12304:                                               $current_disk_usage,$uname,$udom);
                   12305:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12306:                 || $state eq 'file_locked') {
1.661     raeburn  12307:                 $output .= $msg;
                   12308:                 next;
                   12309:             }
                   12310:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12311:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12312:             if ($state eq 'exists') {
                   12313:                 $output .= $msg;
                   12314:                 next;
                   12315:             }
                   12316:         }
                   12317:         # Check if extension is valid
                   12318:         if (($fname =~ /\.(\w+)$/) &&
                   12319:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12320:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12321:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12322:             next;
                   12323:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12324:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12325:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12326:             next;
                   12327:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12328:             $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  12329:             next;
                   12330:         }
                   12331:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12332:         my $subdir = $path;
                   12333:         $subdir =~ s{/+$}{};
1.661     raeburn  12334:         if ($context eq 'portfolio') {
1.984     raeburn  12335:             my $result;
                   12336:             if ($state eq 'existingfile') {
                   12337:                 $result=
                   12338:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12339:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12340:             } else {
1.984     raeburn  12341:                 $result=
                   12342:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12343:                                                     $dirpath.
1.1075.2.35  raeburn  12344:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12345:                 if ($result !~ m|^/uploaded/|) {
                   12346:                     $output .= '<span class="LC_error">'
                   12347:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12348:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12349:                                .'</span><br />';
                   12350:                     next;
                   12351:                 } else {
1.987     raeburn  12352:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12353:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12354:                 }
1.661     raeburn  12355:             }
1.1075.2.35  raeburn  12356:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12357:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12358:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12359:             my $result =
1.1075.2.35  raeburn  12360:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12361:             if ($result !~ m|^/uploaded/|) {
                   12362:                 $output .= '<span class="LC_error">'
                   12363:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12364:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12365:                            .'</span><br />';
                   12366:                     next;
                   12367:             } else {
                   12368:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12369:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12370:                 if ($context eq 'syllabus') {
                   12371:                     &Apache::lonnet::make_public_indefinitely($result);
                   12372:                 }
1.987     raeburn  12373:             }
1.661     raeburn  12374:         } else {
                   12375: # Save the file
                   12376:             my $target = $env{'form.embedded_item_'.$i};
                   12377:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12378:             my $dest = $fullpath.$fname;
                   12379:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12380:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12381:             my $count;
                   12382:             my $filepath = $dir_root;
1.1027    raeburn  12383:             foreach my $subdir (@parts) {
                   12384:                 $filepath .= "/$subdir";
                   12385:                 if (!-e $filepath) {
1.661     raeburn  12386:                     mkdir($filepath,0770);
                   12387:                 }
                   12388:             }
                   12389:             my $fh;
                   12390:             if (!open($fh,'>'.$dest)) {
                   12391:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12392:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12393:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12394:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12395:                            '</span><br />';
                   12396:             } else {
                   12397:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12398:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12399:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12400:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12401:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12402:                               '</span><br />';
                   12403:                 } else {
1.987     raeburn  12404:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12405:                                $url.'</span>').'<br />';
                   12406:                     unless ($context eq 'testbank') {
                   12407:                         $footer .= &mt('View embedded file: [_1]',
                   12408:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12409:                     }
                   12410:                 }
                   12411:                 close($fh);
                   12412:             }
                   12413:         }
                   12414:         if ($env{'form.embedded_ref_'.$i}) {
                   12415:             $pathchange{$i} = 1;
                   12416:         }
                   12417:     }
                   12418:     if ($output) {
                   12419:         $output = '<p>'.$output.'</p>';
                   12420:     }
                   12421:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12422:     $returnflag = 'ok';
1.1071    raeburn  12423:     my $numpathchgs = scalar(keys(%pathchange));
                   12424:     if ($numpathchgs > 0) {
1.987     raeburn  12425:         if ($context eq 'portfolio') {
                   12426:             $output .= '<p>'.&mt('or').'</p>';
                   12427:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12428:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12429:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12430:             $returnflag = 'modify_orightml';
                   12431:         }
                   12432:     }
1.1071    raeburn  12433:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12434: }
                   12435: 
                   12436: sub modify_html_form {
                   12437:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12438:     my $end = 0;
                   12439:     my $modifyform;
                   12440:     if ($context eq 'upload_embedded') {
                   12441:         return unless (ref($pathchange) eq 'HASH');
                   12442:         if ($env{'form.number_embedded_items'}) {
                   12443:             $end += $env{'form.number_embedded_items'};
                   12444:         }
                   12445:         if ($env{'form.number_pathchange_items'}) {
                   12446:             $end += $env{'form.number_pathchange_items'};
                   12447:         }
                   12448:         if ($end) {
                   12449:             for (my $i=0; $i<$end; $i++) {
                   12450:                 if ($i < $env{'form.number_embedded_items'}) {
                   12451:                     next unless($pathchange->{$i});
                   12452:                 }
                   12453:                 $modifyform .=
                   12454:                     &start_data_table_row().
                   12455:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12456:                     'checked="checked" /></td>'.
                   12457:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12458:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12459:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12460:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12461:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12462:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12463:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12464:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12465:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12466:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12467:                     &end_data_table_row();
1.1071    raeburn  12468:             }
1.987     raeburn  12469:         }
                   12470:     } else {
                   12471:         $modifyform = $pathchgtable;
                   12472:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12473:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12474:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12475:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12476:         }
                   12477:     }
                   12478:     if ($modifyform) {
1.1071    raeburn  12479:         if ($actionurl eq '/adm/dependencies') {
                   12480:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12481:         }
1.987     raeburn  12482:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12483:                '<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".
                   12484:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12485:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12486:                '</ol></p>'."\n".'<p>'.
                   12487:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12488:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12489:                &start_data_table()."\n".
                   12490:                &start_data_table_header_row().
                   12491:                '<th>'.&mt('Change?').'</th>'.
                   12492:                '<th>'.&mt('Current reference').'</th>'.
                   12493:                '<th>'.&mt('Required reference').'</th>'.
                   12494:                &end_data_table_header_row()."\n".
                   12495:                $modifyform.
                   12496:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12497:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12498:                '</form>'."\n";
                   12499:     }
                   12500:     return;
                   12501: }
                   12502: 
                   12503: sub modify_html_refs {
1.1075.2.35  raeburn  12504:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12505:     my $container;
                   12506:     if ($context eq 'portfolio') {
                   12507:         $container = $env{'form.container'};
                   12508:     } elsif ($context eq 'coursedoc') {
                   12509:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12510:     } elsif ($context eq 'manage_dependencies') {
                   12511:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12512:         $container = "/$container";
1.1075.2.35  raeburn  12513:     } elsif ($context eq 'syllabus') {
                   12514:         $container = $url;
1.987     raeburn  12515:     } else {
1.1027    raeburn  12516:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12517:     }
                   12518:     my (%allfiles,%codebase,$output,$content);
                   12519:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12520:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12521:         if (wantarray) {
                   12522:             return ('',0,0); 
                   12523:         } else {
                   12524:             return;
                   12525:         }
                   12526:     }
                   12527:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12528:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12529:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12530:             if (wantarray) {
                   12531:                 return ('',0,0);
                   12532:             } else {
                   12533:                 return;
                   12534:             }
                   12535:         } 
1.987     raeburn  12536:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12537:         if ($content eq '-1') {
                   12538:             if (wantarray) {
                   12539:                 return ('',0,0);
                   12540:             } else {
                   12541:                 return;
                   12542:             }
                   12543:         }
1.987     raeburn  12544:     } else {
1.1071    raeburn  12545:         unless ($container =~ /^\Q$dir_root\E/) {
                   12546:             if (wantarray) {
                   12547:                 return ('',0,0);
                   12548:             } else {
                   12549:                 return;
                   12550:             }
                   12551:         } 
1.1075.2.128  raeburn  12552:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12553:             $content = join('', <$fh>);
                   12554:             close($fh);
                   12555:         } else {
1.1071    raeburn  12556:             if (wantarray) {
                   12557:                 return ('',0,0);
                   12558:             } else {
                   12559:                 return;
                   12560:             }
1.987     raeburn  12561:         }
                   12562:     }
                   12563:     my ($count,$codebasecount) = (0,0);
                   12564:     my $mm = new File::MMagic;
                   12565:     my $mime_type = $mm->checktype_contents($content);
                   12566:     if ($mime_type eq 'text/html') {
                   12567:         my $parse_result = 
                   12568:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12569:                                                     \%codebase,\$content);
                   12570:         if ($parse_result eq 'ok') {
                   12571:             foreach my $i (@changes) {
                   12572:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12573:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12574:                 if ($allfiles{$ref}) {
                   12575:                     my $newname =  $orig;
                   12576:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12577:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12578:                     if ($attrib_regexp =~ /:/) {
                   12579:                         $attrib_regexp =~ s/\:/|/g;
                   12580:                     }
                   12581:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12582:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12583:                         $count += $numchg;
1.1075.2.35  raeburn  12584:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12585:                         delete($allfiles{$ref});
1.987     raeburn  12586:                     }
                   12587:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12588:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12589:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12590:                         $codebasecount ++;
                   12591:                     }
                   12592:                 }
                   12593:             }
1.1075.2.35  raeburn  12594:             my $skiprewrites;
1.987     raeburn  12595:             if ($count || $codebasecount) {
                   12596:                 my $saveresult;
1.1071    raeburn  12597:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12598:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12599:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12600:                     if ($url eq $container) {
                   12601:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12602:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12603:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12604:                                             $fname.'</span>').'</p>';
1.987     raeburn  12605:                     } else {
                   12606:                          $output = '<p class="LC_error">'.
                   12607:                                    &mt('Error: update failed for: [_1].',
                   12608:                                    '<span class="LC_filename">'.
                   12609:                                    $container.'</span>').'</p>';
                   12610:                     }
1.1075.2.35  raeburn  12611:                     if ($context eq 'syllabus') {
                   12612:                         unless ($saveresult eq 'ok') {
                   12613:                             $skiprewrites = 1;
                   12614:                         }
                   12615:                     }
1.987     raeburn  12616:                 } else {
1.1075.2.128  raeburn  12617:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12618:                         print $fh $content;
                   12619:                         close($fh);
                   12620:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12621:                                   $count,'<span class="LC_filename">'.
                   12622:                                   $container.'</span>').'</p>';
1.661     raeburn  12623:                     } else {
1.987     raeburn  12624:                          $output = '<p class="LC_error">'.
                   12625:                                    &mt('Error: could not update [_1].',
                   12626:                                    '<span class="LC_filename">'.
                   12627:                                    $container.'</span>').'</p>';
1.661     raeburn  12628:                     }
                   12629:                 }
                   12630:             }
1.1075.2.35  raeburn  12631:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12632:                 my ($actionurl,$state);
                   12633:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12634:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12635:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12636:                                               \%codebase,
                   12637:                                               {'context' => 'rewrites',
                   12638:                                                'ignore_remote_references' => 1,});
                   12639:                 if (ref($mapping) eq 'HASH') {
                   12640:                     my $rewrites = 0;
                   12641:                     foreach my $key (keys(%{$mapping})) {
                   12642:                         next if ($key =~ m{^https?://});
                   12643:                         my $ref = $mapping->{$key};
                   12644:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12645:                         my $attrib;
                   12646:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12647:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12648:                         }
                   12649:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12650:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12651:                             $rewrites += $numchg;
                   12652:                         }
                   12653:                     }
                   12654:                     if ($rewrites) {
                   12655:                         my $saveresult;
                   12656:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12657:                         if ($url eq $container) {
                   12658:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12659:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12660:                                             $count,'<span class="LC_filename">'.
                   12661:                                             $fname.'</span>').'</p>';
                   12662:                         } else {
                   12663:                             $output .= '<p class="LC_error">'.
                   12664:                                        &mt('Error: could not update links in [_1].',
                   12665:                                        '<span class="LC_filename">'.
                   12666:                                        $container.'</span>').'</p>';
                   12667: 
                   12668:                         }
                   12669:                     }
                   12670:                 }
                   12671:             }
1.987     raeburn  12672:         } else {
                   12673:             &logthis('Failed to parse '.$container.
                   12674:                      ' to modify references: '.$parse_result);
1.661     raeburn  12675:         }
                   12676:     }
1.1071    raeburn  12677:     if (wantarray) {
                   12678:         return ($output,$count,$codebasecount);
                   12679:     } else {
                   12680:         return $output;
                   12681:     }
1.661     raeburn  12682: }
                   12683: 
                   12684: sub check_for_existing {
                   12685:     my ($path,$fname,$element) = @_;
                   12686:     my ($state,$msg);
                   12687:     if (-d $path.'/'.$fname) {
                   12688:         $state = 'exists';
                   12689:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12690:     } elsif (-e $path.'/'.$fname) {
                   12691:         $state = 'exists';
                   12692:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12693:     }
                   12694:     if ($state eq 'exists') {
                   12695:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12696:     }
                   12697:     return ($state,$msg);
                   12698: }
                   12699: 
                   12700: sub check_for_upload {
                   12701:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12702:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12703:     my $filesize = length($env{'form.'.$element});
                   12704:     if (!$filesize) {
                   12705:         my $msg = '<span class="LC_error">'.
                   12706:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12707:                       '<span class="LC_filename">'.$fname.'</span>',
                   12708:                       $filesize).'<br />'.
1.1007    raeburn  12709:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12710:                   '</span>';
                   12711:         return ('zero_bytes',$msg);
                   12712:     }
                   12713:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12714:     my $getpropath = 1;
1.1021    raeburn  12715:     my ($dirlistref,$listerror) =
                   12716:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12717:     my $found_file = 0;
                   12718:     my $locked_file = 0;
1.991     raeburn  12719:     my @lockers;
                   12720:     my $navmap;
                   12721:     if ($env{'request.course.id'}) {
                   12722:         $navmap = Apache::lonnavmaps::navmap->new();
                   12723:     }
1.1021    raeburn  12724:     if (ref($dirlistref) eq 'ARRAY') {
                   12725:         foreach my $line (@{$dirlistref}) {
                   12726:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12727:             if ($file_name eq $fname){
                   12728:                 $file_name = $path.$file_name;
                   12729:                 if ($group ne '') {
                   12730:                     $file_name = $group.$file_name;
                   12731:                 }
                   12732:                 $found_file = 1;
                   12733:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12734:                     foreach my $lock (@lockers) {
                   12735:                         if (ref($lock) eq 'ARRAY') {
                   12736:                             my ($symb,$crsid) = @{$lock};
                   12737:                             if ($crsid eq $env{'request.course.id'}) {
                   12738:                                 if (ref($navmap)) {
                   12739:                                     my $res = $navmap->getBySymb($symb);
                   12740:                                     foreach my $part (@{$res->parts()}) { 
                   12741:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12742:                                         unless (($slot_status == $res->RESERVED) ||
                   12743:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12744:                                             $locked_file = 1;
                   12745:                                         }
1.991     raeburn  12746:                                     }
1.1021    raeburn  12747:                                 } else {
                   12748:                                     $locked_file = 1;
1.991     raeburn  12749:                                 }
                   12750:                             } else {
                   12751:                                 $locked_file = 1;
                   12752:                             }
                   12753:                         }
1.1021    raeburn  12754:                    }
                   12755:                 } else {
                   12756:                     my @info = split(/\&/,$rest);
                   12757:                     my $currsize = $info[6]/1000;
                   12758:                     if ($currsize < $filesize) {
                   12759:                         my $extra = $filesize - $currsize;
                   12760:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  12761:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12762:                                       &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.1075.2.69  raeburn  12763:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12764:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12765:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12766:                             return ('will_exceed_quota',$msg);
                   12767:                         }
1.984     raeburn  12768:                     }
                   12769:                 }
1.661     raeburn  12770:             }
                   12771:         }
                   12772:     }
                   12773:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  12774:         my $msg = '<p class="LC_warning">'.
                   12775:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   12776:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12777:         return ('will_exceed_quota',$msg);
                   12778:     } elsif ($found_file) {
                   12779:         if ($locked_file) {
1.1075.2.69  raeburn  12780:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12781:             $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.1075.2.69  raeburn  12782:             $msg .= '</p>';
1.661     raeburn  12783:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12784:             return ('file_locked',$msg);
                   12785:         } else {
1.1075.2.69  raeburn  12786:             my $msg = '<p class="LC_error">';
1.984     raeburn  12787:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  12788:             $msg .= '</p>';
1.984     raeburn  12789:             return ('existingfile',$msg);
1.661     raeburn  12790:         }
                   12791:     }
                   12792: }
                   12793: 
1.987     raeburn  12794: sub check_for_traversal {
                   12795:     my ($path,$url,$toplevel) = @_;
                   12796:     my @parts=split(/\//,$path);
                   12797:     my $cleanpath;
                   12798:     my $fullpath = $url;
                   12799:     for (my $i=0;$i<@parts;$i++) {
                   12800:         next if ($parts[$i] eq '.');
                   12801:         if ($parts[$i] eq '..') {
                   12802:             $fullpath =~ s{([^/]+/)$}{};
                   12803:         } else {
                   12804:             $fullpath .= $parts[$i].'/';
                   12805:         }
                   12806:     }
                   12807:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12808:         $cleanpath = $1;
                   12809:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12810:         my $curr_toprel = $1;
                   12811:         my @parts = split(/\//,$curr_toprel);
                   12812:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12813:         my @urlparts = split(/\//,$url_toprel);
                   12814:         my $doubledots;
                   12815:         my $startdiff = -1;
                   12816:         for (my $i=0; $i<@urlparts; $i++) {
                   12817:             if ($startdiff == -1) {
                   12818:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12819:                     $startdiff = $i;
                   12820:                     $doubledots .= '../';
                   12821:                 }
                   12822:             } else {
                   12823:                 $doubledots .= '../';
                   12824:             }
                   12825:         }
                   12826:         if ($startdiff > -1) {
                   12827:             $cleanpath = $doubledots;
                   12828:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12829:                 $cleanpath .= $parts[$i].'/';
                   12830:             }
                   12831:         }
                   12832:     }
                   12833:     $cleanpath =~ s{(/)$}{};
                   12834:     return $cleanpath;
                   12835: }
1.31      albertel 12836: 
1.1053    raeburn  12837: sub is_archive_file {
                   12838:     my ($mimetype) = @_;
                   12839:     if (($mimetype eq 'application/octet-stream') ||
                   12840:         ($mimetype eq 'application/x-stuffit') ||
                   12841:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12842:         return 1;
                   12843:     }
                   12844:     return;
                   12845: }
                   12846: 
                   12847: sub decompress_form {
1.1065    raeburn  12848:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12849:     my %lt = &Apache::lonlocal::texthash (
                   12850:         this => 'This file is an archive file.',
1.1067    raeburn  12851:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12852:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12853:         youm => 'You may wish to extract its contents.',
                   12854:         extr => 'Extract contents',
1.1067    raeburn  12855:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12856:         proa => 'Process automatically?',
1.1053    raeburn  12857:         yes  => 'Yes',
                   12858:         no   => 'No',
1.1067    raeburn  12859:         fold => 'Title for folder containing movie',
                   12860:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12861:     );
1.1065    raeburn  12862:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12863:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12864:     my $info = &list_archive_contents($fileloc,\@paths);
                   12865:     if (@paths) {
                   12866:         foreach my $path (@paths) {
                   12867:             $path =~ s{^/}{};
1.1067    raeburn  12868:             if ($path =~ m{^([^/]+)/$}) {
                   12869:                 $topdir = $1;
                   12870:             }
1.1065    raeburn  12871:             if ($path =~ m{^([^/]+)/}) {
                   12872:                 $toplevel{$1} = $path;
                   12873:             } else {
                   12874:                 $toplevel{$path} = $path;
                   12875:             }
                   12876:         }
                   12877:     }
1.1067    raeburn  12878:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12879:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12880:                         "$topdir/media/",
                   12881:                         "$topdir/media/$topdir.mp4",
                   12882:                         "$topdir/media/FirstFrame.png",
                   12883:                         "$topdir/media/player.swf",
                   12884:                         "$topdir/media/swfobject.js",
                   12885:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12886:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12887:                          "$topdir/$topdir.mp4",
                   12888:                          "$topdir/$topdir\_config.xml",
                   12889:                          "$topdir/$topdir\_controller.swf",
                   12890:                          "$topdir/$topdir\_embed.css",
                   12891:                          "$topdir/$topdir\_First_Frame.png",
                   12892:                          "$topdir/$topdir\_player.html",
                   12893:                          "$topdir/$topdir\_Thumbnails.png",
                   12894:                          "$topdir/playerProductInstall.swf",
                   12895:                          "$topdir/scripts/",
                   12896:                          "$topdir/scripts/config_xml.js",
                   12897:                          "$topdir/scripts/handlebars.js",
                   12898:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12899:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12900:                          "$topdir/scripts/modernizr.js",
                   12901:                          "$topdir/scripts/player-min.js",
                   12902:                          "$topdir/scripts/swfobject.js",
                   12903:                          "$topdir/skins/",
                   12904:                          "$topdir/skins/configuration_express.xml",
                   12905:                          "$topdir/skins/express_show/",
                   12906:                          "$topdir/skins/express_show/player-min.css",
                   12907:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12908:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12909:                          "$topdir/$topdir.mp4",
                   12910:                          "$topdir/$topdir\_config.xml",
                   12911:                          "$topdir/$topdir\_controller.swf",
                   12912:                          "$topdir/$topdir\_embed.css",
                   12913:                          "$topdir/$topdir\_First_Frame.png",
                   12914:                          "$topdir/$topdir\_player.html",
                   12915:                          "$topdir/$topdir\_Thumbnails.png",
                   12916:                          "$topdir/playerProductInstall.swf",
                   12917:                          "$topdir/scripts/",
                   12918:                          "$topdir/scripts/config_xml.js",
                   12919:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12920:                          "$topdir/skins/",
                   12921:                          "$topdir/skins/configuration_express.xml",
                   12922:                          "$topdir/skins/express_show/",
                   12923:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12924:                          "$topdir/skins/express_show/spritesheet.png",
                   12925:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12926:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12927:         if (@diffs == 0) {
1.1075.2.59  raeburn  12928:             $is_camtasia = 6;
                   12929:         } else {
1.1075.2.81  raeburn  12930:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12931:             if (@diffs == 0) {
                   12932:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12933:             } else {
                   12934:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12935:                 if (@diffs == 0) {
                   12936:                     $is_camtasia = 8;
                   12937:                 }
1.1075.2.59  raeburn  12938:             }
1.1067    raeburn  12939:         }
                   12940:     }
                   12941:     my $output;
                   12942:     if ($is_camtasia) {
                   12943:         $output = <<"ENDCAM";
                   12944: <script type="text/javascript" language="Javascript">
                   12945: // <![CDATA[
                   12946: 
                   12947: function camtasiaToggle() {
                   12948:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12949:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12950:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12951:                 document.getElementById('camtasia_titles').style.display='block';
                   12952:             } else {
                   12953:                 document.getElementById('camtasia_titles').style.display='none';
                   12954:             }
                   12955:         }
                   12956:     }
                   12957:     return;
                   12958: }
                   12959: 
                   12960: // ]]>
                   12961: </script>
                   12962: <p>$lt{'camt'}</p>
                   12963: ENDCAM
1.1065    raeburn  12964:     } else {
1.1067    raeburn  12965:         $output = '<p>'.$lt{'this'};
                   12966:         if ($info eq '') {
                   12967:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12968:         } else {
                   12969:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12970:                        '<div><pre>'.$info.'</pre></div>';
                   12971:         }
1.1065    raeburn  12972:     }
1.1067    raeburn  12973:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12974:     my $duplicates;
                   12975:     my $num = 0;
                   12976:     if (ref($dirlist) eq 'ARRAY') {
                   12977:         foreach my $item (@{$dirlist}) {
                   12978:             if (ref($item) eq 'ARRAY') {
                   12979:                 if (exists($toplevel{$item->[0]})) {
                   12980:                     $duplicates .= 
                   12981:                         &start_data_table_row().
                   12982:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12983:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12984:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12985:                         'value="1" />'.&mt('Yes').'</label>'.
                   12986:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12987:                         '<td>'.$item->[0].'</td>';
                   12988:                     if ($item->[2]) {
                   12989:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12990:                     } else {
                   12991:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12992:                     }
                   12993:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12994:                                    '<td>'.
                   12995:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12996:                                    '</td>'.
                   12997:                                    &end_data_table_row();
                   12998:                     $num ++;
                   12999:                 }
                   13000:             }
                   13001:         }
                   13002:     }
                   13003:     my $itemcount;
                   13004:     if (@paths > 0) {
                   13005:         $itemcount = scalar(@paths);
                   13006:     } else {
                   13007:         $itemcount = 1;
                   13008:     }
1.1067    raeburn  13009:     if ($is_camtasia) {
                   13010:         $output .= $lt{'auto'}.'<br />'.
                   13011:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  13012:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13013:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13014:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13015:                    $lt{'no'}.'</label></span><br />'.
                   13016:                    '<div id="camtasia_titles" style="display:block">'.
                   13017:                    &Apache::lonhtmlcommon::start_pick_box().
                   13018:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13019:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13020:                    &Apache::lonhtmlcommon::row_closure().
                   13021:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13022:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13023:                    &Apache::lonhtmlcommon::row_closure(1).
                   13024:                    &Apache::lonhtmlcommon::end_pick_box().
                   13025:                    '</div>';
                   13026:     }
1.1065    raeburn  13027:     $output .= 
                   13028:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13029:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13030:         "\n";
1.1065    raeburn  13031:     if ($duplicates ne '') {
                   13032:         $output .= '<p><span class="LC_warning">'.
                   13033:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13034:                    &start_data_table().
                   13035:                    &start_data_table_header_row().
                   13036:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13037:                    '<th>'.&mt('Name').'</th>'.
                   13038:                    '<th>'.&mt('Type').'</th>'.
                   13039:                    '<th>'.&mt('Size').'</th>'.
                   13040:                    '<th>'.&mt('Last modified').'</th>'.
                   13041:                    &end_data_table_header_row().
                   13042:                    $duplicates.
                   13043:                    &end_data_table().
                   13044:                    '</p>';
                   13045:     }
1.1067    raeburn  13046:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13047:     if (ref($hiddenelements) eq 'HASH') {
                   13048:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13049:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13050:         }
                   13051:     }
                   13052:     $output .= <<"END";
1.1067    raeburn  13053: <br />
1.1053    raeburn  13054: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13055: </form>
                   13056: $noextract
                   13057: END
                   13058:     return $output;
                   13059: }
                   13060: 
1.1065    raeburn  13061: sub decompression_utility {
                   13062:     my ($program) = @_;
                   13063:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13064:     my $location;
                   13065:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13066:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13067:                          '/usr/sbin/') {
                   13068:             if (-x $dir.$program) {
                   13069:                 $location = $dir.$program;
                   13070:                 last;
                   13071:             }
                   13072:         }
                   13073:     }
                   13074:     return $location;
                   13075: }
                   13076: 
                   13077: sub list_archive_contents {
                   13078:     my ($file,$pathsref) = @_;
                   13079:     my (@cmd,$output);
                   13080:     my $needsregexp;
                   13081:     if ($file =~ /\.zip$/) {
                   13082:         @cmd = (&decompression_utility('unzip'),"-l");
                   13083:         $needsregexp = 1;
                   13084:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13085:              ($file =~ /\.tgz$/)) {
                   13086:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13087:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13088:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13089:     } elsif ($file =~ m|\.tar$|) {
                   13090:         @cmd = (&decompression_utility('tar'),"-tf");
                   13091:     }
                   13092:     if (@cmd) {
                   13093:         undef($!);
                   13094:         undef($@);
                   13095:         if (open(my $fh,"-|", @cmd, $file)) {
                   13096:             while (my $line = <$fh>) {
                   13097:                 $output .= $line;
                   13098:                 chomp($line);
                   13099:                 my $item;
                   13100:                 if ($needsregexp) {
                   13101:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13102:                 } else {
                   13103:                     $item = $line;
                   13104:                 }
                   13105:                 if ($item ne '') {
                   13106:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13107:                         push(@{$pathsref},$item);
                   13108:                     } 
                   13109:                 }
                   13110:             }
                   13111:             close($fh);
                   13112:         }
                   13113:     }
                   13114:     return $output;
                   13115: }
                   13116: 
1.1053    raeburn  13117: sub decompress_uploaded_file {
                   13118:     my ($file,$dir) = @_;
                   13119:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13120:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13121:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13122:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13123:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13124:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13125:     my $decompressed = $env{'cgi.decompressed'};
                   13126:     &Apache::lonnet::delenv('cgi.file');
                   13127:     &Apache::lonnet::delenv('cgi.dir');
                   13128:     &Apache::lonnet::delenv('cgi.decompressed');
                   13129:     return ($decompressed,$result);
                   13130: }
                   13131: 
1.1055    raeburn  13132: sub process_decompression {
                   13133:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13134:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13135:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13136:                &mt('Unexpected file path.').'</p>'."\n";
                   13137:     }
                   13138:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13139:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13140:                &mt('Unexpected course context.').'</p>'."\n";
                   13141:     }
                   13142:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13143:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13144:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13145:     }
1.1055    raeburn  13146:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13147:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13148:         $error = &mt('Filename not a supported archive file type.').
                   13149:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13150:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13151:     } else {
                   13152:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13153:         if ($docuhome eq 'no_host') {
                   13154:             $error = &mt('Could not determine home server for course.');
                   13155:         } else {
                   13156:             my @ids=&Apache::lonnet::current_machine_ids();
                   13157:             my $currdir = "$dir_root/$destination";
                   13158:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13159:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13160:                        "$dir_root/$destination";
                   13161:             } else {
                   13162:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13163:                        "$dir_root/$docudom/$docuname/$destination";
                   13164:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13165:                     $error = &mt('Archive file not found.');
                   13166:                 }
                   13167:             }
1.1065    raeburn  13168:             my (@to_overwrite,@to_skip);
                   13169:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13170:                 my $total = $env{'form.archive_overwrite_total'};
                   13171:                 for (my $i=0; $i<$total; $i++) {
                   13172:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13173:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13174:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13175:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13176:                     }
                   13177:                 }
                   13178:             }
                   13179:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13180:             my $numoverwrite = scalar(@to_overwrite);
                   13181:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13182:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13183:             } elsif ($dir eq '') {
1.1055    raeburn  13184:                 $error = &mt('Directory containing archive file unavailable.');
                   13185:             } elsif (!$error) {
1.1065    raeburn  13186:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13187:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13188:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13189:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13190:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13191:                         ($decompressed,$display) =
                   13192:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13193:                         foreach my $item (@to_skip) {
                   13194:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13195:                                 if (-f "$dir/$tempdir/$item") {
                   13196:                                     unlink("$dir/$tempdir/$item");
                   13197:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13198:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13199:                                 }
                   13200:                             }
                   13201:                         }
                   13202:                         foreach my $item (@to_overwrite) {
                   13203:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13204:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13205:                                     if (-f "$dir/$item") {
                   13206:                                         unlink("$dir/$item");
                   13207:                                     } elsif (-d "$dir/$item") {
                   13208:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13209:                                     }
                   13210:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13211:                                 }
1.1065    raeburn  13212:                             }
                   13213:                         }
1.1075.2.128  raeburn  13214:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13215:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13216:                         }
1.1065    raeburn  13217:                     }
                   13218:                 } else {
                   13219:                     ($decompressed,$display) = 
                   13220:                         &decompress_uploaded_file($file,$dir);
                   13221:                 }
1.1055    raeburn  13222:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13223:                     $output = '<p class="LC_info">'.
                   13224:                               &mt('Files extracted successfully from archive.').
                   13225:                               '</p>'."\n";
1.1055    raeburn  13226:                     my ($warning,$result,@contents);
                   13227:                     my ($newdirlistref,$newlisterror) =
                   13228:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13229:                                                  $docuname,1);
                   13230:                     my (%is_dir,%changes,@newitems);
                   13231:                     my $dirptr = 16384;
1.1065    raeburn  13232:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13233:                         foreach my $dir_line (@{$newdirlistref}) {
                   13234:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13235:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13236:                                 push(@newitems,$item);
                   13237:                                 if ($dirptr&$testdir) {
                   13238:                                     $is_dir{$item} = 1;
                   13239:                                 }
                   13240:                                 $changes{$item} = 1;
                   13241:                             }
                   13242:                         }
                   13243:                     }
                   13244:                     if (keys(%changes) > 0) {
                   13245:                         foreach my $item (sort(@newitems)) {
                   13246:                             if ($changes{$item}) {
                   13247:                                 push(@contents,$item);
                   13248:                             }
                   13249:                         }
                   13250:                     }
                   13251:                     if (@contents > 0) {
1.1067    raeburn  13252:                         my $wantform;
                   13253:                         unless ($env{'form.autoextract_camtasia'}) {
                   13254:                             $wantform = 1;
                   13255:                         }
1.1056    raeburn  13256:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13257:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13258:                                                                 $currdir,\%is_dir,
                   13259:                                                                 \%children,\%parent,
1.1056    raeburn  13260:                                                                 \@contents,\%dirorder,
                   13261:                                                                 \%titles,$wantform);
1.1055    raeburn  13262:                         if ($datatable ne '') {
                   13263:                             $output .= &archive_options_form('decompressed',$datatable,
                   13264:                                                              $count,$hiddenelem);
1.1065    raeburn  13265:                             my $startcount = 6;
1.1055    raeburn  13266:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13267:                                                            \%titles,\%children);
1.1055    raeburn  13268:                         }
1.1067    raeburn  13269:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13270:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13271:                             my %displayed;
                   13272:                             my $total = 1;
                   13273:                             $env{'form.archive_directory'} = [];
                   13274:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13275:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13276:                                 $path =~ s{/$}{};
                   13277:                                 my $item;
                   13278:                                 if ($path ne '') {
                   13279:                                     $item = "$path/$titles{$i}";
                   13280:                                 } else {
                   13281:                                     $item = $titles{$i};
                   13282:                                 }
                   13283:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13284:                                 if ($item eq $contents[0]) {
                   13285:                                     push(@{$env{'form.archive_directory'}},$i);
                   13286:                                     $env{'form.archive_'.$i} = 'display';
                   13287:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13288:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13289:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13290:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13291:                                     $env{'form.archive_'.$i} = 'display';
                   13292:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13293:                                     $displayed{'web'} = $i;
                   13294:                                 } else {
1.1075.2.59  raeburn  13295:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13296:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13297:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13298:                                         push(@{$env{'form.archive_directory'}},$i);
                   13299:                                     }
                   13300:                                     $env{'form.archive_'.$i} = 'dependency';
                   13301:                                 }
                   13302:                                 $total ++;
                   13303:                             }
                   13304:                             for (my $i=1; $i<$total; $i++) {
                   13305:                                 next if ($i == $displayed{'web'});
                   13306:                                 next if ($i == $displayed{'folder'});
                   13307:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13308:                             }
                   13309:                             $env{'form.phase'} = 'decompress_cleanup';
                   13310:                             $env{'form.archivedelete'} = 1;
                   13311:                             $env{'form.archive_count'} = $total-1;
                   13312:                             $output .=
                   13313:                                 &process_extracted_files('coursedocs',$docudom,
                   13314:                                                          $docuname,$destination,
                   13315:                                                          $dir_root,$hiddenelem);
                   13316:                         }
1.1055    raeburn  13317:                     } else {
                   13318:                         $warning = &mt('No new items extracted from archive file.');
                   13319:                     }
                   13320:                 } else {
                   13321:                     $output = $display;
                   13322:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13323:                 }
                   13324:             }
                   13325:         }
                   13326:     }
                   13327:     if ($error) {
                   13328:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13329:                    $error.'</p>'."\n";
                   13330:     }
                   13331:     if ($warning) {
                   13332:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13333:     }
                   13334:     return $output;
                   13335: }
                   13336: 
                   13337: sub get_extracted {
1.1056    raeburn  13338:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13339:         $titles,$wantform) = @_;
1.1055    raeburn  13340:     my $count = 0;
                   13341:     my $depth = 0;
                   13342:     my $datatable;
1.1056    raeburn  13343:     my @hierarchy;
1.1055    raeburn  13344:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13345:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13346:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13347:     foreach my $item (@{$contents}) {
                   13348:         $count ++;
1.1056    raeburn  13349:         @{$dirorder->{$count}} = @hierarchy;
                   13350:         $titles->{$count} = $item;
1.1055    raeburn  13351:         &archive_hierarchy($depth,$count,$parent,$children);
                   13352:         if ($wantform) {
                   13353:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13354:                                        $currdir,$depth,$count);
                   13355:         }
                   13356:         if ($is_dir->{$item}) {
                   13357:             $depth ++;
1.1056    raeburn  13358:             push(@hierarchy,$count);
                   13359:             $parent->{$depth} = $count;
1.1055    raeburn  13360:             $datatable .=
                   13361:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13362:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13363:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13364:             $depth --;
1.1056    raeburn  13365:             pop(@hierarchy);
1.1055    raeburn  13366:         }
                   13367:     }
                   13368:     return ($count,$datatable);
                   13369: }
                   13370: 
                   13371: sub recurse_extracted_archive {
1.1056    raeburn  13372:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13373:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13374:     my $result='';
1.1056    raeburn  13375:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13376:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13377:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13378:         return $result;
                   13379:     }
                   13380:     my $dirptr = 16384;
                   13381:     my ($newdirlistref,$newlisterror) =
                   13382:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13383:     if (ref($newdirlistref) eq 'ARRAY') {
                   13384:         foreach my $dir_line (@{$newdirlistref}) {
                   13385:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13386:             unless ($item =~ /^\.+$/) {
                   13387:                 $$count ++;
1.1056    raeburn  13388:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13389:                 $titles->{$$count} = $item;
1.1055    raeburn  13390:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13391: 
1.1055    raeburn  13392:                 my $is_dir;
                   13393:                 if ($dirptr&$testdir) {
                   13394:                     $is_dir = 1;
                   13395:                 }
                   13396:                 if ($wantform) {
                   13397:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13398:                 }
                   13399:                 if ($is_dir) {
                   13400:                     $$depth ++;
1.1056    raeburn  13401:                     push(@{$hierarchy},$$count);
                   13402:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13403:                     $result .=
                   13404:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13405:                                                    $docuname,$depth,$count,
1.1056    raeburn  13406:                                                    $hierarchy,$dirorder,$children,
                   13407:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13408:                     $$depth --;
1.1056    raeburn  13409:                     pop(@{$hierarchy});
1.1055    raeburn  13410:                 }
                   13411:             }
                   13412:         }
                   13413:     }
                   13414:     return $result;
                   13415: }
                   13416: 
                   13417: sub archive_hierarchy {
                   13418:     my ($depth,$count,$parent,$children) =@_;
                   13419:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13420:         if (exists($parent->{$depth})) {
                   13421:              $children->{$parent->{$depth}} .= $count.':';
                   13422:         }
                   13423:     }
                   13424:     return;
                   13425: }
                   13426: 
                   13427: sub archive_row {
                   13428:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13429:     my ($name) = ($item =~ m{([^/]+)$});
                   13430:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13431:                                        'display'    => 'Add as file',
1.1055    raeburn  13432:                                        'dependency' => 'Include as dependency',
                   13433:                                        'discard'    => 'Discard',
                   13434:                                       );
                   13435:     if ($is_dir) {
1.1059    raeburn  13436:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13437:     }
1.1056    raeburn  13438:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13439:     my $offset = 0;
1.1055    raeburn  13440:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13441:         $offset ++;
1.1065    raeburn  13442:         if ($action ne 'display') {
                   13443:             $offset ++;
                   13444:         }  
1.1055    raeburn  13445:         $output .= '<td><span class="LC_nobreak">'.
                   13446:                    '<label><input type="radio" name="archive_'.$count.
                   13447:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13448:         my $text = $choices{$action};
                   13449:         if ($is_dir) {
                   13450:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13451:             if ($action eq 'display') {
1.1059    raeburn  13452:                 $text = &mt('Add as folder');
1.1055    raeburn  13453:             }
1.1056    raeburn  13454:         } else {
                   13455:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13456: 
                   13457:         }
                   13458:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13459:         if ($action eq 'dependency') {
                   13460:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13461:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13462:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13463:                        '<option value=""></option>'."\n".
                   13464:                        '</select>'."\n".
                   13465:                        '</div>';
1.1059    raeburn  13466:         } elsif ($action eq 'display') {
                   13467:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13468:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13469:                        '</div>';
1.1055    raeburn  13470:         }
1.1056    raeburn  13471:         $output .= '</td>';
1.1055    raeburn  13472:     }
                   13473:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13474:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13475:     for (my $i=0; $i<$depth; $i++) {
                   13476:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13477:     }
                   13478:     if ($is_dir) {
                   13479:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13480:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13481:     } else {
                   13482:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13483:     }
                   13484:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13485:                &end_data_table_row();
                   13486:     return $output;
                   13487: }
                   13488: 
                   13489: sub archive_options_form {
1.1065    raeburn  13490:     my ($form,$display,$count,$hiddenelem) = @_;
                   13491:     my %lt = &Apache::lonlocal::texthash(
                   13492:                perm => 'Permanently remove archive file?',
                   13493:                hows => 'How should each extracted item be incorporated in the course?',
                   13494:                cont => 'Content actions for all',
                   13495:                addf => 'Add as folder/file',
                   13496:                incd => 'Include as dependency for a displayed file',
                   13497:                disc => 'Discard',
                   13498:                no   => 'No',
                   13499:                yes  => 'Yes',
                   13500:                save => 'Save',
                   13501:     );
                   13502:     my $output = <<"END";
                   13503: <form name="$form" method="post" action="">
                   13504: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13505: <label>
                   13506:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13507: </label>
                   13508: &nbsp;
                   13509: <label>
                   13510:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13511: </span>
                   13512: </p>
                   13513: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13514: <br />$lt{'hows'}
                   13515: <div class="LC_columnSection">
                   13516:   <fieldset>
                   13517:     <legend>$lt{'cont'}</legend>
                   13518:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13519:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13520:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13521:   </fieldset>
                   13522: </div>
                   13523: END
                   13524:     return $output.
1.1055    raeburn  13525:            &start_data_table()."\n".
1.1065    raeburn  13526:            $display."\n".
1.1055    raeburn  13527:            &end_data_table()."\n".
                   13528:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13529:            $hiddenelem.
1.1065    raeburn  13530:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13531:            '</form>';
                   13532: }
                   13533: 
                   13534: sub archive_javascript {
1.1056    raeburn  13535:     my ($startcount,$numitems,$titles,$children) = @_;
                   13536:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13537:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13538:     my $scripttag = <<START;
                   13539: <script type="text/javascript">
                   13540: // <![CDATA[
                   13541: 
                   13542: function checkAll(form,prefix) {
                   13543:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13544:     for (var i=0; i < form.elements.length; i++) {
                   13545:         var id = form.elements[i].id;
                   13546:         if ((id != '') && (id != undefined)) {
                   13547:             if (idstr.test(id)) {
                   13548:                 if (form.elements[i].type == 'radio') {
                   13549:                     form.elements[i].checked = true;
1.1056    raeburn  13550:                     var nostart = i-$startcount;
1.1059    raeburn  13551:                     var offset = nostart%7;
                   13552:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13553:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13554:                 }
                   13555:             }
                   13556:         }
                   13557:     }
                   13558: }
                   13559: 
                   13560: function propagateCheck(form,count) {
                   13561:     if (count > 0) {
1.1059    raeburn  13562:         var startelement = $startcount + ((count-1) * 7);
                   13563:         for (var j=1; j<6; j++) {
                   13564:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13565:                 var item = startelement + j; 
                   13566:                 if (form.elements[item].type == 'radio') {
                   13567:                     if (form.elements[item].checked) {
                   13568:                         containerCheck(form,count,j);
                   13569:                         break;
                   13570:                     }
1.1055    raeburn  13571:                 }
                   13572:             }
                   13573:         }
                   13574:     }
                   13575: }
                   13576: 
                   13577: numitems = $numitems
1.1056    raeburn  13578: var titles = new Array(numitems);
                   13579: var parents = new Array(numitems);
1.1055    raeburn  13580: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13581:     parents[i] = new Array;
1.1055    raeburn  13582: }
1.1059    raeburn  13583: var maintitle = '$maintitle';
1.1055    raeburn  13584: 
                   13585: START
                   13586: 
1.1056    raeburn  13587:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13588:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13589:         for (my $i=0; $i<@contents; $i ++) {
                   13590:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13591:         }
                   13592:     }
                   13593: 
1.1056    raeburn  13594:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13595:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13596:     }
                   13597: 
1.1055    raeburn  13598:     $scripttag .= <<END;
                   13599: 
                   13600: function containerCheck(form,count,offset) {
                   13601:     if (count > 0) {
1.1056    raeburn  13602:         dependencyCheck(form,count,offset);
1.1059    raeburn  13603:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13604:         form.elements[item].checked = true;
                   13605:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13606:             if (parents[count].length > 0) {
                   13607:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13608:                     containerCheck(form,parents[count][j],offset);
                   13609:                 }
                   13610:             }
                   13611:         }
                   13612:     }
                   13613: }
                   13614: 
                   13615: function dependencyCheck(form,count,offset) {
                   13616:     if (count > 0) {
1.1059    raeburn  13617:         var chosen = (offset+$startcount)+7*(count-1);
                   13618:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13619:         var currtype = form.elements[depitem].type;
                   13620:         if (form.elements[chosen].value == 'dependency') {
                   13621:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13622:             form.elements[depitem].options.length = 0;
                   13623:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  13624:             for (var i=1; i<=numitems; i++) {
                   13625:                 if (i == count) {
                   13626:                     continue;
                   13627:                 }
1.1059    raeburn  13628:                 var startelement = $startcount + (i-1) * 7;
                   13629:                 for (var j=1; j<6; j++) {
                   13630:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13631:                         var item = startelement + j;
                   13632:                         if (form.elements[item].type == 'radio') {
                   13633:                             if (form.elements[item].checked) {
                   13634:                                 if (form.elements[item].value == 'display') {
                   13635:                                     var n = form.elements[depitem].options.length;
                   13636:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13637:                                 }
                   13638:                             }
                   13639:                         }
                   13640:                     }
                   13641:                 }
                   13642:             }
                   13643:         } else {
                   13644:             document.getElementById('arc_depon_'+count).style.display='none';
                   13645:             form.elements[depitem].options.length = 0;
                   13646:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13647:         }
1.1059    raeburn  13648:         titleCheck(form,count,offset);
1.1056    raeburn  13649:     }
                   13650: }
                   13651: 
                   13652: function propagateSelect(form,count,offset) {
                   13653:     if (count > 0) {
1.1065    raeburn  13654:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13655:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13656:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13657:             if (parents[count].length > 0) {
                   13658:                 for (var j=0; j<parents[count].length; j++) {
                   13659:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13660:                 }
                   13661:             }
                   13662:         }
                   13663:     }
                   13664: }
1.1056    raeburn  13665: 
                   13666: function containerSelect(form,count,offset,picked) {
                   13667:     if (count > 0) {
1.1065    raeburn  13668:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13669:         if (form.elements[item].type == 'radio') {
                   13670:             if (form.elements[item].value == 'dependency') {
                   13671:                 if (form.elements[item+1].type == 'select-one') {
                   13672:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13673:                         if (form.elements[item+1].options[i].value == picked) {
                   13674:                             form.elements[item+1].selectedIndex = i;
                   13675:                             break;
                   13676:                         }
                   13677:                     }
                   13678:                 }
                   13679:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13680:                     if (parents[count].length > 0) {
                   13681:                         for (var j=0; j<parents[count].length; j++) {
                   13682:                             containerSelect(form,parents[count][j],offset,picked);
                   13683:                         }
                   13684:                     }
                   13685:                 }
                   13686:             }
                   13687:         }
                   13688:     }
                   13689: }
                   13690: 
1.1059    raeburn  13691: function titleCheck(form,count,offset) {
                   13692:     if (count > 0) {
                   13693:         var chosen = (offset+$startcount)+7*(count-1);
                   13694:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13695:         var currtype = form.elements[depitem].type;
                   13696:         if (form.elements[chosen].value == 'display') {
                   13697:             document.getElementById('arc_title_'+count).style.display='block';
                   13698:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13699:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13700:             }
                   13701:         } else {
                   13702:             document.getElementById('arc_title_'+count).style.display='none';
                   13703:             if (currtype == 'text') { 
                   13704:                 document.getElementById('archive_title_'+count).value='';
                   13705:             }
                   13706:         }
                   13707:     }
                   13708:     return;
                   13709: }
                   13710: 
1.1055    raeburn  13711: // ]]>
                   13712: </script>
                   13713: END
                   13714:     return $scripttag;
                   13715: }
                   13716: 
                   13717: sub process_extracted_files {
1.1067    raeburn  13718:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13719:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  13720:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13721:     my @ids=&Apache::lonnet::current_machine_ids();
                   13722:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13723:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13724:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13725:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13726:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13727:         $pathtocheck = "$dir_root/$destination";
                   13728:         $dir = $dir_root;
                   13729:         $ishome = 1;
                   13730:     } else {
                   13731:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13732:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  13733:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13734:     }
                   13735:     my $currdir = "$dir_root/$destination";
                   13736:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13737:     if ($env{'form.folderpath'}) {
                   13738:         my @items = split('&',$env{'form.folderpath'});
                   13739:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  13740:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13741:             $containers{'0'}='page';
                   13742:         } else {
                   13743:             $containers{'0'}='sequence';
                   13744:         }
1.1055    raeburn  13745:     }
                   13746:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13747:     if ($numitems) {
                   13748:         for (my $i=1; $i<=$numitems; $i++) {
                   13749:             my $path = $env{'form.archive_content_'.$i};
                   13750:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13751:                 my $item = $1;
                   13752:                 $toplevelitems{$item} = $i;
                   13753:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13754:                     $is_dir{$item} = 1;
                   13755:                 }
                   13756:             }
                   13757:         }
                   13758:     }
1.1067    raeburn  13759:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13760:     if (keys(%toplevelitems) > 0) {
                   13761:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13762:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13763:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13764:     }
1.1066    raeburn  13765:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13766:     if ($numitems) {
                   13767:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  13768:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13769:             my $path = $env{'form.archive_content_'.$i};
                   13770:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13771:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13772:                     if ($prefix ne '' && $path ne '') {
                   13773:                         if (-e $prefix.$path) {
1.1066    raeburn  13774:                             if ((@archdirs > 0) && 
                   13775:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13776:                                 $todeletedir{$prefix.$path} = 1;
                   13777:                             } else {
                   13778:                                 $todelete{$prefix.$path} = 1;
                   13779:                             }
1.1055    raeburn  13780:                         }
                   13781:                     }
                   13782:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13783:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13784:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13785:                     $docstitle = $env{'form.archive_title_'.$i};
                   13786:                     if ($docstitle eq '') {
                   13787:                         $docstitle = $title;
                   13788:                     }
1.1055    raeburn  13789:                     $outer = 0;
1.1056    raeburn  13790:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13791:                         if (@{$dirorder{$i}} > 0) {
                   13792:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13793:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13794:                                     $outer = $item;
                   13795:                                     last;
                   13796:                                 }
                   13797:                             }
                   13798:                         }
                   13799:                     }
                   13800:                     my ($errtext,$fatal) = 
                   13801:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13802:                                                '/'.$folders{$outer}.'.'.
                   13803:                                                $containers{$outer});
                   13804:                     next if ($fatal);
                   13805:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13806:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13807:                             $mapinner{$i} = time;
1.1055    raeburn  13808:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13809:                             $containers{$i} = 'sequence';
                   13810:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13811:                                       $folders{$i}.'.'.$containers{$i};
                   13812:                             my $newidx = &LONCAPA::map::getresidx();
                   13813:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13814:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13815:                             push(@LONCAPA::map::order,$newidx);
                   13816:                             my ($outtext,$errtext) =
                   13817:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13818:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  13819:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13820:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13821:                             unless ($errtext) {
1.1075.2.128  raeburn  13822:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13823:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13824:                                             '</li>'."\n";
1.1067    raeburn  13825:                             }
1.1055    raeburn  13826:                         }
                   13827:                     } else {
                   13828:                         if ($context eq 'coursedocs') {
                   13829:                             my $newidx=&LONCAPA::map::getresidx();
                   13830:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13831:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13832:                                       $title;
1.1075.2.161.  .13(raeb 13833:-23):                             if (($outer !~ /\D/) &&
                   13834:-23):                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   13835:-23):                                 ($newidx !~ /\D/)) {
1.1075.2.128  raeburn  13836:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13837:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13838:                                 }
1.1075.2.128  raeburn  13839:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13840:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13841:                                 }
                   13842:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13843:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13844:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13845:                                         unless ($ishome) {
                   13846:                                             my $fetch = "$newdest{$i}/$title";
                   13847:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13848:                                             $prompttofetch{$fetch} = 1;
                   13849:                                         }
                   13850:                                    }
                   13851:                                 }
                   13852:                                 $LONCAPA::map::resources[$newidx]=
                   13853:                                     $docstitle.':'.$url.':false:normal:res';
                   13854:                                 push(@LONCAPA::map::order, $newidx);
                   13855:                                 my ($outtext,$errtext)=
                   13856:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13857:                                                             $docuname.'/'.$folders{$outer}.
                   13858:                                                             '.'.$containers{$outer},1,1);
                   13859:                                 unless ($errtext) {
                   13860:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13861:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13862:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13863:                                                    '</li>'."\n";
                   13864:                                     }
1.1067    raeburn  13865:                                 }
1.1075.2.128  raeburn  13866:                             } else {
                   13867:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13868:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13869:                             }
1.1055    raeburn  13870:                         }
                   13871:                     }
1.1075.2.11  raeburn  13872:                 }
                   13873:             } else {
1.1075.2.128  raeburn  13874:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13875:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13876:             }
                   13877:         }
                   13878:         for (my $i=1; $i<=$numitems; $i++) {
                   13879:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13880:             my $path = $env{'form.archive_content_'.$i};
                   13881:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13882:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13883:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13884:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13885:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13886:                         my ($itemidx,$fullpath,$relpath);
                   13887:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13888:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13889:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13890:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13891:                                     $itemidx = $j;
1.1056    raeburn  13892:                                 }
                   13893:                             }
1.1075.2.11  raeburn  13894:                         }
                   13895:                         if ($itemidx eq '') {
                   13896:                             $itemidx =  0;
                   13897:                         }
                   13898:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13899:                             if ($mapinner{$referrer{$i}}) {
                   13900:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13901:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13902:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13903:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13904:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13905:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13906:                                             if (!-e $fullpath) {
                   13907:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13908:                                             }
                   13909:                                         }
1.1075.2.11  raeburn  13910:                                     } else {
                   13911:                                         last;
1.1056    raeburn  13912:                                     }
1.1075.2.11  raeburn  13913:                                 }
                   13914:                             }
                   13915:                         } elsif ($newdest{$referrer{$i}}) {
                   13916:                             $fullpath = $newdest{$referrer{$i}};
                   13917:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13918:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13919:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13920:                                     last;
                   13921:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13922:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13923:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13924:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13925:                                         if (!-e $fullpath) {
                   13926:                                             mkdir($fullpath,0755);
1.1056    raeburn  13927:                                         }
                   13928:                                     }
1.1075.2.11  raeburn  13929:                                 } else {
                   13930:                                     last;
1.1056    raeburn  13931:                                 }
1.1075.2.11  raeburn  13932:                             }
                   13933:                         }
                   13934:                         if ($fullpath ne '') {
                   13935:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13936:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13937:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13938:                                 }
1.1075.2.11  raeburn  13939:                             }
                   13940:                             if (-e "$fullpath/$title") {
                   13941:                                 my $showpath;
                   13942:                                 if ($relpath ne '') {
                   13943:                                     $showpath = "$relpath/$title";
                   13944:                                 } else {
                   13945:                                     $showpath = "/$title";
1.1056    raeburn  13946:                                 }
1.1075.2.128  raeburn  13947:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13948:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13949:                                            '</li>'."\n";
                   13950:                                 unless ($ishome) {
                   13951:                                     my $fetch = "$fullpath/$title";
                   13952:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13953:                                     $prompttofetch{$fetch} = 1;
                   13954:                                 }
1.1055    raeburn  13955:                             }
                   13956:                         }
                   13957:                     }
1.1075.2.11  raeburn  13958:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13959:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13960:                                     &HTML::Entities::encode($path,'<>&"'),
                   13961:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13962:                                 '<br />';
1.1055    raeburn  13963:                 }
                   13964:             } else {
1.1075.2.128  raeburn  13965:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13966:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13967:             }
                   13968:         }
                   13969:         if (keys(%todelete)) {
                   13970:             foreach my $key (keys(%todelete)) {
                   13971:                 unlink($key);
1.1066    raeburn  13972:             }
                   13973:         }
                   13974:         if (keys(%todeletedir)) {
                   13975:             foreach my $key (keys(%todeletedir)) {
                   13976:                 rmdir($key);
                   13977:             }
                   13978:         }
                   13979:         foreach my $dir (sort(keys(%is_dir))) {
                   13980:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13981:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13982:             }
                   13983:         }
1.1067    raeburn  13984:         if ($result ne '') {
                   13985:             $output .= '<ul>'."\n".
                   13986:                        $result."\n".
                   13987:                        '</ul>';
                   13988:         }
                   13989:         unless ($ishome) {
                   13990:             my $replicationfail;
                   13991:             foreach my $item (keys(%prompttofetch)) {
                   13992:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13993:                 unless ($fetchresult eq 'ok') {
                   13994:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13995:                 }
                   13996:             }
                   13997:             if ($replicationfail) {
                   13998:                 $output .= '<p class="LC_error">'.
                   13999:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14000:                            $replicationfail.
                   14001:                            '</ul></p>';
                   14002:             }
                   14003:         }
1.1055    raeburn  14004:     } else {
                   14005:         $warning = &mt('No items found in archive.');
                   14006:     }
                   14007:     if ($error) {
                   14008:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14009:                    $error.'</p>'."\n";
                   14010:     }
                   14011:     if ($warning) {
                   14012:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14013:     }
                   14014:     return $output;
                   14015: }
                   14016: 
1.1066    raeburn  14017: sub cleanup_empty_dirs {
                   14018:     my ($path) = @_;
                   14019:     if (($path ne '') && (-d $path)) {
                   14020:         if (opendir(my $dirh,$path)) {
                   14021:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14022:             my $numitems = 0;
                   14023:             foreach my $item (@dircontents) {
                   14024:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  14025:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14026:                     if (-e "$path/$item") {
                   14027:                         $numitems ++;
                   14028:                     }
                   14029:                 } else {
                   14030:                     $numitems ++;
                   14031:                 }
                   14032:             }
                   14033:             if ($numitems == 0) {
                   14034:                 rmdir($path);
                   14035:             }
                   14036:             closedir($dirh);
                   14037:         }
                   14038:     }
                   14039:     return;
                   14040: }
                   14041: 
1.41      ng       14042: =pod
1.45      matthew  14043: 
1.1075.2.56  raeburn  14044: =item * &get_folder_hierarchy()
1.1068    raeburn  14045: 
                   14046: Provides hierarchy of names of folders/sub-folders containing the current
                   14047: item,
                   14048: 
                   14049: Inputs: 3
                   14050:      - $navmap - navmaps object
                   14051: 
                   14052:      - $map - url for map (either the trigger itself, or map containing
                   14053:                            the resource, which is the trigger).
                   14054: 
                   14055:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14056: 
                   14057: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14058: 
                   14059: =cut
                   14060: 
                   14061: sub get_folder_hierarchy {
                   14062:     my ($navmap,$map,$showitem) = @_;
                   14063:     my @pathitems;
                   14064:     if (ref($navmap)) {
                   14065:         my $mapres = $navmap->getResourceByUrl($map);
                   14066:         if (ref($mapres)) {
                   14067:             my $pcslist = $mapres->map_hierarchy();
                   14068:             if ($pcslist ne '') {
                   14069:                 my @pcs = split(/,/,$pcslist);
                   14070:                 foreach my $pc (@pcs) {
                   14071:                     if ($pc == 1) {
1.1075.2.38  raeburn  14072:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14073:                     } else {
                   14074:                         my $res = $navmap->getByMapPc($pc);
                   14075:                         if (ref($res)) {
                   14076:                             my $title = $res->compTitle();
                   14077:                             $title =~ s/\W+/_/g;
                   14078:                             if ($title ne '') {
                   14079:                                 push(@pathitems,$title);
                   14080:                             }
                   14081:                         }
                   14082:                     }
                   14083:                 }
                   14084:             }
1.1071    raeburn  14085:             if ($showitem) {
                   14086:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  14087:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14088:                 } else {
                   14089:                     my $maptitle = $mapres->compTitle();
                   14090:                     $maptitle =~ s/\W+/_/g;
                   14091:                     if ($maptitle ne '') {
                   14092:                         push(@pathitems,$maptitle);
                   14093:                     }
1.1068    raeburn  14094:                 }
                   14095:             }
                   14096:         }
                   14097:     }
                   14098:     return @pathitems;
                   14099: }
                   14100: 
                   14101: =pod
                   14102: 
1.1015    raeburn  14103: =item * &get_turnedin_filepath()
                   14104: 
                   14105: Determines path in a user's portfolio file for storage of files uploaded
                   14106: to a specific essayresponse or dropbox item.
                   14107: 
                   14108: Inputs: 3 required + 1 optional.
                   14109: $symb is symb for resource, $uname and $udom are for current user (required).
                   14110: $caller is optional (can be "submission", if routine is called when storing
                   14111: an upoaded file when "Submit Answer" button was pressed).
                   14112: 
                   14113: Returns array containing $path and $multiresp. 
                   14114: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14115: than one file upload item.  Callers of routine should append partid as a 
                   14116: subdirectory to $path in cases where $multiresp is 1.
                   14117: 
                   14118: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14119: 
                   14120: =cut
                   14121: 
                   14122: sub get_turnedin_filepath {
                   14123:     my ($symb,$uname,$udom,$caller) = @_;
                   14124:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14125:     my $turnindir;
                   14126:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14127:     $turnindir = $userhash{'turnindir'};
                   14128:     my ($path,$multiresp);
                   14129:     if ($turnindir eq '') {
                   14130:         if ($caller eq 'submission') {
                   14131:             $turnindir = &mt('turned in');
                   14132:             $turnindir =~ s/\W+/_/g;
                   14133:             my %newhash = (
                   14134:                             'turnindir' => $turnindir,
                   14135:                           );
                   14136:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14137:         }
                   14138:     }
                   14139:     if ($turnindir ne '') {
                   14140:         $path = '/'.$turnindir.'/';
                   14141:         my ($multipart,$turnin,@pathitems);
                   14142:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14143:         if (defined($navmap)) {
                   14144:             my $mapres = $navmap->getResourceByUrl($map);
                   14145:             if (ref($mapres)) {
                   14146:                 my $pcslist = $mapres->map_hierarchy();
                   14147:                 if ($pcslist ne '') {
                   14148:                     foreach my $pc (split(/,/,$pcslist)) {
                   14149:                         my $res = $navmap->getByMapPc($pc);
                   14150:                         if (ref($res)) {
                   14151:                             my $title = $res->compTitle();
                   14152:                             $title =~ s/\W+/_/g;
                   14153:                             if ($title ne '') {
1.1075.2.48  raeburn  14154:                                 if (($pc > 1) && (length($title) > 12)) {
                   14155:                                     $title = substr($title,0,12);
                   14156:                                 }
1.1015    raeburn  14157:                                 push(@pathitems,$title);
                   14158:                             }
                   14159:                         }
                   14160:                     }
                   14161:                 }
                   14162:                 my $maptitle = $mapres->compTitle();
                   14163:                 $maptitle =~ s/\W+/_/g;
                   14164:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14165:                     if (length($maptitle) > 12) {
                   14166:                         $maptitle = substr($maptitle,0,12);
                   14167:                     }
1.1015    raeburn  14168:                     push(@pathitems,$maptitle);
                   14169:                 }
                   14170:                 unless ($env{'request.state'} eq 'construct') {
                   14171:                     my $res = $navmap->getBySymb($symb);
                   14172:                     if (ref($res)) {
                   14173:                         my $partlist = $res->parts();
                   14174:                         my $totaluploads = 0;
                   14175:                         if (ref($partlist) eq 'ARRAY') {
                   14176:                             foreach my $part (@{$partlist}) {
                   14177:                                 my @types = $res->responseType($part);
                   14178:                                 my @ids = $res->responseIds($part);
                   14179:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14180:                                     if ($types[$i] eq 'essay') {
                   14181:                                         my $partid = $part.'_'.$ids[$i];
                   14182:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14183:                                             $totaluploads ++;
                   14184:                                         }
                   14185:                                     }
                   14186:                                 }
                   14187:                             }
                   14188:                             if ($totaluploads > 1) {
                   14189:                                 $multiresp = 1;
                   14190:                             }
                   14191:                         }
                   14192:                     }
                   14193:                 }
                   14194:             } else {
                   14195:                 return;
                   14196:             }
                   14197:         } else {
                   14198:             return;
                   14199:         }
                   14200:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14201:         $restitle =~ s/\W+/_/g;
                   14202:         if ($restitle eq '') {
                   14203:             $restitle = ($resurl =~ m{/[^/]+$});
                   14204:             if ($restitle eq '') {
                   14205:                 $restitle = time;
                   14206:             }
                   14207:         }
1.1075.2.48  raeburn  14208:         if (length($restitle) > 12) {
                   14209:             $restitle = substr($restitle,0,12);
                   14210:         }
1.1015    raeburn  14211:         push(@pathitems,$restitle);
                   14212:         $path .= join('/',@pathitems);
                   14213:     }
                   14214:     return ($path,$multiresp);
                   14215: }
                   14216: 
                   14217: =pod
                   14218: 
1.464     albertel 14219: =back
1.41      ng       14220: 
1.112     bowersj2 14221: =head1 CSV Upload/Handling functions
1.38      albertel 14222: 
1.41      ng       14223: =over 4
                   14224: 
1.648     raeburn  14225: =item * &upfile_store($r)
1.41      ng       14226: 
                   14227: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14228: needs $env{'form.upfile'}
1.41      ng       14229: returns $datatoken to be put into hidden field
                   14230: 
                   14231: =cut
1.31      albertel 14232: 
                   14233: sub upfile_store {
                   14234:     my $r=shift;
1.258     albertel 14235:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14236:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14237:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14238:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14239: 
1.1075.2.128  raeburn  14240:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14241:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14242:                                      time.'_'.$$);
                   14243:     return if ($datatoken eq '');
                   14244: 
1.31      albertel 14245:     {
1.158     raeburn  14246:         my $datafile = $r->dir_config('lonDaemons').
                   14247:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14248:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14249:             print $fh $env{'form.upfile'};
1.158     raeburn  14250:             close($fh);
                   14251:         }
1.31      albertel 14252:     }
                   14253:     return $datatoken;
                   14254: }
                   14255: 
1.56      matthew  14256: =pod
                   14257: 
1.1075.2.128  raeburn  14258: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14259: 
                   14260: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14261: $datatoken is the name to assign to the temporary file.
1.258     albertel 14262: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14263: 
                   14264: =cut
1.31      albertel 14265: 
                   14266: sub load_tmp_file {
1.1075.2.128  raeburn  14267:     my ($r,$datatoken) = @_;
                   14268:     return if ($datatoken eq '');
1.31      albertel 14269:     my @studentdata=();
                   14270:     {
1.158     raeburn  14271:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14272:                               '/tmp/'.$datatoken.'.tmp';
                   14273:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14274:             @studentdata=<$fh>;
                   14275:             close($fh);
                   14276:         }
1.31      albertel 14277:     }
1.258     albertel 14278:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14279: }
                   14280: 
1.1075.2.128  raeburn  14281: sub valid_datatoken {
                   14282:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14283:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14284:         return $datatoken;
                   14285:     }
                   14286:     return;
                   14287: }
                   14288: 
1.56      matthew  14289: =pod
                   14290: 
1.648     raeburn  14291: =item * &upfile_record_sep()
1.41      ng       14292: 
                   14293: Separate uploaded file into records
                   14294: returns array of records,
1.258     albertel 14295: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14296: 
                   14297: =cut
1.31      albertel 14298: 
                   14299: sub upfile_record_sep {
1.258     albertel 14300:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14301:     } else {
1.248     albertel 14302: 	my @records;
1.258     albertel 14303: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14304: 	    if ($line=~/^\s*$/) { next; }
                   14305: 	    push(@records,$line);
                   14306: 	}
                   14307: 	return @records;
1.31      albertel 14308:     }
                   14309: }
                   14310: 
1.56      matthew  14311: =pod
                   14312: 
1.648     raeburn  14313: =item * &record_sep($record)
1.41      ng       14314: 
1.258     albertel 14315: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14316: 
                   14317: =cut
                   14318: 
1.263     www      14319: sub takeleft {
                   14320:     my $index=shift;
                   14321:     return substr('0000'.$index,-4,4);
                   14322: }
                   14323: 
1.31      albertel 14324: sub record_sep {
                   14325:     my $record=shift;
                   14326:     my %components=();
1.258     albertel 14327:     if ($env{'form.upfiletype'} eq 'xml') {
                   14328:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14329:         my $i=0;
1.356     albertel 14330:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14331:             $field=~s/^(\"|\')//;
                   14332:             $field=~s/(\"|\')$//;
1.263     www      14333:             $components{&takeleft($i)}=$field;
1.31      albertel 14334:             $i++;
                   14335:         }
1.258     albertel 14336:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14337:         my $i=0;
1.356     albertel 14338:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14339:             $field=~s/^(\"|\')//;
                   14340:             $field=~s/(\"|\')$//;
1.263     www      14341:             $components{&takeleft($i)}=$field;
1.31      albertel 14342:             $i++;
                   14343:         }
                   14344:     } else {
1.561     www      14345:         my $separator=',';
1.480     banghart 14346:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14347:             $separator=';';
1.480     banghart 14348:         }
1.31      albertel 14349:         my $i=0;
1.561     www      14350: # the character we are looking for to indicate the end of a quote or a record 
                   14351:         my $looking_for=$separator;
                   14352: # do not add the characters to the fields
                   14353:         my $ignore=0;
                   14354: # we just encountered a separator (or the beginning of the record)
                   14355:         my $just_found_separator=1;
                   14356: # store the field we are working on here
                   14357:         my $field='';
                   14358: # work our way through all characters in record
                   14359:         foreach my $character ($record=~/(.)/g) {
                   14360:             if ($character eq $looking_for) {
                   14361:                if ($character ne $separator) {
                   14362: # Found the end of a quote, again looking for separator
                   14363:                   $looking_for=$separator;
                   14364:                   $ignore=1;
                   14365:                } else {
                   14366: # Found a separator, store away what we got
                   14367:                   $components{&takeleft($i)}=$field;
                   14368: 	          $i++;
                   14369:                   $just_found_separator=1;
                   14370:                   $ignore=0;
                   14371:                   $field='';
                   14372:                }
                   14373:                next;
                   14374:             }
                   14375: # single or double quotation marks after a separator indicate beginning of a quote
                   14376: # we are now looking for the end of the quote and need to ignore separators
                   14377:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14378:                $looking_for=$character;
                   14379:                next;
                   14380:             }
                   14381: # ignore would be true after we reached the end of a quote
                   14382:             if ($ignore) { next; }
                   14383:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14384:             $field.=$character;
                   14385:             $just_found_separator=0; 
1.31      albertel 14386:         }
1.561     www      14387: # catch the very last entry, since we never encountered the separator
                   14388:         $components{&takeleft($i)}=$field;
1.31      albertel 14389:     }
                   14390:     return %components;
                   14391: }
                   14392: 
1.144     matthew  14393: ######################################################
                   14394: ######################################################
                   14395: 
1.56      matthew  14396: =pod
                   14397: 
1.648     raeburn  14398: =item * &upfile_select_html()
1.41      ng       14399: 
1.144     matthew  14400: Return HTML code to select a file from the users machine and specify 
                   14401: the file type.
1.41      ng       14402: 
                   14403: =cut
                   14404: 
1.144     matthew  14405: ######################################################
                   14406: ######################################################
1.31      albertel 14407: sub upfile_select_html {
1.144     matthew  14408:     my %Types = (
                   14409:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14410:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14411:                  space => &mt('Space separated'),
                   14412:                  tab   => &mt('Tabulator separated'),
                   14413: #                 xml   => &mt('HTML/XML'),
                   14414:                  );
                   14415:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14416:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14417:     foreach my $type (sort(keys(%Types))) {
                   14418:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14419:     }
                   14420:     $Str .= "</select>\n";
                   14421:     return $Str;
1.31      albertel 14422: }
                   14423: 
1.301     albertel 14424: sub get_samples {
                   14425:     my ($records,$toget) = @_;
                   14426:     my @samples=({});
                   14427:     my $got=0;
                   14428:     foreach my $rec (@$records) {
                   14429: 	my %temp = &record_sep($rec);
                   14430: 	if (! grep(/\S/, values(%temp))) { next; }
                   14431: 	if (%temp) {
                   14432: 	    $samples[$got]=\%temp;
                   14433: 	    $got++;
                   14434: 	    if ($got == $toget) { last; }
                   14435: 	}
                   14436:     }
                   14437:     return \@samples;
                   14438: }
                   14439: 
1.144     matthew  14440: ######################################################
                   14441: ######################################################
                   14442: 
1.56      matthew  14443: =pod
                   14444: 
1.648     raeburn  14445: =item * &csv_print_samples($r,$records)
1.41      ng       14446: 
                   14447: Prints a table of sample values from each column uploaded $r is an
                   14448: Apache Request ref, $records is an arrayref from
                   14449: &Apache::loncommon::upfile_record_sep
                   14450: 
                   14451: =cut
                   14452: 
1.144     matthew  14453: ######################################################
                   14454: ######################################################
1.31      albertel 14455: sub csv_print_samples {
                   14456:     my ($r,$records) = @_;
1.662     bisitz   14457:     my $samples = &get_samples($records,5);
1.301     albertel 14458: 
1.594     raeburn  14459:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14460:               &start_data_table_header_row());
1.356     albertel 14461:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14462:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14463:     $r->print(&end_data_table_header_row());
1.301     albertel 14464:     foreach my $hash (@$samples) {
1.594     raeburn  14465: 	$r->print(&start_data_table_row());
1.356     albertel 14466: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14467: 	    $r->print('<td>');
1.356     albertel 14468: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14469: 	    $r->print('</td>');
                   14470: 	}
1.594     raeburn  14471: 	$r->print(&end_data_table_row());
1.31      albertel 14472:     }
1.594     raeburn  14473:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14474: }
                   14475: 
1.144     matthew  14476: ######################################################
                   14477: ######################################################
                   14478: 
1.56      matthew  14479: =pod
                   14480: 
1.648     raeburn  14481: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14482: 
                   14483: Prints a table to create associations between values and table columns.
1.144     matthew  14484: 
1.41      ng       14485: $r is an Apache Request ref,
                   14486: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14487: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14488: 
                   14489: =cut
                   14490: 
1.144     matthew  14491: ######################################################
                   14492: ######################################################
1.31      albertel 14493: sub csv_print_select_table {
                   14494:     my ($r,$records,$d) = @_;
1.301     albertel 14495:     my $i=0;
                   14496:     my $samples = &get_samples($records,1);
1.144     matthew  14497:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14498: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14499:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14500:               '<th>'.&mt('Column').'</th>'.
                   14501:               &end_data_table_header_row()."\n");
1.356     albertel 14502:     foreach my $array_ref (@$d) {
                   14503: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14504: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14505: 
1.875     bisitz   14506: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14507: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14508: 	$r->print('<option value="none"></option>');
1.356     albertel 14509: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14510: 	    $r->print('<option value="'.$sample.'"'.
                   14511:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14512:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14513: 	}
1.594     raeburn  14514: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14515: 	$i++;
                   14516:     }
1.594     raeburn  14517:     $r->print(&end_data_table());
1.31      albertel 14518:     $i--;
                   14519:     return $i;
                   14520: }
1.56      matthew  14521: 
1.144     matthew  14522: ######################################################
                   14523: ######################################################
                   14524: 
1.56      matthew  14525: =pod
1.31      albertel 14526: 
1.648     raeburn  14527: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14528: 
                   14529: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14530: 
                   14531: $r is an Apache Request ref,
                   14532: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14533: $d is an array of 2 element arrays (internal name, displayed name)
                   14534: 
                   14535: =cut
                   14536: 
1.144     matthew  14537: ######################################################
                   14538: ######################################################
1.31      albertel 14539: sub csv_samples_select_table {
                   14540:     my ($r,$records,$d) = @_;
                   14541:     my $i=0;
1.144     matthew  14542:     #
1.662     bisitz   14543:     my $max_samples = 5;
                   14544:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14545:     $r->print(&start_data_table().
                   14546:               &start_data_table_header_row().'<th>'.
                   14547:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14548:               &end_data_table_header_row());
1.301     albertel 14549: 
                   14550:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14551: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14552: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14553: 	foreach my $option (@$d) {
                   14554: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14555: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14556:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14557:                       $display.'</option>');
1.31      albertel 14558: 	}
                   14559: 	$r->print('</select></td><td>');
1.662     bisitz   14560: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14561: 	    if (defined($samples->[$line]{$key})) { 
                   14562: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14563: 	    }
                   14564: 	}
1.594     raeburn  14565: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14566: 	$i++;
                   14567:     }
1.594     raeburn  14568:     $r->print(&end_data_table());
1.31      albertel 14569:     $i--;
                   14570:     return($i);
1.115     matthew  14571: }
                   14572: 
1.144     matthew  14573: ######################################################
                   14574: ######################################################
                   14575: 
1.115     matthew  14576: =pod
                   14577: 
1.648     raeburn  14578: =item * &clean_excel_name($name)
1.115     matthew  14579: 
                   14580: Returns a replacement for $name which does not contain any illegal characters.
                   14581: 
                   14582: =cut
                   14583: 
1.144     matthew  14584: ######################################################
                   14585: ######################################################
1.115     matthew  14586: sub clean_excel_name {
                   14587:     my ($name) = @_;
                   14588:     $name =~ s/[:\*\?\/\\]//g;
                   14589:     if (length($name) > 31) {
                   14590:         $name = substr($name,0,31);
                   14591:     }
                   14592:     return $name;
1.25      albertel 14593: }
1.84      albertel 14594: 
1.85      albertel 14595: =pod
                   14596: 
1.648     raeburn  14597: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14598: 
                   14599: Returns either 1 or undef
                   14600: 
                   14601: 1 if the part is to be hidden, undef if it is to be shown
                   14602: 
                   14603: Arguments are:
                   14604: 
                   14605: $id the id of the part to be checked
                   14606: $symb, optional the symb of the resource to check
                   14607: $udom, optional the domain of the user to check for
                   14608: $uname, optional the username of the user to check for
                   14609: 
                   14610: =cut
1.84      albertel 14611: 
                   14612: sub check_if_partid_hidden {
                   14613:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14614:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14615: 					 $symb,$udom,$uname);
1.141     albertel 14616:     my $truth=1;
                   14617:     #if the string starts with !, then the list is the list to show not hide
                   14618:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14619:     my @hiddenlist=split(/,/,$hiddenparts);
                   14620:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14621: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14622:     }
1.141     albertel 14623:     return !$truth;
1.84      albertel 14624: }
1.127     matthew  14625: 
1.138     matthew  14626: 
                   14627: ############################################################
                   14628: ############################################################
                   14629: 
                   14630: =pod
                   14631: 
1.157     matthew  14632: =back 
                   14633: 
1.138     matthew  14634: =head1 cgi-bin script and graphing routines
                   14635: 
1.157     matthew  14636: =over 4
                   14637: 
1.648     raeburn  14638: =item * &get_cgi_id()
1.138     matthew  14639: 
                   14640: Inputs: none
                   14641: 
                   14642: Returns an id which can be used to pass environment variables
                   14643: to various cgi-bin scripts.  These environment variables will
                   14644: be removed from the users environment after a given time by
                   14645: the routine &Apache::lonnet::transfer_profile_to_env.
                   14646: 
                   14647: =cut
                   14648: 
                   14649: ############################################################
                   14650: ############################################################
1.152     albertel 14651: my $uniq=0;
1.136     matthew  14652: sub get_cgi_id {
1.154     albertel 14653:     $uniq=($uniq+1)%100000;
1.280     albertel 14654:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14655: }
                   14656: 
1.127     matthew  14657: ############################################################
                   14658: ############################################################
                   14659: 
                   14660: =pod
                   14661: 
1.648     raeburn  14662: =item * &DrawBarGraph()
1.127     matthew  14663: 
1.138     matthew  14664: Facilitates the plotting of data in a (stacked) bar graph.
                   14665: Puts plot definition data into the users environment in order for 
                   14666: graph.png to plot it.  Returns an <img> tag for the plot.
                   14667: The bars on the plot are labeled '1','2',...,'n'.
                   14668: 
                   14669: Inputs:
                   14670: 
                   14671: =over 4
                   14672: 
                   14673: =item $Title: string, the title of the plot
                   14674: 
                   14675: =item $xlabel: string, text describing the X-axis of the plot
                   14676: 
                   14677: =item $ylabel: string, text describing the Y-axis of the plot
                   14678: 
                   14679: =item $Max: scalar, the maximum Y value to use in the plot
                   14680: If $Max is < any data point, the graph will not be rendered.
                   14681: 
1.140     matthew  14682: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14683: they are plotted.  If undefined, default values will be used.
                   14684: 
1.178     matthew  14685: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14686: 
1.138     matthew  14687: =item @Values: An array of array references.  Each array reference holds data
                   14688: to be plotted in a stacked bar chart.
                   14689: 
1.239     matthew  14690: =item If the final element of @Values is a hash reference the key/value
                   14691: pairs will be added to the graph definition.
                   14692: 
1.138     matthew  14693: =back
                   14694: 
                   14695: Returns:
                   14696: 
                   14697: An <img> tag which references graph.png and the appropriate identifying
                   14698: information for the plot.
                   14699: 
1.127     matthew  14700: =cut
                   14701: 
                   14702: ############################################################
                   14703: ############################################################
1.134     matthew  14704: sub DrawBarGraph {
1.178     matthew  14705:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14706:     #
                   14707:     if (! defined($colors)) {
                   14708:         $colors = ['#33ff00', 
                   14709:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14710:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14711:                   ]; 
                   14712:     }
1.228     matthew  14713:     my $extra_settings = {};
                   14714:     if (ref($Values[-1]) eq 'HASH') {
                   14715:         $extra_settings = pop(@Values);
                   14716:     }
1.127     matthew  14717:     #
1.136     matthew  14718:     my $identifier = &get_cgi_id();
                   14719:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14720:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14721:         return '';
                   14722:     }
1.225     matthew  14723:     #
                   14724:     my @Labels;
                   14725:     if (defined($labels)) {
                   14726:         @Labels = @$labels;
                   14727:     } else {
                   14728:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  14729:             push(@Labels,$i+1);
1.225     matthew  14730:         }
                   14731:     }
                   14732:     #
1.129     matthew  14733:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14734:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14735:     my %ValuesHash;
                   14736:     my $NumSets=1;
                   14737:     foreach my $array (@Values) {
                   14738:         next if (! ref($array));
1.136     matthew  14739:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14740:             join(',',@$array);
1.129     matthew  14741:     }
1.127     matthew  14742:     #
1.136     matthew  14743:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14744:     if ($NumBars < 3) {
                   14745:         $width = 120+$NumBars*32;
1.220     matthew  14746:         $xskip = 1;
1.225     matthew  14747:         $bar_width = 30;
                   14748:     } elsif ($NumBars < 5) {
                   14749:         $width = 120+$NumBars*20;
                   14750:         $xskip = 1;
                   14751:         $bar_width = 20;
1.220     matthew  14752:     } elsif ($NumBars < 10) {
1.136     matthew  14753:         $width = 120+$NumBars*15;
                   14754:         $xskip = 1;
                   14755:         $bar_width = 15;
                   14756:     } elsif ($NumBars <= 25) {
                   14757:         $width = 120+$NumBars*11;
                   14758:         $xskip = 5;
                   14759:         $bar_width = 8;
                   14760:     } elsif ($NumBars <= 50) {
                   14761:         $width = 120+$NumBars*8;
                   14762:         $xskip = 5;
                   14763:         $bar_width = 4;
                   14764:     } else {
                   14765:         $width = 120+$NumBars*8;
                   14766:         $xskip = 5;
                   14767:         $bar_width = 4;
                   14768:     }
                   14769:     #
1.137     matthew  14770:     $Max = 1 if ($Max < 1);
                   14771:     if ( int($Max) < $Max ) {
                   14772:         $Max++;
                   14773:         $Max = int($Max);
                   14774:     }
1.127     matthew  14775:     $Title  = '' if (! defined($Title));
                   14776:     $xlabel = '' if (! defined($xlabel));
                   14777:     $ylabel = '' if (! defined($ylabel));
1.369     www      14778:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14779:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14780:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14781:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14782:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14783:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14784:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14785:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14786:     $ValuesHash{$id.'.height'}   = $height;
                   14787:     $ValuesHash{$id.'.width'}    = $width;
                   14788:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14789:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14790:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14791:     #
1.228     matthew  14792:     # Deal with other parameters
                   14793:     while (my ($key,$value) = each(%$extra_settings)) {
                   14794:         $ValuesHash{$id.'.'.$key} = $value;
                   14795:     }
                   14796:     #
1.646     raeburn  14797:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14798:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14799: }
                   14800: 
                   14801: ############################################################
                   14802: ############################################################
                   14803: 
                   14804: =pod
                   14805: 
1.648     raeburn  14806: =item * &DrawXYGraph()
1.137     matthew  14807: 
1.138     matthew  14808: Facilitates the plotting of data in an XY graph.
                   14809: Puts plot definition data into the users environment in order for 
                   14810: graph.png to plot it.  Returns an <img> tag for the plot.
                   14811: 
                   14812: Inputs:
                   14813: 
                   14814: =over 4
                   14815: 
                   14816: =item $Title: string, the title of the plot
                   14817: 
                   14818: =item $xlabel: string, text describing the X-axis of the plot
                   14819: 
                   14820: =item $ylabel: string, text describing the Y-axis of the plot
                   14821: 
                   14822: =item $Max: scalar, the maximum Y value to use in the plot
                   14823: If $Max is < any data point, the graph will not be rendered.
                   14824: 
                   14825: =item $colors: Array ref containing the hex color codes for the data to be 
                   14826: plotted in.  If undefined, default values will be used.
                   14827: 
                   14828: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14829: 
                   14830: =item $Ydata: Array ref containing Array refs.  
1.185     www      14831: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14832: 
                   14833: =item %Values: hash indicating or overriding any default values which are 
                   14834: passed to graph.png.  
                   14835: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14836: 
                   14837: =back
                   14838: 
                   14839: Returns:
                   14840: 
                   14841: An <img> tag which references graph.png and the appropriate identifying
                   14842: information for the plot.
                   14843: 
1.137     matthew  14844: =cut
                   14845: 
                   14846: ############################################################
                   14847: ############################################################
                   14848: sub DrawXYGraph {
                   14849:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14850:     #
                   14851:     # Create the identifier for the graph
                   14852:     my $identifier = &get_cgi_id();
                   14853:     my $id = 'cgi.'.$identifier;
                   14854:     #
                   14855:     $Title  = '' if (! defined($Title));
                   14856:     $xlabel = '' if (! defined($xlabel));
                   14857:     $ylabel = '' if (! defined($ylabel));
                   14858:     my %ValuesHash = 
                   14859:         (
1.369     www      14860:          $id.'.title'  => &escape($Title),
                   14861:          $id.'.xlabel' => &escape($xlabel),
                   14862:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14863:          $id.'.y_max_value'=> $Max,
                   14864:          $id.'.labels'     => join(',',@$Xlabels),
                   14865:          $id.'.PlotType'   => 'XY',
                   14866:          );
                   14867:     #
                   14868:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14869:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14870:     }
                   14871:     #
                   14872:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14873:         return '';
                   14874:     }
                   14875:     my $NumSets=1;
1.138     matthew  14876:     foreach my $array (@{$Ydata}){
1.137     matthew  14877:         next if (! ref($array));
                   14878:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14879:     }
1.138     matthew  14880:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14881:     #
                   14882:     # Deal with other parameters
                   14883:     while (my ($key,$value) = each(%Values)) {
                   14884:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14885:     }
                   14886:     #
1.646     raeburn  14887:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14888:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14889: }
                   14890: 
                   14891: ############################################################
                   14892: ############################################################
                   14893: 
                   14894: =pod
                   14895: 
1.648     raeburn  14896: =item * &DrawXYYGraph()
1.138     matthew  14897: 
                   14898: Facilitates the plotting of data in an XY graph with two Y axes.
                   14899: Puts plot definition data into the users environment in order for 
                   14900: graph.png to plot it.  Returns an <img> tag for the plot.
                   14901: 
                   14902: Inputs:
                   14903: 
                   14904: =over 4
                   14905: 
                   14906: =item $Title: string, the title of the plot
                   14907: 
                   14908: =item $xlabel: string, text describing the X-axis of the plot
                   14909: 
                   14910: =item $ylabel: string, text describing the Y-axis of the plot
                   14911: 
                   14912: =item $colors: Array ref containing the hex color codes for the data to be 
                   14913: plotted in.  If undefined, default values will be used.
                   14914: 
                   14915: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14916: 
                   14917: =item $Ydata1: The first data set
                   14918: 
                   14919: =item $Min1: The minimum value of the left Y-axis
                   14920: 
                   14921: =item $Max1: The maximum value of the left Y-axis
                   14922: 
                   14923: =item $Ydata2: The second data set
                   14924: 
                   14925: =item $Min2: The minimum value of the right Y-axis
                   14926: 
                   14927: =item $Max2: The maximum value of the left Y-axis
                   14928: 
                   14929: =item %Values: hash indicating or overriding any default values which are 
                   14930: passed to graph.png.  
                   14931: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14932: 
                   14933: =back
                   14934: 
                   14935: Returns:
                   14936: 
                   14937: An <img> tag which references graph.png and the appropriate identifying
                   14938: information for the plot.
1.136     matthew  14939: 
                   14940: =cut
                   14941: 
                   14942: ############################################################
                   14943: ############################################################
1.137     matthew  14944: sub DrawXYYGraph {
                   14945:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14946:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14947:     #
                   14948:     # Create the identifier for the graph
                   14949:     my $identifier = &get_cgi_id();
                   14950:     my $id = 'cgi.'.$identifier;
                   14951:     #
                   14952:     $Title  = '' if (! defined($Title));
                   14953:     $xlabel = '' if (! defined($xlabel));
                   14954:     $ylabel = '' if (! defined($ylabel));
                   14955:     my %ValuesHash = 
                   14956:         (
1.369     www      14957:          $id.'.title'  => &escape($Title),
                   14958:          $id.'.xlabel' => &escape($xlabel),
                   14959:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14960:          $id.'.labels' => join(',',@$Xlabels),
                   14961:          $id.'.PlotType' => 'XY',
                   14962:          $id.'.NumSets' => 2,
1.137     matthew  14963:          $id.'.two_axes' => 1,
                   14964:          $id.'.y1_max_value' => $Max1,
                   14965:          $id.'.y1_min_value' => $Min1,
                   14966:          $id.'.y2_max_value' => $Max2,
                   14967:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14968:          );
                   14969:     #
1.137     matthew  14970:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14971:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14972:     }
                   14973:     #
                   14974:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14975:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14976:         return '';
                   14977:     }
                   14978:     my $NumSets=1;
1.137     matthew  14979:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14980:         next if (! ref($array));
                   14981:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14982:     }
                   14983:     #
                   14984:     # Deal with other parameters
                   14985:     while (my ($key,$value) = each(%Values)) {
                   14986:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14987:     }
                   14988:     #
1.646     raeburn  14989:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14990:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14991: }
                   14992: 
                   14993: ############################################################
                   14994: ############################################################
                   14995: 
                   14996: =pod
                   14997: 
1.157     matthew  14998: =back 
                   14999: 
1.139     matthew  15000: =head1 Statistics helper routines?  
                   15001: 
                   15002: Bad place for them but what the hell.
                   15003: 
1.157     matthew  15004: =over 4
                   15005: 
1.648     raeburn  15006: =item * &chartlink()
1.139     matthew  15007: 
                   15008: Returns a link to the chart for a specific student.  
                   15009: 
                   15010: Inputs:
                   15011: 
                   15012: =over 4
                   15013: 
                   15014: =item $linktext: The text of the link
                   15015: 
                   15016: =item $sname: The students username
                   15017: 
                   15018: =item $sdomain: The students domain
                   15019: 
                   15020: =back
                   15021: 
1.157     matthew  15022: =back
                   15023: 
1.139     matthew  15024: =cut
                   15025: 
                   15026: ############################################################
                   15027: ############################################################
                   15028: sub chartlink {
                   15029:     my ($linktext, $sname, $sdomain) = @_;
                   15030:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15031:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15032:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15033:        '">'.$linktext.'</a>';
1.153     matthew  15034: }
                   15035: 
                   15036: #######################################################
                   15037: #######################################################
                   15038: 
                   15039: =pod
                   15040: 
                   15041: =head1 Course Environment Routines
1.157     matthew  15042: 
                   15043: =over 4
1.153     matthew  15044: 
1.648     raeburn  15045: =item * &restore_course_settings()
1.153     matthew  15046: 
1.648     raeburn  15047: =item * &store_course_settings()
1.153     matthew  15048: 
                   15049: Restores/Store indicated form parameters from the course environment.
                   15050: Will not overwrite existing values of the form parameters.
                   15051: 
                   15052: Inputs: 
                   15053: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15054: 
                   15055: a hash ref describing the data to be stored.  For example:
                   15056:    
                   15057: %Save_Parameters = ('Status' => 'scalar',
                   15058:     'chartoutputmode' => 'scalar',
                   15059:     'chartoutputdata' => 'scalar',
                   15060:     'Section' => 'array',
1.373     raeburn  15061:     'Group' => 'array',
1.153     matthew  15062:     'StudentData' => 'array',
                   15063:     'Maps' => 'array');
                   15064: 
                   15065: Returns: both routines return nothing
                   15066: 
1.631     raeburn  15067: =back
                   15068: 
1.153     matthew  15069: =cut
                   15070: 
                   15071: #######################################################
                   15072: #######################################################
                   15073: sub store_course_settings {
1.496     albertel 15074:     return &store_settings($env{'request.course.id'},@_);
                   15075: }
                   15076: 
                   15077: sub store_settings {
1.153     matthew  15078:     # save to the environment
                   15079:     # appenv the same items, just to be safe
1.300     albertel 15080:     my $udom  = $env{'user.domain'};
                   15081:     my $uname = $env{'user.name'};
1.496     albertel 15082:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15083:     my %SaveHash;
                   15084:     my %AppHash;
                   15085:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15086:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15087:         my $envname = 'environment.'.$basename;
1.258     albertel 15088:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15089:             # Save this value away
                   15090:             if ($type eq 'scalar' &&
1.258     albertel 15091:                 (! exists($env{$envname}) || 
                   15092:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15093:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15094:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15095:             } elsif ($type eq 'array') {
                   15096:                 my $stored_form;
1.258     albertel 15097:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15098:                     $stored_form = join(',',
                   15099:                                         map {
1.369     www      15100:                                             &escape($_);
1.258     albertel 15101:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15102:                 } else {
                   15103:                     $stored_form = 
1.369     www      15104:                         &escape($env{'form.'.$setting});
1.153     matthew  15105:                 }
                   15106:                 # Determine if the array contents are the same.
1.258     albertel 15107:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15108:                     $SaveHash{$basename} = $stored_form;
                   15109:                     $AppHash{$envname}   = $stored_form;
                   15110:                 }
                   15111:             }
                   15112:         }
                   15113:     }
                   15114:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15115:                                           $udom,$uname);
1.153     matthew  15116:     if ($put_result !~ /^(ok|delayed)/) {
                   15117:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15118:                                  'got error:'.$put_result);
                   15119:     }
                   15120:     # Make sure these settings stick around in this session, too
1.646     raeburn  15121:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15122:     return;
                   15123: }
                   15124: 
                   15125: sub restore_course_settings {
1.499     albertel 15126:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15127: }
                   15128: 
                   15129: sub restore_settings {
                   15130:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15131:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15132:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15133:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15134:             '.'.$setting;
1.258     albertel 15135:         if (exists($env{$envname})) {
1.153     matthew  15136:             if ($type eq 'scalar') {
1.258     albertel 15137:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15138:             } elsif ($type eq 'array') {
1.258     albertel 15139:                 $env{'form.'.$setting} = [ 
1.153     matthew  15140:                                            map { 
1.369     www      15141:                                                &unescape($_); 
1.258     albertel 15142:                                            } split(',',$env{$envname})
1.153     matthew  15143:                                            ];
                   15144:             }
                   15145:         }
                   15146:     }
1.127     matthew  15147: }
                   15148: 
1.618     raeburn  15149: #######################################################
                   15150: #######################################################
                   15151: 
                   15152: =pod
                   15153: 
                   15154: =head1 Domain E-mail Routines  
                   15155: 
                   15156: =over 4
                   15157: 
1.648     raeburn  15158: =item * &build_recipient_list()
1.618     raeburn  15159: 
1.1075.2.44  raeburn  15160: Build recipient lists for following types of e-mail:
1.766     raeburn  15161: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15162: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15163: module change checking, student/employee ID conflict checks, as
                   15164: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15165: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15166: 
                   15167: Inputs:
1.1075.2.44  raeburn  15168: defmail (scalar - email address of default recipient),
                   15169: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15170: requestsmail, updatesmail, or idconflictsmail).
                   15171: 
1.619     raeburn  15172: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15173: 
                   15174: origmail (scalar - email address of recipient from loncapa.conf,
                   15175: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15176: 
1.1075.2.139  raeburn  15177: $requname username of requester (if mailing type is helpdeskmail)
                   15178: 
                   15179: $requdom domain of requester (if mailing type is helpdeskmail)
                   15180: 
                   15181: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15182: 
1.655     raeburn  15183: Returns: comma separated list of addresses to which to send e-mail.
                   15184: 
                   15185: =back
1.618     raeburn  15186: 
                   15187: =cut
                   15188: 
                   15189: ############################################################
                   15190: ############################################################
                   15191: sub build_recipient_list {
1.1075.2.139  raeburn  15192:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15193:     my @recipients;
1.1075.2.122  raeburn  15194:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15195:     my %domconfig =
1.1075.2.122  raeburn  15196:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15197:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15198:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15199:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15200:                 my @contacts = ('adminemail','supportemail');
                   15201:                 foreach my $item (@contacts) {
                   15202:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15203:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15204:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15205:                             push(@recipients,$addr);
                   15206:                         }
1.619     raeburn  15207:                     }
1.1075.2.122  raeburn  15208:                 }
                   15209:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15210:                 if ($mailing eq 'helpdeskmail') {
                   15211:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15212:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15213:                         my @ok_bccs;
                   15214:                         foreach my $bcc (@bccs) {
                   15215:                             $bcc =~ s/^\s+//g;
                   15216:                             $bcc =~ s/\s+$//g;
                   15217:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15218:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15219:                                     push(@ok_bccs,$bcc);
                   15220:                                 }
                   15221:                             }
                   15222:                         }
                   15223:                         if (@ok_bccs > 0) {
                   15224:                             $allbcc = join(', ',@ok_bccs);
                   15225:                         }
                   15226:                     }
                   15227:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15228:                 }
                   15229:             }
1.766     raeburn  15230:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15231:             $lastresort = $origmail;
1.618     raeburn  15232:         }
1.1075.2.139  raeburn  15233:         if ($mailing eq 'helpdeskmail') {
                   15234:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15235:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15236:                 my ($inststatus,$inststatus_checked);
                   15237:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15238:                     ($env{'user.domain'} ne 'public')) {
                   15239:                     $inststatus_checked = 1;
                   15240:                     $inststatus = $env{'environment.inststatus'};
                   15241:                 }
                   15242:                 unless ($inststatus_checked) {
                   15243:                     if (($requname ne '') && ($requdom ne '')) {
                   15244:                         if (($requname =~ /^$match_username$/) &&
                   15245:                             ($requdom =~ /^$match_domain$/) &&
                   15246:                             (&Apache::lonnet::domain($requdom))) {
                   15247:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15248:                                                                       $requdom);
                   15249:                             unless ($requhome eq 'no_host') {
                   15250:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15251:                                 $inststatus = $userenv{'inststatus'};
                   15252:                                 $inststatus_checked = 1;
                   15253:                             }
                   15254:                         }
                   15255:                     }
                   15256:                 }
                   15257:                 unless ($inststatus_checked) {
                   15258:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15259:                         my %srch = (srchby     => 'email',
                   15260:                                     srchdomain => $defdom,
                   15261:                                     srchterm   => $reqemail,
                   15262:                                     srchtype   => 'exact');
                   15263:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15264:                         foreach my $uname (keys(%srch_results)) {
                   15265:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15266:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15267:                                 $inststatus_checked = 1;
                   15268:                                 last;
                   15269:                             }
                   15270:                         }
                   15271:                         unless ($inststatus_checked) {
                   15272:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15273:                             if ($dirsrchres eq 'ok') {
                   15274:                                 foreach my $uname (keys(%srch_results)) {
                   15275:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15276:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15277:                                         $inststatus_checked = 1;
                   15278:                                         last;
                   15279:                                     }
                   15280:                                 }
                   15281:                             }
                   15282:                         }
                   15283:                     }
                   15284:                 }
                   15285:                 if ($inststatus ne '') {
                   15286:                     foreach my $status (split(/\:/,$inststatus)) {
                   15287:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15288:                             my @contacts = ('adminemail','supportemail');
                   15289:                             foreach my $item (@contacts) {
                   15290:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15291:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15292:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15293:                                         push(@recipients,$addr);
                   15294:                                     }
                   15295:                                 }
                   15296:                             }
                   15297:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15298:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15299:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15300:                                 my @ok_bccs;
                   15301:                                 foreach my $bcc (@bccs) {
                   15302:                                     $bcc =~ s/^\s+//g;
                   15303:                                     $bcc =~ s/\s+$//g;
                   15304:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15305:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15306:                                             push(@ok_bccs,$bcc);
                   15307:                                         }
                   15308:                                     }
                   15309:                                 }
                   15310:                                 if (@ok_bccs > 0) {
                   15311:                                     $allbcc = join(', ',@ok_bccs);
                   15312:                                 }
                   15313:                             }
                   15314:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15315:                             last;
                   15316:                         }
                   15317:                     }
                   15318:                 }
                   15319:             }
                   15320:         }
1.619     raeburn  15321:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15322:         $lastresort = $origmail;
                   15323:     }
1.1075.2.128  raeburn  15324:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15325:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15326:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15327:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15328:             my %what = (
                   15329:                           perlvar => 1,
                   15330:                        );
                   15331:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15332:             if ($primary) {
                   15333:                 my $gotaddr;
                   15334:                 my ($result,$returnhash) =
                   15335:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15336:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15337:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15338:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15339:                         $gotaddr = 1;
                   15340:                     }
                   15341:                 }
                   15342:                 unless ($gotaddr) {
                   15343:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15344:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15345:                     unless ($uintdom eq $intdom) {
                   15346:                         my %domconfig =
                   15347:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15348:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15349:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15350:                                 my @contacts = ('adminemail','supportemail');
                   15351:                                 foreach my $item (@contacts) {
                   15352:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15353:                                         my $addr = $domconfig{'contacts'}{$item};
                   15354:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15355:                                             push(@recipients,$addr);
                   15356:                                         }
                   15357:                                     }
                   15358:                                 }
                   15359:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15360:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15361:                                 }
                   15362:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15363:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15364:                                     my @ok_bccs;
                   15365:                                     foreach my $bcc (@bccs) {
                   15366:                                         $bcc =~ s/^\s+//g;
                   15367:                                         $bcc =~ s/\s+$//g;
                   15368:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15369:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15370:                                                 push(@ok_bccs,$bcc);
                   15371:                                             }
                   15372:                                         }
                   15373:                                     }
                   15374:                                     if (@ok_bccs > 0) {
                   15375:                                         $allbcc = join(', ',@ok_bccs);
                   15376:                                     }
                   15377:                                 }
                   15378:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15379:                             }
                   15380:                         }
                   15381:                     }
                   15382:                 }
                   15383:             }
                   15384:         }
1.618     raeburn  15385:     }
1.688     raeburn  15386:     if (defined($defmail)) {
                   15387:         if ($defmail ne '') {
                   15388:             push(@recipients,$defmail);
                   15389:         }
1.618     raeburn  15390:     }
                   15391:     if ($otheremails) {
1.619     raeburn  15392:         my @others;
                   15393:         if ($otheremails =~ /,/) {
                   15394:             @others = split(/,/,$otheremails);
1.618     raeburn  15395:         } else {
1.619     raeburn  15396:             push(@others,$otheremails);
                   15397:         }
                   15398:         foreach my $addr (@others) {
                   15399:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15400:                 push(@recipients,$addr);
                   15401:             }
1.618     raeburn  15402:         }
                   15403:     }
1.1075.2.128  raeburn  15404:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15405:         if ((!@recipients) && ($lastresort ne '')) {
                   15406:             push(@recipients,$lastresort);
                   15407:         }
                   15408:     } elsif ($lastresort ne '') {
                   15409:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15410:             push(@recipients,$lastresort);
                   15411:         }
                   15412:     }
                   15413:     my $recipientlist = join(',',@recipients);
                   15414:     if (wantarray) {
                   15415:         return ($recipientlist,$allbcc,$addtext);
                   15416:     } else {
                   15417:         return $recipientlist;
                   15418:     }
1.618     raeburn  15419: }
                   15420: 
1.127     matthew  15421: ############################################################
                   15422: ############################################################
1.154     albertel 15423: 
1.655     raeburn  15424: =pod
                   15425: 
                   15426: =head1 Course Catalog Routines
                   15427: 
                   15428: =over 4
                   15429: 
                   15430: =item * &gather_categories()
                   15431: 
                   15432: Converts category definitions - keys of categories hash stored in  
                   15433: coursecategories in configuration.db on the primary library server in a 
                   15434: domain - to an array.  Also generates javascript and idx hash used to 
                   15435: generate Domain Coordinator interface for editing Course Categories.
                   15436: 
                   15437: Inputs:
1.663     raeburn  15438: 
1.655     raeburn  15439: categories (reference to hash of category definitions).
1.663     raeburn  15440: 
1.655     raeburn  15441: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15442:       categories and subcategories).
1.663     raeburn  15443: 
1.655     raeburn  15444: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15445:       editing Course Categories).
1.663     raeburn  15446: 
1.655     raeburn  15447: jsarray (reference to array of categories used to create Javascript arrays for
                   15448:          Domain Coordinator interface for editing Course Categories).
                   15449: 
                   15450: Returns: nothing
                   15451: 
                   15452: Side effects: populates cats, idx and jsarray. 
                   15453: 
                   15454: =cut
                   15455: 
                   15456: sub gather_categories {
                   15457:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15458:     my %counters;
                   15459:     my $num = 0;
                   15460:     foreach my $item (keys(%{$categories})) {
                   15461:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15462:         if ($container eq '' && $depth == 0) {
                   15463:             $cats->[$depth][$categories->{$item}] = $cat;
                   15464:         } else {
                   15465:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15466:         }
                   15467:         my ($escitem,$tail) = split(/:/,$item,2);
                   15468:         if ($counters{$tail} eq '') {
                   15469:             $counters{$tail} = $num;
                   15470:             $num ++;
                   15471:         }
                   15472:         if (ref($idx) eq 'HASH') {
                   15473:             $idx->{$item} = $counters{$tail};
                   15474:         }
                   15475:         if (ref($jsarray) eq 'ARRAY') {
                   15476:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15477:         }
                   15478:     }
                   15479:     return;
                   15480: }
                   15481: 
                   15482: =pod
                   15483: 
                   15484: =item * &extract_categories()
                   15485: 
                   15486: Used to generate breadcrumb trails for course categories.
                   15487: 
                   15488: Inputs:
1.663     raeburn  15489: 
1.655     raeburn  15490: categories (reference to hash of category definitions).
1.663     raeburn  15491: 
1.655     raeburn  15492: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15493:       categories and subcategories).
1.663     raeburn  15494: 
1.655     raeburn  15495: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15496: 
1.655     raeburn  15497: allitems (reference to hash - key is category key 
                   15498:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15499: 
1.655     raeburn  15500: idx (reference to hash of counters used in Domain Coordinator interface for
                   15501:       editing Course Categories).
1.663     raeburn  15502: 
1.655     raeburn  15503: jsarray (reference to array of categories used to create Javascript arrays for
                   15504:          Domain Coordinator interface for editing Course Categories).
                   15505: 
1.665     raeburn  15506: subcats (reference to hash of arrays containing all subcategories within each 
                   15507:          category, -recursive)
                   15508: 
1.1075.2.132  raeburn  15509: maxd (reference to hash used to hold max depth for all top-level categories).
                   15510: 
1.655     raeburn  15511: Returns: nothing
                   15512: 
                   15513: Side effects: populates trails and allitems hash references.
                   15514: 
                   15515: =cut
                   15516: 
                   15517: sub extract_categories {
1.1075.2.132  raeburn  15518:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15519:     if (ref($categories) eq 'HASH') {
                   15520:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15521:         if (ref($cats->[0]) eq 'ARRAY') {
                   15522:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15523:                 my $name = $cats->[0][$i];
                   15524:                 my $item = &escape($name).'::0';
                   15525:                 my $trailstr;
                   15526:                 if ($name eq 'instcode') {
                   15527:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15528:                 } elsif ($name eq 'communities') {
                   15529:                     $trailstr = &mt('Communities');
1.655     raeburn  15530:                 } else {
                   15531:                     $trailstr = $name;
                   15532:                 }
                   15533:                 if ($allitems->{$item} eq '') {
                   15534:                     push(@{$trails},$trailstr);
                   15535:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15536:                 }
                   15537:                 my @parents = ($name);
                   15538:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15539:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15540:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15541:                         if (ref($subcats) eq 'HASH') {
                   15542:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15543:                         }
1.1075.2.132  raeburn  15544:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15545:                     }
                   15546:                 } else {
                   15547:                     if (ref($subcats) eq 'HASH') {
                   15548:                         $subcats->{$item} = [];
1.655     raeburn  15549:                     }
1.1075.2.132  raeburn  15550:                     if (ref($maxd) eq 'HASH') {
                   15551:                         $maxd->{$name} = 1;
                   15552:                     }
1.655     raeburn  15553:                 }
                   15554:             }
                   15555:         }
                   15556:     }
                   15557:     return;
                   15558: }
                   15559: 
                   15560: =pod
                   15561: 
1.1075.2.56  raeburn  15562: =item * &recurse_categories()
1.655     raeburn  15563: 
                   15564: Recursively used to generate breadcrumb trails for course categories.
                   15565: 
                   15566: Inputs:
1.663     raeburn  15567: 
1.655     raeburn  15568: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15569:       categories and subcategories).
1.663     raeburn  15570: 
1.655     raeburn  15571: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15572: 
                   15573: category (current course category, for which breadcrumb trail is being generated).
                   15574: 
                   15575: trails (reference to array of breadcrumb trails for each category).
                   15576: 
1.655     raeburn  15577: allitems (reference to hash - key is category key
                   15578:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15579: 
1.655     raeburn  15580: parents (array containing containers directories for current category, 
                   15581:          back to top level). 
                   15582: 
                   15583: Returns: nothing
                   15584: 
                   15585: Side effects: populates trails and allitems hash references
                   15586: 
                   15587: =cut
                   15588: 
                   15589: sub recurse_categories {
1.1075.2.132  raeburn  15590:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15591:     my $shallower = $depth - 1;
                   15592:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15593:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15594:             my $name = $cats->[$depth]{$category}[$k];
                   15595:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 15596:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15597:             if ($allitems->{$item} eq '') {
                   15598:                 push(@{$trails},$trailstr);
                   15599:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15600:             }
                   15601:             my $deeper = $depth+1;
                   15602:             push(@{$parents},$category);
1.665     raeburn  15603:             if (ref($subcats) eq 'HASH') {
                   15604:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15605:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15606:                     my $higher;
                   15607:                     if ($j > 0) {
                   15608:                         $higher = &escape($parents->[$j]).':'.
                   15609:                                   &escape($parents->[$j-1]).':'.$j;
                   15610:                     } else {
                   15611:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15612:                     }
                   15613:                     push(@{$subcats->{$higher}},$subcat);
                   15614:                 }
                   15615:             }
                   15616:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  15617:                                 $subcats,$maxd);
1.655     raeburn  15618:             pop(@{$parents});
                   15619:         }
                   15620:     } else {
                   15621:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  15622:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15623:         if ($allitems->{$item} eq '') {
                   15624:             push(@{$trails},$trailstr);
                   15625:             $allitems->{$item} = scalar(@{$trails})-1;
                   15626:         }
1.1075.2.132  raeburn  15627:         if (ref($maxd) eq 'HASH') {
                   15628:             if ($depth > $maxd->{$parents->[0]}) {
                   15629:                 $maxd->{$parents->[0]} = $depth;
                   15630:             }
                   15631:         }
1.655     raeburn  15632:     }
                   15633:     return;
                   15634: }
                   15635: 
1.663     raeburn  15636: =pod
                   15637: 
1.1075.2.56  raeburn  15638: =item * &assign_categories_table()
1.663     raeburn  15639: 
                   15640: Create a datatable for display of hierarchical categories in a domain,
                   15641: with checkboxes to allow a course to be categorized. 
                   15642: 
                   15643: Inputs:
                   15644: 
                   15645: cathash - reference to hash of categories defined for the domain (from
                   15646:           configuration.db)
                   15647: 
                   15648: currcat - scalar with an & separated list of categories assigned to a course. 
                   15649: 
1.919     raeburn  15650: type    - scalar contains course type (Course or Community).
                   15651: 
1.1075.2.117  raeburn  15652: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15653:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15654: 
1.663     raeburn  15655: Returns: $output (markup to be displayed) 
                   15656: 
                   15657: =cut
                   15658: 
                   15659: sub assign_categories_table {
1.1075.2.117  raeburn  15660:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15661:     my $output;
                   15662:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  15663:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15664:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15665:         $maxdepth = scalar(@cats);
                   15666:         if (@cats > 0) {
                   15667:             my $itemcount = 0;
                   15668:             if (ref($cats[0]) eq 'ARRAY') {
                   15669:                 my @currcategories;
                   15670:                 if ($currcat ne '') {
                   15671:                     @currcategories = split('&',$currcat);
                   15672:                 }
1.919     raeburn  15673:                 my $table;
1.663     raeburn  15674:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15675:                     my $parent = $cats[0][$i];
1.919     raeburn  15676:                     next if ($parent eq 'instcode');
                   15677:                     if ($type eq 'Community') {
                   15678:                         next unless ($parent eq 'communities');
                   15679:                     } else {
                   15680:                         next if ($parent eq 'communities');
                   15681:                     }
1.663     raeburn  15682:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15683:                     my $item = &escape($parent).'::0';
                   15684:                     my $checked = '';
                   15685:                     if (@currcategories > 0) {
                   15686:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15687:                             $checked = ' checked="checked"';
1.663     raeburn  15688:                         }
                   15689:                     }
1.919     raeburn  15690:                     my $parent_title = $parent;
                   15691:                     if ($parent eq 'communities') {
                   15692:                         $parent_title = &mt('Communities');
                   15693:                     }
                   15694:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15695:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15696:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15697:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15698:                     my $depth = 1;
                   15699:                     push(@path,$parent);
1.1075.2.117  raeburn  15700:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15701:                     pop(@path);
1.919     raeburn  15702:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15703:                     $itemcount ++;
                   15704:                 }
1.919     raeburn  15705:                 if ($itemcount) {
                   15706:                     $output = &Apache::loncommon::start_data_table().
                   15707:                               $table.
                   15708:                               &Apache::loncommon::end_data_table();
                   15709:                 }
1.663     raeburn  15710:             }
                   15711:         }
                   15712:     }
                   15713:     return $output;
                   15714: }
                   15715: 
                   15716: =pod
                   15717: 
1.1075.2.56  raeburn  15718: =item * &assign_category_rows()
1.663     raeburn  15719: 
                   15720: Create a datatable row for display of nested categories in a domain,
                   15721: with checkboxes to allow a course to be categorized,called recursively.
                   15722: 
                   15723: Inputs:
                   15724: 
                   15725: itemcount - track row number for alternating colors
                   15726: 
                   15727: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15728:       categories and subcategories.
                   15729: 
                   15730: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15731: 
                   15732: parent - parent of current category item
                   15733: 
                   15734: path - Array containing all categories back up through the hierarchy from the
                   15735:        current category to the top level.
                   15736: 
                   15737: currcategories - reference to array of current categories assigned to the course
                   15738: 
1.1075.2.117  raeburn  15739: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15740:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15741: 
1.663     raeburn  15742: Returns: $output (markup to be displayed).
                   15743: 
                   15744: =cut
                   15745: 
                   15746: sub assign_category_rows {
1.1075.2.117  raeburn  15747:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15748:     my ($text,$name,$item,$chgstr);
                   15749:     if (ref($cats) eq 'ARRAY') {
                   15750:         my $maxdepth = scalar(@{$cats});
                   15751:         if (ref($cats->[$depth]) eq 'HASH') {
                   15752:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15753:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15754:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  15755:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15756:                 for (my $j=0; $j<$numchildren; $j++) {
                   15757:                     $name = $cats->[$depth]{$parent}[$j];
                   15758:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15759:                     my $deeper = $depth+1;
                   15760:                     my $checked = '';
                   15761:                     if (ref($currcategories) eq 'ARRAY') {
                   15762:                         if (@{$currcategories} > 0) {
                   15763:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15764:                                 $checked = ' checked="checked"';
1.663     raeburn  15765:                             }
                   15766:                         }
                   15767:                     }
1.664     raeburn  15768:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15769:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15770:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15771:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15772:                              '</td><td>';
1.663     raeburn  15773:                     if (ref($path) eq 'ARRAY') {
                   15774:                         push(@{$path},$name);
1.1075.2.117  raeburn  15775:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15776:                         pop(@{$path});
                   15777:                     }
                   15778:                     $text .= '</td></tr>';
                   15779:                 }
                   15780:                 $text .= '</table></td>';
                   15781:             }
                   15782:         }
                   15783:     }
                   15784:     return $text;
                   15785: }
                   15786: 
1.1075.2.69  raeburn  15787: =pod
                   15788: 
                   15789: =back
                   15790: 
                   15791: =cut
                   15792: 
1.655     raeburn  15793: ############################################################
                   15794: ############################################################
                   15795: 
                   15796: 
1.443     albertel 15797: sub commit_customrole {
1.664     raeburn  15798:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15799:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15800:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15801:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15802:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15803:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15804:                  '</b><br />';
                   15805:     return $output;
                   15806: }
                   15807: 
                   15808: sub commit_standardrole {
1.1075.2.31  raeburn  15809:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15810:     my ($output,$logmsg,$linefeed);
                   15811:     if ($context eq 'auto') {
                   15812:         $linefeed = "\n";
                   15813:     } else {
                   15814:         $linefeed = "<br />\n";
                   15815:     }  
1.443     albertel 15816:     if ($three eq 'st') {
1.541     raeburn  15817:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  15818:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15819:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15820:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15821:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15822:         } else {
1.541     raeburn  15823:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15824:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15825:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15826:             if ($context eq 'auto') {
                   15827:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15828:             } else {
                   15829:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15830:                &mt('Add to classlist').': <b>ok</b>';
                   15831:             }
                   15832:             $output .= $linefeed;
1.443     albertel 15833:         }
                   15834:     } else {
                   15835:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15836:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15837:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15838:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15839:         if ($context eq 'auto') {
                   15840:             $output .= $result.$linefeed;
                   15841:         } else {
                   15842:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15843:         }
1.443     albertel 15844:     }
                   15845:     return $output;
                   15846: }
                   15847: 
                   15848: sub commit_studentrole {
1.1075.2.31  raeburn  15849:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15850:         $credits) = @_;
1.626     raeburn  15851:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15852:     if ($context eq 'auto') {
                   15853:         $linefeed = "\n";
                   15854:     } else {
                   15855:         $linefeed = '<br />'."\n";
                   15856:     }
1.443     albertel 15857:     if (defined($one) && defined($two)) {
                   15858:         my $cid=$one.'_'.$two;
                   15859:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15860:         my $secchange = 0;
                   15861:         my $expire_role_result;
                   15862:         my $modify_section_result;
1.628     raeburn  15863:         if ($oldsec ne '-1') { 
                   15864:             if ($oldsec ne $sec) {
1.443     albertel 15865:                 $secchange = 1;
1.628     raeburn  15866:                 my $now = time;
1.443     albertel 15867:                 my $uurl='/'.$cid;
                   15868:                 $uurl=~s/\_/\//g;
                   15869:                 if ($oldsec) {
                   15870:                     $uurl.='/'.$oldsec;
                   15871:                 }
1.626     raeburn  15872:                 $oldsecurl = $uurl;
1.628     raeburn  15873:                 $expire_role_result = 
1.1075.2.161.  .14(raeb 15874:-23):                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
1.628     raeburn  15875:                 if ($env{'request.course.sec'} ne '') { 
                   15876:                     if ($expire_role_result eq 'refused') {
                   15877:                         my @roles = ('st');
                   15878:                         my @statuses = ('previous');
                   15879:                         my @roledoms = ($one);
                   15880:                         my $withsec = 1;
                   15881:                         my %roleshash = 
                   15882:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15883:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15884:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15885:                             my ($oldstart,$oldend) = 
                   15886:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15887:                             if ($oldend > 0 && $oldend <= $now) {
                   15888:                                 $expire_role_result = 'ok';
                   15889:                             }
                   15890:                         }
                   15891:                     }
                   15892:                 }
1.443     albertel 15893:                 $result = $expire_role_result;
                   15894:             }
                   15895:         }
                   15896:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15897:             $modify_section_result = 
                   15898:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15899:                                                            undef,undef,undef,$sec,
                   15900:                                                            $end,$start,'','',$cid,
                   15901:                                                            '',$context,$credits);
1.443     albertel 15902:             if ($modify_section_result =~ /^ok/) {
                   15903:                 if ($secchange == 1) {
1.628     raeburn  15904:                     if ($sec eq '') {
                   15905:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15906:                     } else {
                   15907:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15908:                     }
1.443     albertel 15909:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15910:                     if ($sec eq '') {
                   15911:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15912:                     } else {
                   15913:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15914:                     }
1.443     albertel 15915:                 } else {
1.628     raeburn  15916:                     if ($sec eq '') {
                   15917:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15918:                     } else {
                   15919:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15920:                     }
1.443     albertel 15921:                 }
                   15922:             } else {
1.628     raeburn  15923:                 if ($secchange) {       
                   15924:                     $$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;
                   15925:                 } else {
                   15926:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15927:                 }
1.443     albertel 15928:             }
                   15929:             $result = $modify_section_result;
                   15930:         } elsif ($secchange == 1) {
1.628     raeburn  15931:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15932:                 $$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  15933:             } else {
                   15934:                 $$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;
                   15935:             }
1.626     raeburn  15936:             if ($expire_role_result eq 'refused') {
                   15937:                 my $newsecurl = '/'.$cid;
                   15938:                 $newsecurl =~ s/\_/\//g;
                   15939:                 if ($sec ne '') {
                   15940:                     $newsecurl.='/'.$sec;
                   15941:                 }
                   15942:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15943:                     if ($sec eq '') {
                   15944:                         $$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;
                   15945:                     } else {
                   15946:                         $$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;
                   15947:                     }
                   15948:                 }
                   15949:             }
1.443     albertel 15950:         }
                   15951:     } else {
1.626     raeburn  15952:         $$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 15953:         $result = "error: incomplete course id\n";
                   15954:     }
                   15955:     return $result;
                   15956: }
                   15957: 
1.1075.2.25  raeburn  15958: sub show_role_extent {
                   15959:     my ($scope,$context,$role) = @_;
                   15960:     $scope =~ s{^/}{};
                   15961:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15962:     push(@courseroles,'co');
                   15963:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15964:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15965:         $scope =~ s{/}{_};
                   15966:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15967:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15968:         my ($audom,$auname) = split(/\//,$scope);
                   15969:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15970:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15971:     } else {
                   15972:         $scope =~ s{/$}{};
                   15973:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15974:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15975:     }
                   15976: }
                   15977: 
1.443     albertel 15978: ############################################################
                   15979: ############################################################
                   15980: 
1.566     albertel 15981: sub check_clone {
1.578     raeburn  15982:     my ($args,$linefeed) = @_;
1.566     albertel 15983:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15984:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15985:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 15986:21):     my $clonetitle;
                   15987:21):     my @clonemsg;
1.566     albertel 15988:     my $can_clone = 0;
1.944     raeburn  15989:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15990:     if ($lctype ne 'community') {
                   15991:         $lctype = 'course';
                   15992:     }
1.566     albertel 15993:     if ($clonehome eq 'no_host') {
1.944     raeburn  15994:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15995:21):             push(@clonemsg,({
                   15996:21):                               mt => 'No new community created.',
                   15997:21):                               args => [],
                   15998:21):                             },
                   15999:21):                             {
                   16000:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16001:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16002:21):                             }));
1.908     raeburn  16003:         } else {
1.1075.2.161.  .1(raebu 16004:21):             push(@clonemsg,({
                   16005:21):                               mt => 'No new course created.',
                   16006:21):                               args => [],
                   16007:21):                             },
                   16008:21):                             {
                   16009:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16010:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16011:21):                             }));
                   16012:21):         }
1.566     albertel 16013:     } else {
                   16014: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 16015:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16016:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16017:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 16018:21):                 push(@clonemsg,({
                   16019:21):                                   mt => 'No new community created.',
                   16020:21):                                   args => [],
                   16021:21):                                 },
                   16022:21):                                 {
                   16023:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16024:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16025:21):                                 }));
                   16026:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16027:             }
                   16028:         }
1.1075.2.119  raeburn  16029: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16030:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16031: 	    $can_clone = 1;
                   16032: 	} else {
1.1075.2.95  raeburn  16033: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16034: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  16035:             if ($clonehash{'cloners'} eq '') {
                   16036:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16037:                 if ($domdefs{'canclone'}) {
                   16038:                     unless ($domdefs{'canclone'} eq 'none') {
                   16039:                         if ($domdefs{'canclone'} eq 'domain') {
                   16040:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16041:                                 $can_clone = 1;
                   16042:                             }
                   16043:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16044:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16045:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16046:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16047:                                 $can_clone = 1;
                   16048:                             }
                   16049:                         }
                   16050:                     }
1.908     raeburn  16051:                 }
1.1075.2.95  raeburn  16052:             } else {
                   16053: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16054:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16055:                     $can_clone = 1;
1.1075.2.95  raeburn  16056:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16057:                     $can_clone = 1;
1.1075.2.96  raeburn  16058:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16059:                     $can_clone = 1;
1.1075.2.95  raeburn  16060:                 }
                   16061:                 unless ($can_clone) {
1.1075.2.96  raeburn  16062:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16063:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  16064:                         my (%gotdomdefaults,%gotcodedefaults);
                   16065:                         foreach my $cloner (@cloners) {
                   16066:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16067:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16068:                                 my (%codedefaults,@code_order);
                   16069:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16070:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16071:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16072:                                     }
                   16073:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16074:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16075:                                     }
                   16076:                                 } else {
                   16077:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16078:                                                                             \%codedefaults,
                   16079:                                                                             \@code_order);
                   16080:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16081:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16082:                                 }
                   16083:                                 if (@code_order > 0) {
                   16084:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16085:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16086:                                                                                 $args->{'crscode'})) {
                   16087:                                         $can_clone = 1;
                   16088:                                         last;
                   16089:                                     }
                   16090:                                 }
                   16091:                             }
                   16092:                         }
                   16093:                     }
1.1075.2.96  raeburn  16094:                 }
                   16095:             }
                   16096:             unless ($can_clone) {
                   16097:                 my $ccrole = 'cc';
                   16098:                 if ($args->{'crstype'} eq 'Community') {
                   16099:                     $ccrole = 'co';
                   16100:                 }
                   16101:                 my %roleshash =
                   16102:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16103:                                                   $args->{'ccdomain'},
                   16104:                                                   'userroles',['active'],[$ccrole],
                   16105:                                                   [$args->{'clonedomain'}]);
                   16106:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16107:                     $can_clone = 1;
                   16108:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16109:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16110:                     $can_clone = 1;
1.1075.2.95  raeburn  16111:                 }
                   16112:             }
                   16113:             unless ($can_clone) {
                   16114:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16115:21):                     push(@clonemsg,({
                   16116:21):                                       mt => 'No new community created.',
                   16117:21):                                       args => [],
                   16118:21):                                     },
                   16119:21):                                     {
                   16120:21):                                       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]).',
                   16121:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16122:21):                                     }));
1.1075.2.95  raeburn  16123:                 } else {
1.1075.2.161.  .1(raebu 16124:21):                     push(@clonemsg,({
                   16125:21):                                       mt => 'No new course created.',
                   16126:21):                                       args => [],
                   16127:21):                                     },
                   16128:21):                                     {
                   16129:21):                                       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]).',
                   16130:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16131:21):                                     }));
1.578     raeburn  16132: 	        }
1.566     albertel 16133: 	    }
1.578     raeburn  16134:         }
1.566     albertel 16135:     }
1.1075.2.161.  .1(raebu 16136:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16137: }
                   16138: 
1.444     albertel 16139: sub construct_course {
1.1075.2.119  raeburn  16140:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16141:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16142:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16143:     my $linefeed =  '<br />'."\n";
                   16144:     if ($context eq 'auto') {
                   16145:         $linefeed = "\n";
                   16146:     }
1.566     albertel 16147: 
                   16148: #
                   16149: # Are we cloning?
                   16150: #
1.1075.2.161.  .1(raebu 16151:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16152:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16153:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16154:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16155:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16156: 	}
                   16157:     }
                   16158: 
1.444     albertel 16159: #
                   16160: # Open course
                   16161: #
                   16162:     my $crstype = lc($args->{'crstype'});
                   16163:     my %cenv=();
                   16164:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16165:                                              $args->{'cdescr'},
                   16166:                                              $args->{'curl'},
                   16167:                                              $args->{'course_home'},
                   16168:                                              $args->{'nonstandard'},
                   16169:                                              $args->{'crscode'},
                   16170:                                              $args->{'ccuname'}.':'.
                   16171:                                              $args->{'ccdomain'},
1.882     raeburn  16172:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16173:21):                                              $cnum,$context,$category,
                   16174:21):                                              $callercontext);
1.444     albertel 16175: 
                   16176:     # Note: The testing routines depend on this being output; see 
                   16177:     # Utils::Course. This needs to at least be output as a comment
                   16178:     # if anyone ever decides to not show this, and Utils::Course::new
                   16179:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16180:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16181:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16182:21):     } else {
                   16183:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16184:21):     }
1.943     raeburn  16185:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16186:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16187:     }
                   16188: 
1.444     albertel 16189: #
                   16190: # Check if created correctly
                   16191: #
1.479     albertel 16192:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16193:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16194:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16195:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16196:21):             $outcome .= &mt_user($user_lh,
                   16197:21):                             'Course creation failed, unrecognized course home server.');
                   16198:21):         } else {
                   16199:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16200:21):         }
                   16201:21):         $outcome .= $linefeed;
                   16202:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16203:     }
1.541     raeburn  16204:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16205: 
1.444     albertel 16206: #
1.566     albertel 16207: # Do the cloning
1.1075.2.161.  .1(raebu 16208:21): #
                   16209:21):     my @clonemsg;
1.566     albertel 16210:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16211:21):         push(@clonemsg,
                   16212:21):                       {
                   16213:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16214:21):                           args => [$crstype,$clonetitle],
                   16215:21):                       });
1.566     albertel 16216: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16217: # Copy all files
1.1075.2.161.  .1(raebu 16218:21):         my @info =
                   16219:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16220:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16221:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16222:21):                                                      $args->{'tinyurls'});
                   16223:21):         if (@info) {
                   16224:21):             push(@clonemsg,@info);
                   16225:21):         }
1.444     albertel 16226: # Restore URL
1.566     albertel 16227: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16228: # Restore title
1.566     albertel 16229: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16230: # Restore creation date, creator and creation context.
                   16231:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16232:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16233:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16234: # Mark as cloned
1.566     albertel 16235: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16236: # Need to clone grading mode
                   16237:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16238:         $cenv{'grading'}=$newenv{'grading'};
                   16239: # Do not clone these environment entries
                   16240:         &Apache::lonnet::del('environment',
                   16241:                   ['default_enrollment_start_date',
                   16242:                    'default_enrollment_end_date',
                   16243:                    'question.email',
                   16244:                    'policy.email',
                   16245:                    'comment.email',
                   16246:                    'pch.users.denied',
1.725     raeburn  16247:                    'plc.users.denied',
                   16248:                    'hidefromcat',
1.1075.2.36  raeburn  16249:                    'checkforpriv',
1.1075.2.158  raeburn  16250:                    'categories'],
1.638     www      16251:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16252:         if ($args->{'textbook'}) {
                   16253:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16254:         }
1.444     albertel 16255:     }
1.566     albertel 16256: 
1.444     albertel 16257: #
                   16258: # Set environment (will override cloned, if existing)
                   16259: #
                   16260:     my @sections = ();
                   16261:     my @xlists = ();
                   16262:     if ($args->{'crstype'}) {
                   16263:         $cenv{'type'}=$args->{'crstype'};
                   16264:     }
1.1075.2.161.  .17(raeb 16265:-23):     if ($args->{'lti'}) {
                   16266:-23):         $cenv{'internal.lti'}=$args->{'lti'};
                   16267:-23):     }
1.444     albertel 16268:     if ($args->{'crsid'}) {
                   16269:         $cenv{'courseid'}=$args->{'crsid'};
                   16270:     }
                   16271:     if ($args->{'crscode'}) {
                   16272:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16273:     }
                   16274:     if ($args->{'crsquota'} ne '') {
                   16275:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16276:     } else {
                   16277:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16278:     }
                   16279:     if ($args->{'ccuname'}) {
                   16280:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16281:                                         ':'.$args->{'ccdomain'};
                   16282:     } else {
                   16283:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16284:     }
1.1075.2.31  raeburn  16285:     if ($args->{'defaultcredits'}) {
                   16286:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16287:     }
1.444     albertel 16288:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16289:     if ($args->{'crssections'}) {
                   16290:         $cenv{'internal.sectionnums'} = '';
                   16291:         if ($args->{'crssections'} =~ m/,/) {
                   16292:             @sections = split/,/,$args->{'crssections'};
                   16293:         } else {
                   16294:             $sections[0] = $args->{'crssections'};
                   16295:         }
                   16296:         if (@sections > 0) {
                   16297:             foreach my $item (@sections) {
                   16298:                 my ($sec,$gp) = split/:/,$item;
                   16299:                 my $class = $args->{'crscode'}.$sec;
                   16300:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16301:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16302:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16303:                     push(@badclasses,$class);
1.444     albertel 16304:                 }
                   16305:             }
                   16306:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16307:         }
                   16308:     }
                   16309: # do not hide course coordinator from staff listing, 
                   16310: # even if privileged
                   16311:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16312: # add course coordinator's domain to domains to check for privileged users
                   16313: # if different to course domain
                   16314:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16315:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16316:     }
1.444     albertel 16317: # add crosslistings
                   16318:     if ($args->{'crsxlist'}) {
                   16319:         $cenv{'internal.crosslistings'}='';
                   16320:         if ($args->{'crsxlist'} =~ m/,/) {
                   16321:             @xlists = split/,/,$args->{'crsxlist'};
                   16322:         } else {
                   16323:             $xlists[0] = $args->{'crsxlist'};
                   16324:         }
                   16325:         if (@xlists > 0) {
                   16326:             foreach my $item (@xlists) {
                   16327:                 my ($xl,$gp) = split/:/,$item;
                   16328:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16329:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16330:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16331:                     push(@badclasses,$xl);
1.444     albertel 16332:                 }
                   16333:             }
                   16334:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16335:         }
                   16336:     }
                   16337:     if ($args->{'autoadds'}) {
                   16338:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16339:     }
                   16340:     if ($args->{'autodrops'}) {
                   16341:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16342:     }
                   16343: # check for notification of enrollment changes
                   16344:     my @notified = ();
                   16345:     if ($args->{'notify_owner'}) {
                   16346:         if ($args->{'ccuname'} ne '') {
                   16347:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16348:         }
                   16349:     }
                   16350:     if ($args->{'notify_dc'}) {
                   16351:         if ($uname ne '') { 
1.630     raeburn  16352:             push(@notified,$uname.':'.$udom);
1.444     albertel 16353:         }
                   16354:     }
                   16355:     if (@notified > 0) {
                   16356:         my $notifylist;
                   16357:         if (@notified > 1) {
                   16358:             $notifylist = join(',',@notified);
                   16359:         } else {
                   16360:             $notifylist = $notified[0];
                   16361:         }
                   16362:         $cenv{'internal.notifylist'} = $notifylist;
                   16363:     }
                   16364:     if (@badclasses > 0) {
                   16365:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16366:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16367:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16368:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16369:         );
1.1075.2.119  raeburn  16370:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16371:                            &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  16372:         if ($context eq 'auto') {
                   16373:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16374:         } else {
1.566     albertel 16375:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16376:         }
                   16377:         foreach my $item (@badclasses) {
1.541     raeburn  16378:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16379:                 $outcome .= " - $item\n";
1.541     raeburn  16380:             } else {
1.1075.2.119  raeburn  16381:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16382:             }
1.1075.2.119  raeburn  16383:         }
                   16384:         if ($context eq 'auto') {
                   16385:             $outcome .= $linefeed;
                   16386:         } else {
                   16387:             $outcome .= "</ul><br /><br /></div>\n";
                   16388:         }
1.444     albertel 16389:     }
                   16390:     if ($args->{'no_end_date'}) {
                   16391:         $args->{'endaccess'} = 0;
                   16392:     }
                   16393:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16394:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16395:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16396:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16397:     if ($args->{'showphotos'}) {
                   16398:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16399:     }
                   16400:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16401:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16402:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16403:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16404:             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'); 
                   16405:             if ($context eq 'auto') {
                   16406:                 $outcome .= $krb_msg;
                   16407:             } else {
1.566     albertel 16408:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16409:             }
                   16410:             $outcome .= $linefeed;
1.444     albertel 16411:         }
                   16412:     }
                   16413:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16414:        if ($args->{'setpolicy'}) {
                   16415:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16416:        }
                   16417:        if ($args->{'setcontent'}) {
                   16418:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16419:        }
1.1075.2.110  raeburn  16420:        if ($args->{'setcomment'}) {
                   16421:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16422:        }
1.444     albertel 16423:     }
                   16424:     if ($args->{'reshome'}) {
                   16425: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16426: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16427:     }
                   16428: #
                   16429: # course has keyed access
                   16430: #
                   16431:     if ($args->{'setkeys'}) {
                   16432:        $cenv{'keyaccess'}='yes';
                   16433:     }
                   16434: # if specified, key authority is not course, but user
                   16435: # only active if keyaccess is yes
                   16436:     if ($args->{'keyauth'}) {
1.487     albertel 16437: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16438: 	$user = &LONCAPA::clean_username($user);
                   16439: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16440: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16441: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16442: 	}
                   16443:     }
                   16444: 
1.1075.2.59  raeburn  16445: #
                   16446: #  generate and store uniquecode (available to course requester), if course should have one.
                   16447: #
                   16448:     if ($args->{'uniquecode'}) {
                   16449:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16450:         if ($code) {
                   16451:             $cenv{'internal.uniquecode'} = $code;
                   16452:             my %crsinfo =
                   16453:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16454:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16455:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16456:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16457:             }
                   16458:             if (ref($coderef)) {
                   16459:                 $$coderef = $code;
                   16460:             }
                   16461:         }
                   16462:     }
                   16463: 
1.444     albertel 16464:     if ($args->{'disresdis'}) {
                   16465:         $cenv{'pch.roles.denied'}='st';
                   16466:     }
                   16467:     if ($args->{'disablechat'}) {
                   16468:         $cenv{'plc.roles.denied'}='st';
                   16469:     }
                   16470: 
                   16471:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16472:     # course
                   16473:     $cenv{'course.helper.not.run'} = 1;
                   16474:     #
                   16475:     # Use new Randomseed
                   16476:     #
                   16477:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16478:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16479:     #
                   16480:     # The encryption code and receipt prefix for this course
                   16481:     #
                   16482:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16483:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16484:     #
                   16485:     # By default, use standard grading
                   16486:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16487: 
1.541     raeburn  16488:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16489:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16490: #
                   16491: # Open all assignments
                   16492: #
                   16493:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16494:        my $opendate = time;
                   16495:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16496:            $opendate = $args->{'openallfrom'};
                   16497:        }
1.444     albertel 16498:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16499:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16500:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16501:        $outcome .= &mt('All assignments open starting [_1]',
                   16502:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16503:                    &Apache::lonnet::cput
                   16504:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16505:    }
                   16506: #
                   16507: # Set first page
                   16508: #
                   16509:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16510: 	    || ($cloneid)) {
                   16511: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16512: 
                   16513: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16514:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16515: 
1.444     albertel 16516:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16517:         my $title; my $url;
                   16518:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16519: 	    $title=&mt('Syllabus');
1.444     albertel 16520:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16521:         } else {
1.963     raeburn  16522:             $title=&mt('Table of Contents');
1.444     albertel 16523:             $url='/adm/navmaps';
                   16524:         }
1.445     albertel 16525: 
                   16526:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16527: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16528: 
                   16529: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16530:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16531:     }
1.566     albertel 16532: 
1.1075.2.161.  .1(raebu 16533:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16534: }
                   16535: 
1.1075.2.59  raeburn  16536: sub make_unique_code {
                   16537:     my ($cdom,$cnum) = @_;
                   16538:     # get lock on uniquecodes db
                   16539:     my $lockhash = {
                   16540:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16541:                                                   ':'.$env{'user.domain'},
                   16542:                    };
                   16543:     my $tries = 0;
                   16544:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16545:     my ($code,$error);
                   16546: 
                   16547:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16548:         $tries ++;
                   16549:         sleep 1;
                   16550:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16551:     }
                   16552:     if ($gotlock eq 'ok') {
                   16553:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16554:         my $gotcode;
                   16555:         my $attempts = 0;
                   16556:         while ((!$gotcode) && ($attempts < 100)) {
                   16557:             $code = &generate_code();
                   16558:             if (!exists($currcodes{$code})) {
                   16559:                 $gotcode = 1;
                   16560:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16561:                     $error = 'nostore';
                   16562:                 }
                   16563:             }
                   16564:             $attempts ++;
                   16565:         }
                   16566:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16567:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16568:     } else {
                   16569:         $error = 'nolock';
                   16570:     }
                   16571:     return ($code,$error);
                   16572: }
                   16573: 
                   16574: sub generate_code {
                   16575:     my $code;
                   16576:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16577:     for (my $i=0; $i<6; $i++) {
                   16578:         my $lettnum = int (rand 2);
                   16579:         my $item = '';
                   16580:         if ($lettnum) {
                   16581:             $item = $letts[int( rand(18) )];
                   16582:         } else {
                   16583:             $item = 1+int( rand(8) );
                   16584:         }
                   16585:         $code .= $item;
                   16586:     }
                   16587:     return $code;
                   16588: }
                   16589: 
1.444     albertel 16590: ############################################################
                   16591: ############################################################
                   16592: 
1.953     droeschl 16593: #SD
                   16594: # only Community and Course, or anything else?
1.378     raeburn  16595: sub course_type {
                   16596:     my ($cid) = @_;
                   16597:     if (!defined($cid)) {
                   16598:         $cid = $env{'request.course.id'};
                   16599:     }
1.404     albertel 16600:     if (defined($env{'course.'.$cid.'.type'})) {
                   16601:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16602:     } else {
                   16603:         return 'Course';
1.377     raeburn  16604:     }
                   16605: }
1.156     albertel 16606: 
1.406     raeburn  16607: sub group_term {
                   16608:     my $crstype = &course_type();
                   16609:     my %names = (
                   16610:                   'Course' => 'group',
1.865     raeburn  16611:                   'Community' => 'group',
1.406     raeburn  16612:                 );
                   16613:     return $names{$crstype};
                   16614: }
                   16615: 
1.902     raeburn  16616: sub course_types {
1.1075.2.161.  .17(raeb 16617:-23):     my @types = ('official','unofficial','community','textbook','lti');
1.902     raeburn  16618:     my %typename = (
                   16619:                          official   => 'Official course',
                   16620:                          unofficial => 'Unofficial course',
                   16621:                          community  => 'Community',
1.1075.2.59  raeburn  16622:                          textbook   => 'Textbook course',
1.1075.2.161.  .17(raeb 16623:-23):                          lti        => 'LTI provider',
1.902     raeburn  16624:                    );
                   16625:     return (\@types,\%typename);
                   16626: }
                   16627: 
1.156     albertel 16628: sub icon {
                   16629:     my ($file)=@_;
1.505     albertel 16630:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16631:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16632:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16633:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16634: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16635: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16636: 	            $curfext.".gif") {
                   16637: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16638: 		$curfext.".gif";
                   16639: 	}
                   16640:     }
1.249     albertel 16641:     return &lonhttpdurl($iconname);
1.154     albertel 16642: } 
1.84      albertel 16643: 
1.575     albertel 16644: sub lonhttpdurl {
1.692     www      16645: #
                   16646: # Had been used for "small fry" static images on separate port 8080.
                   16647: # Modify here if lightweight http functionality desired again.
                   16648: # Currently eliminated due to increasing firewall issues.
                   16649: #
1.575     albertel 16650:     my ($url)=@_;
1.692     www      16651:     return $url;
1.215     albertel 16652: }
                   16653: 
1.213     albertel 16654: sub connection_aborted {
                   16655:     my ($r)=@_;
                   16656:     $r->print(" ");$r->rflush();
                   16657:     my $c = $r->connection;
                   16658:     return $c->aborted();
                   16659: }
                   16660: 
1.221     foxr     16661: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16662: #    strings as 'strings'.
                   16663: sub escape_single {
1.221     foxr     16664:     my ($input) = @_;
1.223     albertel 16665:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16666:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16667:     return $input;
                   16668: }
1.223     albertel 16669: 
1.222     foxr     16670: #  Same as escape_single, but escape's "'s  This 
                   16671: #  can be used for  "strings"
                   16672: sub escape_double {
                   16673:     my ($input) = @_;
                   16674:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16675:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16676:     return $input;
                   16677: }
1.223     albertel 16678:  
1.222     foxr     16679: #   Escapes the last element of a full URL.
                   16680: sub escape_url {
                   16681:     my ($url)   = @_;
1.238     raeburn  16682:     my @urlslices = split(/\//, $url,-1);
1.369     www      16683:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  16684:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16685: }
1.462     albertel 16686: 
1.820     raeburn  16687: sub compare_arrays {
                   16688:     my ($arrayref1,$arrayref2) = @_;
                   16689:     my (@difference,%count);
                   16690:     @difference = ();
                   16691:     %count = ();
                   16692:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16693:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16694:         foreach my $element (keys(%count)) {
                   16695:             if ($count{$element} == 1) {
                   16696:                 push(@difference,$element);
                   16697:             }
                   16698:         }
                   16699:     }
                   16700:     return @difference;
                   16701: }
                   16702: 
1.1075.2.152  raeburn  16703: sub lon_status_items {
                   16704:     my %defaults = (
                   16705:                      E         => 100,
                   16706:                      W         => 4,
                   16707:                      N         => 1,
                   16708:                      U         => 5,
                   16709:                      threshold => 200,
                   16710:                      sysmail   => 2500,
                   16711:                    );
                   16712:     my %names = (
                   16713:                    E => 'Errors',
                   16714:                    W => 'Warnings',
                   16715:                    N => 'Notices',
                   16716:                    U => 'Unsent',
                   16717:                 );
                   16718:     return (\%defaults,\%names);
                   16719: }
                   16720: 
1.817     bisitz   16721: # -------------------------------------------------------- Initialize user login
1.462     albertel 16722: sub init_user_environment {
1.463     albertel 16723:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16724:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16725: 
                   16726:     my $public=($username eq 'public' && $domain eq 'public');
                   16727: 
                   16728: # See if old ID present, if so, remove
                   16729: 
1.1062    raeburn  16730:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16731:     my $now=time;
                   16732: 
                   16733:     if ($public) {
                   16734: 	my $max_public=100;
                   16735: 	my $oldest;
                   16736: 	my $oldest_time=0;
                   16737: 	for(my $next=1;$next<=$max_public;$next++) {
                   16738: 	    if (-e $lonids."/publicuser_$next.id") {
                   16739: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16740: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16741: 		    $oldest_time=$mtime;
                   16742: 		    $oldest=$next;
                   16743: 		}
                   16744: 	    } else {
                   16745: 		$cookie="publicuser_$next";
                   16746: 		last;
                   16747: 	    }
                   16748: 	}
                   16749: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16750:     } else {
1.463     albertel 16751: 	# if this isn't a robot, kill any existing non-robot sessions
                   16752: 	if (!$args->{'robot'}) {
                   16753: 	    opendir(DIR,$lonids);
                   16754: 	    while ($filename=readdir(DIR)) {
                   16755: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  16756:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16757:                             &GDBM_READER(),0640)) {
                   16758:                         my $linkedfile;
                   16759:                         if (exists($oldenv{'user.linkedenv'})) {
                   16760:                             $linkedfile = $oldenv{'user.linkedenv'};
                   16761:                         }
                   16762:                         untie(%oldenv);
                   16763:                         if (unlink("$lonids/$filename")) {
                   16764:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16765:                                 if (-l "$lonids/$linkedfile.id") {
                   16766:                                     unlink("$lonids/$linkedfile.id");
                   16767:                                 }
                   16768:                             }
                   16769:                         }
                   16770:                     } else {
                   16771:                         unlink($lonids.'/'.$filename);
                   16772:                     }
1.463     albertel 16773: 		}
1.462     albertel 16774: 	    }
1.463     albertel 16775: 	    closedir(DIR);
1.1075.2.84  raeburn  16776: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16777:             my $namespace = 'nohist_courseeditor';
                   16778:             my $lockingkey = 'paste'."\0".'locked_num';
                   16779:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16780:                                                 $domain,$username);
                   16781:             if (exists($lockhash{$lockingkey})) {
                   16782:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16783:                 unless ($delresult eq 'ok') {
                   16784:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16785:                 }
                   16786:             }
1.462     albertel 16787: 	}
                   16788: # Give them a new cookie
1.463     albertel 16789: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16790: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16791: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16792:     
                   16793: # Initialize roles
                   16794: 
1.1062    raeburn  16795: 	($userroles,$firstaccenv,$timerintenv) = 
                   16796:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16797:     }
                   16798: # ------------------------------------ Check browser type and MathML capability
                   16799: 
1.1075.2.77  raeburn  16800:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16801:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16802: 
                   16803: # ------------------------------------------------------------- Get environment
                   16804: 
                   16805:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16806:     my ($tmp) = keys(%userenv);
                   16807:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   16808:     } else {
                   16809: 	undef(%userenv);
                   16810:     }
                   16811:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16812: 	$form->{'interface'}=$userenv{'interface'};
                   16813:     }
                   16814:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16815: 
                   16816: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16817:     foreach my $option ('interface','localpath','localres') {
                   16818:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16819:     }
                   16820: # --------------------------------------------------------- Write first profile
                   16821: 
                   16822:     {
1.1075.2.150  raeburn  16823:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 16824: 	my %initial_env = 
                   16825: 	    ("user.name"          => $username,
                   16826: 	     "user.domain"        => $domain,
                   16827: 	     "user.home"          => $authhost,
                   16828: 	     "browser.type"       => $clientbrowser,
                   16829: 	     "browser.version"    => $clientversion,
                   16830: 	     "browser.mathml"     => $clientmathml,
                   16831: 	     "browser.unicode"    => $clientunicode,
                   16832: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  16833:              "browser.mobile"     => $clientmobile,
                   16834:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  16835:              "browser.osversion"  => $clientosversion,
1.462     albertel 16836: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16837: 	     "request.course.fn"  => '',
                   16838: 	     "request.course.uri" => '',
                   16839: 	     "request.course.sec" => '',
                   16840: 	     "request.role"       => 'cm',
                   16841: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  16842: 	     "request.host"       => $ip,);
1.462     albertel 16843: 
                   16844:         if ($form->{'localpath'}) {
                   16845: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16846: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16847:         }
                   16848: 	
                   16849: 	if ($form->{'interface'}) {
                   16850: 	    $form->{'interface'}=~s/\W//gs;
                   16851: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16852: 	    $env{'browser.interface'}=$form->{'interface'};
                   16853: 	}
                   16854: 
1.1075.2.54  raeburn  16855:         if ($form->{'iptoken'}) {
                   16856:             my $lonhost = $r->dir_config('lonHostID');
                   16857:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16858:             $env{'user.noloadbalance'} = $lonhost;
                   16859:         }
                   16860: 
1.1075.2.120  raeburn  16861:         if ($form->{'noloadbalance'}) {
                   16862:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16863:             my $hosthere = $form->{'noloadbalance'};
                   16864:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16865:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16866:                 $env{'user.noloadbalance'} = $hosthere;
                   16867:             }
                   16868:         }
                   16869: 
1.1016    raeburn  16870:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  16871:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16872:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  16873: 
1.1075.2.161.  .10(raeb 16874:-22):             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1075.2.125  raeburn  16875:                 $userenv{'availabletools.'.$tool} = 
                   16876:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16877:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16878:             }
1.724     raeburn  16879: 
1.1075.2.161.  .17(raeb 16880:-23):             foreach my $crstype ('official','unofficial','community','textbook','lti') {
1.1075.2.125  raeburn  16881:                 $userenv{'canrequest.'.$crstype} =
                   16882:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16883:                                                       'reload','requestcourses',
                   16884:                                                       \%userenv,\%domdef,\%is_adv);
                   16885:             }
1.765     raeburn  16886: 
1.1075.2.125  raeburn  16887:             $userenv{'canrequest.author'} =
                   16888:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16889:                                                   'reload','requestauthor',
                   16890:                                                   \%userenv,\%domdef,\%is_adv);
                   16891:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16892:                                                  $domain,$username);
                   16893:             my $reqstatus = $reqauthor{'author_status'};
                   16894:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16895:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16896:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16897:                                                       $reqauthor{'author'}{'timestamp'};
                   16898:                 }
1.1075.2.14  raeburn  16899:             }
                   16900:         }
                   16901: 
1.462     albertel 16902: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16903: 
1.462     albertel 16904: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16905: 		 &GDBM_WRCREAT(),0640)) {
                   16906: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16907: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16908: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16909:             if (ref($firstaccenv) eq 'HASH') {
                   16910:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16911:             }
                   16912:             if (ref($timerintenv) eq 'HASH') {
                   16913:                 &_add_to_env(\%disk_env,$timerintenv);
                   16914:             }
1.463     albertel 16915: 	    if (ref($args->{'extra_env'})) {
                   16916: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16917: 	    }
1.462     albertel 16918: 	    untie(%disk_env);
                   16919: 	} else {
1.705     tempelho 16920: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16921: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16922: 	    return 'error: '.$!;
                   16923: 	}
                   16924:     }
                   16925:     $env{'request.role'}='cm';
                   16926:     $env{'request.role.adv'}=$env{'user.adv'};
                   16927:     $env{'browser.type'}=$clientbrowser;
                   16928: 
                   16929:     return $cookie;
                   16930: 
                   16931: }
                   16932: 
                   16933: sub _add_to_env {
                   16934:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16935:     if (ref($env_data) eq 'HASH') {
                   16936:         while (my ($key,$value) = each(%$env_data)) {
                   16937: 	    $idf->{$prefix.$key} = $value;
                   16938: 	    $env{$prefix.$key}   = $value;
                   16939:         }
1.462     albertel 16940:     }
                   16941: }
                   16942: 
1.685     tempelho 16943: # --- Get the symbolic name of a problem and the url
                   16944: sub get_symb {
                   16945:     my ($request,$silent) = @_;
1.726     raeburn  16946:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16947:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16948:     if ($symb eq '') {
                   16949:         if (!$silent) {
1.1071    raeburn  16950:             if (ref($request)) { 
                   16951:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16952:             }
1.685     tempelho 16953:             return ();
                   16954:         }
                   16955:     }
                   16956:     &Apache::lonenc::check_decrypt(\$symb);
                   16957:     return ($symb);
                   16958: }
                   16959: 
                   16960: # --------------------------------------------------------------Get annotation
                   16961: 
                   16962: sub get_annotation {
                   16963:     my ($symb,$enc) = @_;
                   16964: 
                   16965:     my $key = $symb;
                   16966:     if (!$enc) {
                   16967:         $key =
                   16968:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16969:     }
                   16970:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16971:     return $annotation{$key};
                   16972: }
                   16973: 
                   16974: sub clean_symb {
1.731     raeburn  16975:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16976: 
                   16977:     &Apache::lonenc::check_decrypt(\$symb);
                   16978:     my $enc = $env{'request.enc'};
1.731     raeburn  16979:     if ($delete_enc) {
1.730     raeburn  16980:         delete($env{'request.enc'});
                   16981:     }
1.685     tempelho 16982: 
                   16983:     return ($symb,$enc);
                   16984: }
1.462     albertel 16985: 
1.1075.2.69  raeburn  16986: ############################################################
                   16987: ############################################################
                   16988: 
                   16989: =pod
                   16990: 
                   16991: =head1 Routines for building display used to search for courses
                   16992: 
                   16993: 
                   16994: =over 4
                   16995: 
                   16996: =item * &build_filters()
                   16997: 
                   16998: Create markup for a table used to set filters to use when selecting
                   16999: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17000: and quotacheck.pl
                   17001: 
                   17002: 
                   17003: Inputs:
                   17004: 
                   17005: filterlist - anonymous array of fields to include as potential filters
                   17006: 
                   17007: crstype - course type
                   17008: 
                   17009: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17010:               to pop-open a course selector (will contain "extra element").
                   17011: 
                   17012: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17013: 
                   17014: filter - anonymous hash of criteria and their values
                   17015: 
                   17016: action - form action
                   17017: 
                   17018: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17019: 
                   17020: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   17021: 
                   17022: cloneruname - username of owner of new course who wants to clone
                   17023: 
                   17024: clonerudom - domain of owner of new course who wants to clone
                   17025: 
                   17026: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   17027: 
                   17028: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17029: 
                   17030: codedom - domain
                   17031: 
                   17032: formname - value of form element named "form".
                   17033: 
                   17034: fixeddom - domain, if fixed.
                   17035: 
                   17036: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   17037: 
                   17038: cnameelement - name of form element in form on opener page which will receive title of selected course
                   17039: 
                   17040: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17041: 
                   17042: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17043: 
                   17044: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17045: 
                   17046: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17047: 
                   17048: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17049: 
                   17050: 
                   17051: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17052: 
                   17053: 
                   17054: Side Effects: None
                   17055: 
                   17056: =cut
                   17057: 
                   17058: # ---------------------------------------------- search for courses based on last activity etc.
                   17059: 
                   17060: sub build_filters {
                   17061:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17062:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17063:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17064:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17065:         $clonetext,$clonewarning) = @_;
                   17066:     my ($list,$jscript);
                   17067:     my $onchange = 'javascript:updateFilters(this)';
                   17068:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17069:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17070:         $typeselectform,$instcodetitle);
                   17071:     if ($formname eq '') {
                   17072:         $formname = $caller;
                   17073:     }
                   17074:     foreach my $item (@{$filterlist}) {
                   17075:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17076:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17077:             if ($item eq 'domainfilter') {
                   17078:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17079:             } elsif ($item eq 'coursefilter') {
                   17080:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17081:             } elsif ($item eq 'ownerfilter') {
                   17082:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17083:             } elsif ($item eq 'ownerdomfilter') {
                   17084:                 $filter->{'ownerdomfilter'} =
                   17085:                     &LONCAPA::clean_domain($filter->{$item});
                   17086:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17087:                                                        'ownerdomfilter',1);
                   17088:             } elsif ($item eq 'personfilter') {
                   17089:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17090:             } elsif ($item eq 'persondomfilter') {
                   17091:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17092:                                                         'persondomfilter',1);
                   17093:             } else {
                   17094:                 $filter->{$item} =~ s/\W//g;
                   17095:             }
                   17096:             if (!$filter->{$item}) {
                   17097:                 $filter->{$item} = '';
                   17098:             }
                   17099:         }
                   17100:         if ($item eq 'domainfilter') {
                   17101:             my $allow_blank = 1;
                   17102:             if ($formname eq 'portform') {
                   17103:                 $allow_blank=0;
                   17104:             } elsif ($formname eq 'studentform') {
                   17105:                 $allow_blank=0;
                   17106:             }
                   17107:             if ($fixeddom) {
                   17108:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17109:                                     ' value="'.$codedom.'" />'.
                   17110:                                     &Apache::lonnet::domain($codedom,'description');
                   17111:             } else {
                   17112:                 $domainselectform = &select_dom_form($filter->{$item},
                   17113:                                                      'domainfilter',
                   17114:                                                       $allow_blank,'',$onchange);
                   17115:             }
                   17116:         } else {
                   17117:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17118:         }
                   17119:     }
                   17120: 
                   17121:     # last course activity filter and selection
                   17122:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17123: 
                   17124:     # course created filter and selection
                   17125:     if (exists($filter->{'createdfilter'})) {
                   17126:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17127:     }
                   17128: 
                   17129:     my %lt = &Apache::lonlocal::texthash(
                   17130:                 'cac' => "$crstype Activity",
                   17131:                 'ccr' => "$crstype Created",
                   17132:                 'cde' => "$crstype Title",
                   17133:                 'cdo' => "$crstype Domain",
                   17134:                 'ins' => 'Institutional Code',
                   17135:                 'inc' => 'Institutional Categorization',
                   17136:                 'cow' => "$crstype Owner/Co-owner",
                   17137:                 'cop' => "$crstype Personnel Includes",
                   17138:                 'cog' => 'Type',
                   17139:              );
                   17140: 
                   17141:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17142:         my $typeval = 'Course';
                   17143:         if ($crstype eq 'Community') {
                   17144:             $typeval = 'Community';
                   17145:         }
                   17146:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17147:     } else {
                   17148:         $typeselectform =  '<select name="type" size="1"';
                   17149:         if ($onchange) {
                   17150:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17151:         }
                   17152:         $typeselectform .= '>'."\n";
                   17153:         foreach my $posstype ('Course','Community') {
                   17154:             $typeselectform.='<option value="'.$posstype.'"'.
                   17155:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17156:         }
                   17157:         $typeselectform.="</select>";
                   17158:     }
                   17159: 
                   17160:     my ($cloneableonlyform,$cloneabletitle);
                   17161:     if (exists($filter->{'cloneableonly'})) {
                   17162:         my $cloneableon = '';
                   17163:         my $cloneableoff = ' checked="checked"';
                   17164:         if ($filter->{'cloneableonly'}) {
                   17165:             $cloneableon = $cloneableoff;
                   17166:             $cloneableoff = '';
                   17167:         }
                   17168:         $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>';
                   17169:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17170:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17171:         } else {
                   17172:             $cloneabletitle = &mt('Cloneable by you');
                   17173:         }
                   17174:     }
                   17175:     my $officialjs;
                   17176:     if ($crstype eq 'Course') {
                   17177:         if (exists($filter->{'instcodefilter'})) {
                   17178: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17179: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17180:             if ($codedom) {
                   17181:                 $officialjs = 1;
                   17182:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17183:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17184:                                                                   $officialjs,$codetitlesref);
                   17185:                 if ($jscript) {
                   17186:                     $jscript = '<script type="text/javascript">'."\n".
                   17187:                                '// <![CDATA['."\n".
                   17188:                                $jscript."\n".
                   17189:                                '// ]]>'."\n".
                   17190:                                '</script>'."\n";
                   17191:                 }
                   17192:             }
                   17193:             if ($instcodeform eq '') {
                   17194:                 $instcodeform =
                   17195:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17196:                     $list->{'instcodefilter'}.'" />';
                   17197:                 $instcodetitle = $lt{'ins'};
                   17198:             } else {
                   17199:                 $instcodetitle = $lt{'inc'};
                   17200:             }
                   17201:             if ($fixeddom) {
                   17202:                 $instcodetitle .= '<br />('.$codedom.')';
                   17203:             }
                   17204:         }
                   17205:     }
                   17206:     my $output = qq|
                   17207: <form method="post" name="filterpicker" action="$action">
                   17208: <input type="hidden" name="form" value="$formname" />
                   17209: |;
                   17210:     if ($formname eq 'modifycourse') {
                   17211:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17212:                    '<input type="hidden" name="prevphase" value="'.
                   17213:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17214:     } elsif ($formname eq 'quotacheck') {
                   17215:         $output .= qq|
                   17216: <input type="hidden" name="sortby" value="" />
                   17217: <input type="hidden" name="sortorder" value="" />
                   17218: |;
                   17219:     } else {
1.1075.2.69  raeburn  17220:         my $name_input;
                   17221:         if ($cnameelement ne '') {
                   17222:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17223:                           $cnameelement.'" />';
                   17224:         }
                   17225:         $output .= qq|
                   17226: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17227: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17228: $name_input
                   17229: $roleelement
                   17230: $multelement
                   17231: $typeelement
                   17232: |;
                   17233:         if ($formname eq 'portform') {
                   17234:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17235:         }
                   17236:     }
                   17237:     if ($fixeddom) {
                   17238:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17239:     }
                   17240:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17241:     if ($sincefilterform) {
                   17242:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17243:                   .$sincefilterform
                   17244:                   .&Apache::lonhtmlcommon::row_closure();
                   17245:     }
                   17246:     if ($createdfilterform) {
                   17247:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17248:                   .$createdfilterform
                   17249:                   .&Apache::lonhtmlcommon::row_closure();
                   17250:     }
                   17251:     if ($domainselectform) {
                   17252:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17253:                   .$domainselectform
                   17254:                   .&Apache::lonhtmlcommon::row_closure();
                   17255:     }
                   17256:     if ($typeselectform) {
                   17257:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17258:             $output .= $typeselectform;
                   17259:         } else {
                   17260:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17261:                       .$typeselectform
                   17262:                       .&Apache::lonhtmlcommon::row_closure();
                   17263:         }
                   17264:     }
                   17265:     if ($instcodeform) {
                   17266:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17267:                   .$instcodeform
                   17268:                   .&Apache::lonhtmlcommon::row_closure();
                   17269:     }
                   17270:     if (exists($filter->{'ownerfilter'})) {
                   17271:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17272:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17273:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17274:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17275:                    $ownerdomselectform.'</td></tr></table>'.
                   17276:                    &Apache::lonhtmlcommon::row_closure();
                   17277:     }
                   17278:     if (exists($filter->{'personfilter'})) {
                   17279:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17280:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17281:                    '<input type="text" name="personfilter" size="20" value="'.
                   17282:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17283:                    $persondomselectform.'</td></tr></table>'.
                   17284:                    &Apache::lonhtmlcommon::row_closure();
                   17285:     }
                   17286:     if (exists($filter->{'coursefilter'})) {
                   17287:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17288:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17289:                   .$list->{'coursefilter'}.'" />'
                   17290:                   .&Apache::lonhtmlcommon::row_closure();
                   17291:     }
                   17292:     if ($cloneableonlyform) {
                   17293:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17294:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17295:     }
                   17296:     if (exists($filter->{'descriptfilter'})) {
                   17297:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17298:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17299:                   .$list->{'descriptfilter'}.'" />'
                   17300:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17301:     }
                   17302:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17303:                '<input type="hidden" name="updater" value="" />'."\n".
                   17304:                '<input type="submit" name="gosearch" value="'.
                   17305:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17306:     return $jscript.$clonewarning.$output;
                   17307: }
                   17308: 
                   17309: =pod
                   17310: 
                   17311: =item * &timebased_select_form()
                   17312: 
                   17313: Create markup for a dropdown list used to select a time-based
                   17314: filter e.g., Course Activity, Course Created, when searching for courses
                   17315: or communities
                   17316: 
                   17317: Inputs:
                   17318: 
                   17319: item - name of form element (sincefilter or createdfilter)
                   17320: 
                   17321: filter - anonymous hash of criteria and their values
                   17322: 
                   17323: Returns: HTML for a select box contained a blank, then six time selections,
                   17324:          with value set in incoming form variables currently selected.
                   17325: 
                   17326: Side Effects: None
                   17327: 
                   17328: =cut
                   17329: 
                   17330: sub timebased_select_form {
                   17331:     my ($item,$filter) = @_;
                   17332:     if (ref($filter) eq 'HASH') {
                   17333:         $filter->{$item} =~ s/[^\d-]//g;
                   17334:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17335:         return &select_form(
                   17336:                             $filter->{$item},
                   17337:                             $item,
                   17338:                             {      '-1' => '',
                   17339:                                 '86400' => &mt('today'),
                   17340:                                '604800' => &mt('last week'),
                   17341:                               '2592000' => &mt('last month'),
                   17342:                               '7776000' => &mt('last three months'),
                   17343:                              '15552000' => &mt('last six months'),
                   17344:                              '31104000' => &mt('last year'),
                   17345:                     'select_form_order' =>
                   17346:                            ['-1','86400','604800','2592000','7776000',
                   17347:                             '15552000','31104000']});
                   17348:     }
                   17349: }
                   17350: 
                   17351: =pod
                   17352: 
                   17353: =item * &js_changer()
                   17354: 
                   17355: Create script tag containing Javascript used to submit course search form
                   17356: when course type or domain is changed, and also to hide 'Searching ...' on
                   17357: page load completion for page showing search result.
                   17358: 
                   17359: Inputs: None
                   17360: 
                   17361: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17362: 
                   17363: Side Effects: None
                   17364: 
                   17365: =cut
                   17366: 
                   17367: sub js_changer {
                   17368:     return <<ENDJS;
                   17369: <script type="text/javascript">
                   17370: // <![CDATA[
                   17371: function updateFilters(caller) {
                   17372:     if (typeof(caller) != "undefined") {
                   17373:         document.filterpicker.updater.value = caller.name;
                   17374:     }
                   17375:     document.filterpicker.submit();
                   17376: }
                   17377: 
                   17378: function hideSearching() {
                   17379:     if (document.getElementById('searching')) {
                   17380:         document.getElementById('searching').style.display = 'none';
                   17381:     }
                   17382:     return;
                   17383: }
                   17384: 
                   17385: // ]]>
                   17386: </script>
                   17387: 
                   17388: ENDJS
                   17389: }
                   17390: 
                   17391: =pod
                   17392: 
                   17393: =item * &search_courses()
                   17394: 
                   17395: Process selected filters form course search form and pass to lonnet::courseiddump
                   17396: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17397: 
                   17398: Inputs:
                   17399: 
                   17400: dom - domain being searched
                   17401: 
                   17402: type - course type ('Course' or 'Community' or '.' if any).
                   17403: 
                   17404: filter - anonymous hash of criteria and their values
                   17405: 
                   17406: numtitles - for institutional codes - number of categories
                   17407: 
                   17408: cloneruname - optional username of new course owner
                   17409: 
                   17410: clonerudom - optional domain of new course owner
                   17411: 
1.1075.2.95  raeburn  17412: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17413:             (used when DC is using course creation form)
                   17414: 
                   17415: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17416: 
1.1075.2.95  raeburn  17417: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17418:            (and so can clone automatically)
                   17419: 
                   17420: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17421: 
                   17422: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17423:               courses to clone
1.1075.2.69  raeburn  17424: 
                   17425: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17426: 
                   17427: 
                   17428: Side Effects: None
                   17429: 
                   17430: =cut
                   17431: 
                   17432: 
                   17433: sub search_courses {
1.1075.2.95  raeburn  17434:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17435:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17436:     my (%courses,%showcourses,$cloner);
                   17437:     if (($filter->{'ownerfilter'} ne '') ||
                   17438:         ($filter->{'ownerdomfilter'} ne '')) {
                   17439:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17440:                                        $filter->{'ownerdomfilter'};
                   17441:     }
                   17442:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17443:         if (!$filter->{$item}) {
                   17444:             $filter->{$item}='.';
                   17445:         }
                   17446:     }
                   17447:     my $now = time;
                   17448:     my $timefilter =
                   17449:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17450:     my ($createdbefore,$createdafter);
                   17451:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17452:         $createdbefore = $now;
                   17453:         $createdafter = $now-$filter->{'createdfilter'};
                   17454:     }
                   17455:     my ($instcodefilter,$regexpok);
                   17456:     if ($numtitles) {
                   17457:         if ($env{'form.official'} eq 'on') {
                   17458:             $instcodefilter =
                   17459:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17460:             $regexpok = 1;
                   17461:         } elsif ($env{'form.official'} eq 'off') {
                   17462:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17463:             unless ($instcodefilter eq '') {
                   17464:                 $regexpok = -1;
                   17465:             }
                   17466:         }
                   17467:     } else {
                   17468:         $instcodefilter = $filter->{'instcodefilter'};
                   17469:     }
                   17470:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17471:     if ($type eq '') { $type = '.'; }
                   17472: 
                   17473:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17474:         $cloner = $cloneruname.':'.$clonerudom;
                   17475:     }
                   17476:     %courses = &Apache::lonnet::courseiddump($dom,
                   17477:                                              $filter->{'descriptfilter'},
                   17478:                                              $timefilter,
                   17479:                                              $instcodefilter,
                   17480:                                              $filter->{'combownerfilter'},
                   17481:                                              $filter->{'coursefilter'},
                   17482:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17483:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17484:                                              $filter->{'cloneableonly'},
                   17485:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17486:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17487:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17488:         my $ccrole;
                   17489:         if ($type eq 'Community') {
                   17490:             $ccrole = 'co';
                   17491:         } else {
                   17492:             $ccrole = 'cc';
                   17493:         }
                   17494:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17495:                                                      $filter->{'persondomfilter'},
                   17496:                                                      'userroles',undef,
                   17497:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17498:                                                      $dom);
                   17499:         foreach my $role (keys(%rolehash)) {
                   17500:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17501:             my $cid = $cdom.'_'.$cnum;
                   17502:             if (exists($courses{$cid})) {
                   17503:                 if (ref($courses{$cid}) eq 'HASH') {
                   17504:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17505:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17506:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17507:                         }
                   17508:                     } else {
                   17509:                         $courses{$cid}{roles} = [$courserole];
                   17510:                     }
                   17511:                     $showcourses{$cid} = $courses{$cid};
                   17512:                 }
                   17513:             }
                   17514:         }
                   17515:         %courses = %showcourses;
                   17516:     }
                   17517:     return %courses;
                   17518: }
                   17519: 
                   17520: =pod
                   17521: 
                   17522: =back
                   17523: 
1.1075.2.88  raeburn  17524: =head1 Routines for version requirements for current course.
                   17525: 
                   17526: =over 4
                   17527: 
                   17528: =item * &check_release_required()
                   17529: 
                   17530: Compares required LON-CAPA version with version on server, and
                   17531: if required version is newer looks for a server with the required version.
                   17532: 
                   17533: Looks first at servers in user's owen domain; if none suitable, looks at
                   17534: servers in course's domain are permitted to host sessions for user's domain.
                   17535: 
                   17536: Inputs:
                   17537: 
                   17538: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17539: 
                   17540: $courseid - Course ID of current course
                   17541: 
                   17542: $rolecode - User's current role in course (for switchserver query string).
                   17543: 
                   17544: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17545: 
                   17546: 
                   17547: Returns:
                   17548: 
                   17549: $switchserver - query string tp append to /adm/switchserver call (if
                   17550:                 current server's LON-CAPA version is too old.
                   17551: 
                   17552: $warning - Message is displayed if no suitable server could be found.
                   17553: 
                   17554: =cut
                   17555: 
                   17556: sub check_release_required {
                   17557:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17558:     my ($switchserver,$warning);
                   17559:     if ($required ne '') {
                   17560:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17561:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17562:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17563:             my $otherserver;
                   17564:             if (($major eq '' && $minor eq '') ||
                   17565:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17566:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17567:                 my $switchlcrev =
                   17568:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17569:                                                            $userdomserver);
                   17570:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17571:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17572:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17573:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17574:                     if ($cdom ne $env{'user.domain'}) {
                   17575:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17576:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17577:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17578:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17579:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17580:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17581:                         my $canhost =
                   17582:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17583:                                                               $coursedomserver,
                   17584:                                                               $remoterev,
                   17585:                                                               $udomdefaults{'remotesessions'},
                   17586:                                                               $defdomdefaults{'hostedsessions'});
                   17587: 
                   17588:                         if ($canhost) {
                   17589:                             $otherserver = $coursedomserver;
                   17590:                         } else {
                   17591:                             $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.");
                   17592:                         }
                   17593:                     } else {
                   17594:                         $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).");
                   17595:                     }
                   17596:                 } else {
                   17597:                     $otherserver = $userdomserver;
                   17598:                 }
                   17599:             }
                   17600:             if ($otherserver ne '') {
                   17601:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17602:             }
                   17603:         }
                   17604:     }
                   17605:     return ($switchserver,$warning);
                   17606: }
                   17607: 
                   17608: =pod
                   17609: 
                   17610: =item * &check_release_result()
                   17611: 
                   17612: Inputs:
                   17613: 
                   17614: $switchwarning - Warning message if no suitable server found to host session.
                   17615: 
                   17616: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17617:                 and current role.
                   17618: 
                   17619: Returns: HTML to display with information about requirement to switch server.
                   17620:          Either displaying warning with link to Roles/Courses screen or
                   17621:          display link to switchserver.
                   17622: 
1.1075.2.69  raeburn  17623: =cut
                   17624: 
1.1075.2.88  raeburn  17625: sub check_release_result {
                   17626:     my ($switchwarning,$switchserver) = @_;
                   17627:     my $output = &start_page('Selected course unavailable on this server').
                   17628:                  '<p class="LC_warning">';
                   17629:     if ($switchwarning) {
                   17630:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17631:         if (&show_course()) {
                   17632:             $output .= &mt('Display courses');
                   17633:         } else {
                   17634:             $output .= &mt('Display roles');
                   17635:         }
                   17636:         $output .= '</a>';
                   17637:     } elsif ($switchserver) {
                   17638:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17639:                    '<br />'.
                   17640:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17641:                    &mt('Switch Server').
                   17642:                    '</a>';
                   17643:     }
                   17644:     $output .= '</p>'.&end_page();
                   17645:     return $output;
                   17646: }
                   17647: 
                   17648: =pod
                   17649: 
                   17650: =item * &needs_coursereinit()
                   17651: 
                   17652: Determine if course contents stored for user's session needs to be
                   17653: refreshed, because content has changed since "Big Hash" last tied.
                   17654: 
                   17655: Check for change is made if time last checked is more than 10 minutes ago
                   17656: (by default).
                   17657: 
                   17658: Inputs:
                   17659: 
                   17660: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17661: 
                   17662: $interval (optional) - Time which may elapse (in s) between last check for content
                   17663:                        change in current course. (default: 600 s).
                   17664: 
                   17665: Returns: an array; first element is:
                   17666: 
                   17667: =over 4
                   17668: 
                   17669: 'switch' - if content updates mean user's session
                   17670:            needs to be switched to a server running a newer LON-CAPA version
                   17671: 
                   17672: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17673:            on current server hosting user's session
                   17674: 
                   17675: ''       - if no action required.
                   17676: 
                   17677: =back
                   17678: 
                   17679: If first item element is 'switch':
                   17680: 
                   17681: second item is $switchwarning - Warning message if no suitable server found to host session.
                   17682: 
                   17683: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17684:                               and current role.
                   17685: 
                   17686: otherwise: no other elements returned.
                   17687: 
                   17688: =back
                   17689: 
                   17690: =cut
                   17691: 
                   17692: sub needs_coursereinit {
                   17693:     my ($loncaparev,$interval) = @_;
                   17694:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17695:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17696:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17697:     my $now = time;
                   17698:     if ($interval eq '') {
                   17699:         $interval = 600;
                   17700:     }
                   17701:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   17702:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 17703:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 17704:21):         if ($blocked) {
                   17705:21):             return ();
                   17706:21):         }
          .13(raeb 17707:-23):         my $update;
                   17708:-23):         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17709:-23):         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   17710:-23):         if ($lastmainchange > $env{'request.course.tied'}) {
                   17711:-23):             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   17712:-23):             if ($needswitch) {
                   17713:-23):                 return ('switch',$switchwarning,$switchserver);
                   17714:-23):             }
                   17715:-23):             $update = 'main';
                   17716:-23):         }
                   17717:-23):         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   17718:-23):             if ($update) {
                   17719:-23):                 $update = 'both';
                   17720:-23):             } else {
                   17721:-23):                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   17722:-23):                 if ($needswitch) {
                   17723:-23):                     return ('switch',$switchwarning,$switchserver);
                   17724:-23):                 } else {
                   17725:-23):                     $update = 'supp';
1.1075.2.88  raeburn  17726:                 }
                   17727:             }
1.1075.2.161.  .13(raeb 17728:-23):             return ($update);
                   17729:-23):         }
                   17730:-23):     }
                   17731:-23):     return ();
                   17732:-23): }
                   17733:-23): 
                   17734:-23): sub switch_for_update {
                   17735:-23):     my ($loncaparev,$cdom,$cnum) = @_;
                   17736:-23):     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17737:-23):     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17738:-23):         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17739:-23):         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17740:-23):             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17741:-23):                                     $curr_reqd_hash{'internal.releaserequired'}});
                   17742:-23):             my ($switchserver,$switchwarning) =
                   17743:-23):                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17744:-23):                                         $curr_reqd_hash{'internal.releaserequired'});
                   17745:-23):             if ($switchwarning ne '' || $switchserver ne '') {
                   17746:-23):                 return ('switch',$switchwarning,$switchserver);
                   17747:-23):             }
1.1075.2.88  raeburn  17748:         }
                   17749:     }
                   17750:     return ();
                   17751: }
1.1075.2.69  raeburn  17752: 
1.1075.2.11  raeburn  17753: sub update_content_constraints {
                   17754:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17755:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17756:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17757:     my %checkresponsetypes;
                   17758:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   17759:         my ($item,$name,$value) = split(/:/,$key);
                   17760:         if ($item eq 'resourcetag') {
                   17761:             if ($name eq 'responsetype') {
                   17762:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17763:             }
                   17764:         }
                   17765:     }
                   17766:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17767:     if (defined($navmap)) {
                   17768:         my %allresponses;
                   17769:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17770:             my %responses = $res->responseTypes();
                   17771:             foreach my $key (keys(%responses)) {
                   17772:                 next unless(exists($checkresponsetypes{$key}));
                   17773:                 $allresponses{$key} += $responses{$key};
                   17774:             }
                   17775:         }
                   17776:         foreach my $key (keys(%allresponses)) {
                   17777:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17778:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17779:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17780:             }
                   17781:         }
                   17782:         undef($navmap);
                   17783:     }
                   17784:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17785:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17786:     }
                   17787:     return;
                   17788: }
                   17789: 
1.1075.2.27  raeburn  17790: sub allmaps_incourse {
                   17791:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17792:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17793:         $cid = $env{'request.course.id'};
                   17794:         $cdom = $env{'course.'.$cid.'.domain'};
                   17795:         $cnum = $env{'course.'.$cid.'.num'};
                   17796:         $chome = $env{'course.'.$cid.'.home'};
                   17797:     }
                   17798:     my %allmaps = ();
                   17799:     my $lastchange =
                   17800:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17801:     if ($lastchange > $env{'request.course.tied'}) {
                   17802:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17803:         unless ($ferr) {
                   17804:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17805:         }
                   17806:     }
                   17807:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17808:     if (defined($navmap)) {
                   17809:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17810:             $allmaps{$res->src()} = 1;
                   17811:         }
                   17812:     }
                   17813:     return \%allmaps;
                   17814: }
                   17815: 
1.1075.2.11  raeburn  17816: sub parse_supplemental_title {
                   17817:     my ($title) = @_;
                   17818: 
                   17819:     my ($foldertitle,$renametitle);
                   17820:     if ($title =~ /&amp;&amp;&amp;/) {
                   17821:         $title = &HTML::Entites::decode($title);
                   17822:     }
                   17823:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17824:         $renametitle=$4;
                   17825:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17826:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17827:         my $name =  &plainname($uname,$udom);
                   17828:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17829:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1075.2.161.  .16(raeb 17830:-23):         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
                   17831:-23):         if ($foldertitle ne '') {
                   17832:-23):             $title .= ': <br />'.$foldertitle;
                   17833:-23):         }
1.1075.2.11  raeburn  17834:     }
                   17835:     if (wantarray) {
                   17836:         return ($title,$foldertitle,$renametitle);
                   17837:     }
                   17838:     return $title;
                   17839: }
                   17840: 
1.1075.2.161.  .13(raeb 17841:-23): sub get_supplemental {
                   17842:-23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   17843:-23):     my $hashid=$cnum.':'.$cdom;
                   17844:-23):     my ($supplemental,$cached,$set_httprefs);
                   17845:-23):     unless ($ignorecache) {
                   17846:-23):         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   17847:-23):     }
                   17848:-23):     unless (defined($cached)) {
                   17849:-23):         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   17850:-23):         unless ($chome eq 'no_host') {
                   17851:-23):             my @order = @LONCAPA::map::order;
                   17852:-23):             my @resources = @LONCAPA::map::resources;
                   17853:-23):             my @resparms = @LONCAPA::map::resparms;
                   17854:-23):             my @zombies = @LONCAPA::map::zombies;
                   17855:-23):             my ($errors,%ids,%hidden);
                   17856:-23):             $errors =
                   17857:-23):                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   17858:-23):                                       $errors,$possdel,\%ids,\%hidden);
                   17859:-23):             @LONCAPA::map::order = @order;
                   17860:-23):             @LONCAPA::map::resources = @resources;
                   17861:-23):             @LONCAPA::map::resparms = @resparms;
                   17862:-23):             @LONCAPA::map::zombies = @zombies;
                   17863:-23):             $set_httprefs = 1;
                   17864:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   17865:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   17866:-23):             }
                   17867:-23):             $supplemental = {
                   17868:-23):                                ids => \%ids,
                   17869:-23):                                hidden => \%hidden,
                   17870:-23):                             };
                   17871:-23):             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   17872:-23):         }
                   17873:-23):     }
                   17874:-23):     return ($supplemental,$set_httprefs);
                   17875:-23): }
                   17876:-23): 
1.1075.2.43  raeburn  17877: sub recurse_supplemental {
1.1075.2.161.  .13(raeb 17878:-23):     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   17879:-23):     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   17880:-23):         my $mapnum;
                   17881:-23):         if ($suppmap eq 'supplemental.sequence') {
                   17882:-23):             $mapnum = 0;
                   17883:-23):         } else {
                   17884:-23):             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   17885:-23):         }
1.1075.2.43  raeburn  17886:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17887:         if ($fatal) {
                   17888:             $errors ++;
                   17889:         } else {
1.1075.2.161.  .13(raeb 17890:-23):             my @order = @LONCAPA::map::order;
                   17891:-23):             if (@order > 0) {
                   17892:-23):                 my @resources = @LONCAPA::map::resources;
                   17893:-23):                 my @resparms = @LONCAPA::map::resparms;
                   17894:-23):                 foreach my $idx (@order) {
                   17895:-23):                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1075.2.43  raeburn  17896:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.161.  .13(raeb 17897:-23):                         my $id = $mapnum.':'.$idx;
                   17898:-23):                         push(@{$suppids->{$src}},$id);
                   17899:-23):                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   17900:-23):                             $hiddensupp->{$id} = 1;
                   17901:-23):                         }
1.1075.2.46  raeburn  17902:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1075.2.161.  .13(raeb 17903:-23):                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   17904:-23):                                                             $hiddensupp,$hiddensupp->{$id});
1.1075.2.43  raeburn  17905:                         } else {
1.1075.2.161.  .13(raeb 17906:-23):                             my $allowed;
                   17907:-23):                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   17908:-23):                                 $allowed = 1;
                   17909:-23):                             } elsif ($possdel) {
                   17910:-23):                                 foreach my $item (@{$suppids->{$src}}) {
                   17911:-23):                                     next if ($item eq $id);
                   17912:-23):                                     unless ($hiddensupp->{$item}) {
                   17913:-23):                                        $allowed = 1;
                   17914:-23):                                        last;
                   17915:-23):                                     }
                   17916:-23):                                 }
                   17917:-23):                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   17918:-23):                                     &Apache::lonnet::delenv('httpref.'.$src);
                   17919:-23):                                 }
                   17920:-23):                             }
                   17921:-23):                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   17922:-23):                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   17923:-23):                             }
                   17924:-23):                         }
                   17925:-23):                     }
                   17926:-23):                 }
                   17927:-23):             }
                   17928:-23):         }
                   17929:-23):     }
                   17930:-23):     return $errors;
                   17931:-23): }
                   17932:-23): 
                   17933:-23): sub set_supp_httprefs {
                   17934:-23):     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   17935:-23):     if (ref($supplemental) eq 'HASH') {
                   17936:-23):         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   17937:-23):             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   17938:-23):                 next if ($src =~ /\.sequence$/);
                   17939:-23):                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   17940:-23):                     my $allowed;
                   17941:-23):                     if ($env{'request.role.adv'}) {
                   17942:-23):                         $allowed = 1;
                   17943:-23):                     } else {
                   17944:-23):                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   17945:-23):                             unless ($supplemental->{'hidden'}->{$id}) {
                   17946:-23):                                 $allowed = 1;
                   17947:-23):                                 last;
                   17948:-23):                             }
                   17949:-23):                         }
                   17950:-23):                     }
                   17951:-23):                     if (exists($env{'httpref.'.$src})) {
                   17952:-23):                         if ($possdel) {
                   17953:-23):                             unless ($allowed) {
                   17954:-23):                                 &Apache::lonnet::delenv('httpref.'.$src);
                   17955:-23):                             }
1.1075.2.43  raeburn  17956:                         }
1.1075.2.161.  .13(raeb 17957:-23):                     } elsif ($allowed) {
                   17958:-23):                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1075.2.43  raeburn  17959:                     }
                   17960:                 }
                   17961:             }
1.1075.2.161.  .13(raeb 17962:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   17963:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   17964:-23):             }
1.1075.2.43  raeburn  17965:         }
                   17966:     }
1.1075.2.161.  .13(raeb 17967:-23): }
                   17968:-23): 
                   17969:-23): sub get_supp_parameter {
                   17970:-23):     my ($resparm,$name)=@_;
                   17971:-23):     return if ($resparm eq '');
                   17972:-23):     my $value=undef;
                   17973:-23):     my $ptype=undef;
                   17974:-23):     foreach (split('&&&',$resparm)) {
                   17975:-23):         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   17976:-23):         if ($thisname eq $name) {
                   17977:-23):             $value=$thisvalue;
                   17978:-23):             $ptype=$thistype;
                   17979:-23):         }
                   17980:-23):     }
                   17981:-23):     return $value;
1.1075.2.43  raeburn  17982: }
                   17983: 
1.1075.2.18  raeburn  17984: sub symb_to_docspath {
1.1075.2.119  raeburn  17985:     my ($symb,$navmapref) = @_;
                   17986:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  17987:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17988:     if ($resurl=~/\.(sequence|page)$/) {
                   17989:         $mapurl=$resurl;
                   17990:     } elsif ($resurl eq 'adm/navmaps') {
                   17991:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17992:     }
                   17993:     my $mapresobj;
1.1075.2.119  raeburn  17994:     unless (ref($$navmapref)) {
                   17995:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17996:     }
                   17997:     if (ref($$navmapref)) {
                   17998:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  17999:     }
                   18000:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18001:     my $type=$2;
                   18002:     my $path;
                   18003:     if (ref($mapresobj)) {
                   18004:         my $pcslist = $mapresobj->map_hierarchy();
                   18005:         if ($pcslist ne '') {
                   18006:             foreach my $pc (split(/,/,$pcslist)) {
                   18007:                 next if ($pc <= 1);
1.1075.2.119  raeburn  18008:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  18009:                 if (ref($res)) {
                   18010:                     my $thisurl = $res->src();
                   18011:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18012:                     my $thistitle = $res->title();
                   18013:                     $path .= '&'.
                   18014:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  18015:                              &escape($thistitle).
1.1075.2.18  raeburn  18016:                              ':'.$res->randompick().
                   18017:                              ':'.$res->randomout().
                   18018:                              ':'.$res->encrypted().
                   18019:                              ':'.$res->randomorder().
                   18020:                              ':'.$res->is_page();
                   18021:                 }
                   18022:             }
                   18023:         }
                   18024:         $path =~ s/^\&//;
                   18025:         my $maptitle = $mapresobj->title();
                   18026:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18027:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18028:         }
                   18029:         $path .= (($path ne '')? '&' : '').
                   18030:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18031:                  &escape($maptitle).
1.1075.2.18  raeburn  18032:                  ':'.$mapresobj->randompick().
                   18033:                  ':'.$mapresobj->randomout().
                   18034:                  ':'.$mapresobj->encrypted().
                   18035:                  ':'.$mapresobj->randomorder().
                   18036:                  ':'.$mapresobj->is_page();
                   18037:     } else {
                   18038:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18039:         my $ispage = (($type eq 'page')? 1 : '');
                   18040:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18041:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18042:         }
                   18043:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18044:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  18045:     }
                   18046:     unless ($mapurl eq 'default') {
                   18047:         $path = 'default&'.
1.1075.2.46  raeburn  18048:                 &escape('Main Content').
1.1075.2.18  raeburn  18049:                 ':::::&'.$path;
                   18050:     }
                   18051:     return $path;
                   18052: }
                   18053: 
1.1075.2.161.  .13(raeb 18054:-23): sub validate_folderpath {
                   18055:-23):     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18056:-23):     if ($env{'form.folderpath'} ne '') {
                   18057:-23):         my @items = split(/\&/,$env{'form.folderpath'});
                   18058:-23):         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
                   18059:-23):         for (my $i=0; $i<@items; $i++) {
                   18060:-23):             my $odd = $i%2;
                   18061:-23):             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18062:-23):                 $badpath = 1;
                   18063:-23):             } elsif ($odd && $supplementalflag) {
                   18064:-23):                 my $idx = $i-1;
                   18065:-23):                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18066:-23):                     my $esc_name = $1;
                   18067:-23):                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18068:-23):                         $supppath .= '&'.$esc_name;
                   18069:-23):                         $changed = 1;
                   18070:-23):                     } else {
                   18071:-23):                         $supppath .= '&'.$items[$i];
                   18072:-23):                     }
                   18073:-23):                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18074:-23):                     $changed = 1;
                   18075:-23):                     my $is_hidden;
                   18076:-23):                     unless ($got_supp) {
                   18077:-23):                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
                   18078:-23):                         if (ref($supplemental) eq 'HASH') {
                   18079:-23):                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18080:-23):                                 %supphidden = %{$supplemental->{'hidden'}};
                   18081:-23):                             }
                   18082:-23):                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18083:-23):                                 %suppids = %{$supplemental->{'ids'}};
                   18084:-23):                             }
                   18085:-23):                         }
                   18086:-23):                         $got_supp = 1;
                   18087:-23):                     }
                   18088:-23):                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18089:-23):                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18090:-23):                         if ($supphidden{$mapid}) {
                   18091:-23):                             $is_hidden = 1;
                   18092:-23):                         }
                   18093:-23):                     }
                   18094:-23):                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18095:-23):                 } else {
                   18096:-23):                     $supppath .= '&'.$items[$i];
                   18097:-23):                 }
                   18098:-23):             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18099:-23):                 $badpath = 1;
                   18100:-23):             } elsif ($supplementalflag) {
                   18101:-23):                 $supppath .= '&'.$items[$i];
                   18102:-23):             }
                   18103:-23):             last if ($badpath);
                   18104:-23):         }
                   18105:-23):         if ($badpath) {
                   18106:-23):             delete($env{'form.folderpath'});
                   18107:-23):         } elsif ($changed && $supplementalflag) {
                   18108:-23):             $supppath =~ s/^\&//;
                   18109:-23):             $env{'form.folderpath'} = $supppath;
                   18110:-23):         }
                   18111:-23):     }
                   18112:-23):     return;
                   18113:-23): }
                   18114:-23): 
1.1075.2.14  raeburn  18115: sub captcha_display {
1.1075.2.137  raeburn  18116:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18117:     my ($output,$error);
1.1075.2.107  raeburn  18118:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  18119:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18120:     if ($captcha eq 'original') {
                   18121:         $output = &create_captcha();
                   18122:         unless ($output) {
                   18123:             $error = 'captcha';
                   18124:         }
                   18125:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18126:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  18127:         unless ($output) {
                   18128:             $error = 'recaptcha';
                   18129:         }
                   18130:     }
1.1075.2.107  raeburn  18131:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  18132: }
                   18133: 
                   18134: sub captcha_response {
1.1075.2.137  raeburn  18135:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18136:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  18137:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18138:     if ($captcha eq 'original') {
                   18139:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18140:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18141:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  18142:     } else {
                   18143:         $captcha_chk = 1;
                   18144:     }
                   18145:     return ($captcha_chk,$captcha_error);
                   18146: }
                   18147: 
                   18148: sub get_captcha_config {
1.1075.2.137  raeburn  18149:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  18150:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  18151:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18152:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18153:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18154:     if ($context eq 'usercreation') {
                   18155:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18156:         if (ref($domconfig{$context}) eq 'HASH') {
                   18157:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18158:             if (ref($hashtocheck) eq 'HASH') {
                   18159:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18160:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18161:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18162:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18163:                     }
                   18164:                     if ($privkey && $pubkey) {
                   18165:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  18166:                         $version = $hashtocheck->{'recaptchaversion'};
                   18167:                         if ($version ne '2') {
                   18168:                             $version = 1;
                   18169:                         }
1.1075.2.14  raeburn  18170:                     } else {
                   18171:                         $captcha = 'original';
                   18172:                     }
                   18173:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18174:                     $captcha = 'original';
                   18175:                 }
                   18176:             }
                   18177:         } else {
                   18178:             $captcha = 'captcha';
                   18179:         }
                   18180:     } elsif ($context eq 'login') {
                   18181:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18182:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18183:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18184:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   18185:             if ($privkey && $pubkey) {
                   18186:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  18187:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18188:                 if ($version ne '2') {
                   18189:                     $version = 1;
                   18190:                 }
1.1075.2.14  raeburn  18191:             } else {
                   18192:                 $captcha = 'original';
                   18193:             }
                   18194:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18195:             $captcha = 'original';
                   18196:         }
1.1075.2.137  raeburn  18197:     } elsif ($context eq 'passwords') {
                   18198:         if ($dom_in_effect) {
                   18199:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18200:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18201:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18202:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18203:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18204:                 }
                   18205:                 if ($privkey && $pubkey) {
                   18206:                     $captcha = 'recaptcha';
                   18207:                     $version = $passwdconf{'recaptchaversion'};
                   18208:                     if ($version ne '2') {
                   18209:                         $version = 1;
                   18210:                     }
                   18211:                 } else {
                   18212:                     $captcha = 'original';
                   18213:                 }
                   18214:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18215:                 $captcha = 'original';
                   18216:             }
                   18217:         }
1.1075.2.14  raeburn  18218:     }
1.1075.2.107  raeburn  18219:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  18220: }
                   18221: 
                   18222: sub create_captcha {
                   18223:     my %captcha_params = &captcha_settings();
                   18224:     my ($output,$maxtries,$tries) = ('',10,0);
                   18225:     while ($tries < $maxtries) {
                   18226:         $tries ++;
                   18227:         my $captcha = Authen::Captcha->new (
                   18228:                                            output_folder => $captcha_params{'output_dir'},
                   18229:                                            data_folder   => $captcha_params{'db_dir'},
                   18230:                                           );
                   18231:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18232: 
                   18233:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18234:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  18235:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  18236:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.161.  .15(raeb 18237:-23):                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1075.2.158  raeburn  18238:                       '</span><br />'.
1.1075.2.66  raeburn  18239:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  18240:             last;
                   18241:         }
                   18242:     }
1.1075.2.158  raeburn  18243:     if ($output eq '') {
                   18244:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18245:     }
1.1075.2.14  raeburn  18246:     return $output;
                   18247: }
                   18248: 
                   18249: sub captcha_settings {
                   18250:     my %captcha_params = (
                   18251:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18252:                            www_output_dir => "/captchaspool",
                   18253:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18254:                            numchars       => '5',
                   18255:                          );
                   18256:     return %captcha_params;
                   18257: }
                   18258: 
                   18259: sub check_captcha {
                   18260:     my ($captcha_chk,$captcha_error);
                   18261:     my $code = $env{'form.code'};
                   18262:     my $md5sum = $env{'form.crypt'};
                   18263:     my %captcha_params = &captcha_settings();
                   18264:     my $captcha = Authen::Captcha->new(
                   18265:                       output_folder => $captcha_params{'output_dir'},
                   18266:                       data_folder   => $captcha_params{'db_dir'},
                   18267:                   );
1.1075.2.26  raeburn  18268:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  18269:     my %captcha_hash = (
                   18270:                         0       => 'Code not checked (file error)',
                   18271:                        -1      => 'Failed: code expired',
                   18272:                        -2      => 'Failed: invalid code (not in database)',
                   18273:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18274:     );
                   18275:     if ($captcha_chk != 1) {
                   18276:         $captcha_error = $captcha_hash{$captcha_chk}
                   18277:     }
                   18278:     return ($captcha_chk,$captcha_error);
                   18279: }
                   18280: 
                   18281: sub create_recaptcha {
1.1075.2.107  raeburn  18282:     my ($pubkey,$version) = @_;
                   18283:     if ($version >= 2) {
1.1075.2.158  raeburn  18284:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18285:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  18286:     } else {
                   18287:         my $use_ssl;
                   18288:         if ($ENV{'SERVER_PORT'} == 443) {
                   18289:             $use_ssl = 1;
                   18290:         }
                   18291:         my $captcha = Captcha::reCAPTCHA->new;
                   18292:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18293:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18294:                &mt('If the text is hard to read, [_1] will replace them.',
                   18295:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18296:                '<br /><br />';
                   18297:      }
1.1075.2.14  raeburn  18298: }
                   18299: 
                   18300: sub check_recaptcha {
1.1075.2.107  raeburn  18301:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  18302:     my $captcha_chk;
1.1075.2.150  raeburn  18303:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  18304:     if ($version >= 2) {
                   18305:         my $ua = LWP::UserAgent->new;
                   18306:         $ua->timeout(10);
                   18307:         my %info = (
                   18308:                      secret   => $privkey,
                   18309:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  18310:                      remoteip => $ip,
1.1075.2.107  raeburn  18311:                    );
                   18312:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   18313:         if ($response->is_success)  {
                   18314:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18315:             if (ref($data) eq 'HASH') {
                   18316:                 if ($data->{'success'}) {
                   18317:                     $captcha_chk = 1;
                   18318:                 }
                   18319:             }
                   18320:         }
                   18321:     } else {
                   18322:         my $captcha = Captcha::reCAPTCHA->new;
                   18323:         my $captcha_result =
                   18324:             $captcha->check_answer(
                   18325:                                     $privkey,
1.1075.2.150  raeburn  18326:                                     $ip,
1.1075.2.107  raeburn  18327:                                     $env{'form.recaptcha_challenge_field'},
                   18328:                                     $env{'form.recaptcha_response_field'},
                   18329:                                   );
                   18330:         if ($captcha_result->{is_valid}) {
                   18331:             $captcha_chk = 1;
                   18332:         }
1.1075.2.14  raeburn  18333:     }
                   18334:     return $captcha_chk;
                   18335: }
                   18336: 
1.1075.2.64  raeburn  18337: sub emailusername_info {
1.1075.2.103  raeburn  18338:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18339:     my %titles = &Apache::lonlocal::texthash (
                   18340:                      lastname      => 'Last Name',
                   18341:                      firstname     => 'First Name',
                   18342:                      institution   => 'School/college/university',
                   18343:                      location      => "School's city, state/province, country",
                   18344:                      web           => "School's web address",
                   18345:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18346:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18347:                  );
                   18348:     return (\@fields,\%titles);
                   18349: }
                   18350: 
1.1075.2.56  raeburn  18351: sub cleanup_html {
                   18352:     my ($incoming) = @_;
                   18353:     my $outgoing;
                   18354:     if ($incoming ne '') {
                   18355:         $outgoing = $incoming;
                   18356:         $outgoing =~ s/;/&#059;/g;
                   18357:         $outgoing =~ s/\#/&#035;/g;
                   18358:         $outgoing =~ s/\&/&#038;/g;
                   18359:         $outgoing =~ s/</&#060;/g;
                   18360:         $outgoing =~ s/>/&#062;/g;
                   18361:         $outgoing =~ s/\(/&#040/g;
                   18362:         $outgoing =~ s/\)/&#041;/g;
                   18363:         $outgoing =~ s/"/&#034;/g;
                   18364:         $outgoing =~ s/'/&#039;/g;
                   18365:         $outgoing =~ s/\$/&#036;/g;
                   18366:         $outgoing =~ s{/}{&#047;}g;
                   18367:         $outgoing =~ s/=/&#061;/g;
                   18368:         $outgoing =~ s/\\/&#092;/g
                   18369:     }
                   18370:     return $outgoing;
                   18371: }
                   18372: 
1.1075.2.74  raeburn  18373: # Checks for critical messages and returns a redirect url if one exists.
                   18374: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18375:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18376: sub critical_redirect {
1.1075.2.161.  .1(raebu 18377:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18378:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18379:         return ();
                   18380:     }
1.1075.2.74  raeburn  18381:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18382:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18383:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18384:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18385:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18386:21):             if ($blocked) {
                   18387:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18388:21):                 if ($env{'request.course.sec'} ne '') {
                   18389:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18390:21):                 }
                   18391:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18392:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18393:21):                     return;
                   18394:21):                 }
                   18395:21):             }
                   18396:21):         }
1.1075.2.74  raeburn  18397:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18398:                                         $env{'user.name'});
                   18399:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18400:         my $redirecturl;
                   18401:         if ($what[0]) {
1.1075.2.158  raeburn  18402:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18403:                 $redirecturl='/adm/email?critical=display';
                   18404:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18405:                 return (1, $url);
                   18406:             }
                   18407:         }
                   18408:     }
                   18409:     return ();
                   18410: }
                   18411: 
1.1075.2.64  raeburn  18412: # Use:
                   18413: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18414: #
                   18415: ##################################################
                   18416: #          password associated functions         #
                   18417: ##################################################
                   18418: sub des_keys {
                   18419:     # Make a new key for DES encryption.
                   18420:     # Each key has two parts which are returned separately.
                   18421:     # Please note:  Each key must be passed through the &hex function
                   18422:     # before it is output to the web browser.  The hex versions cannot
                   18423:     # be used to decrypt.
                   18424:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18425:                 '8','9','a','b','c','d','e','f');
                   18426:     my $lkey='';
                   18427:     for (0..7) {
                   18428:         $lkey.=$hexstr[rand(15)];
                   18429:     }
                   18430:     my $ukey='';
                   18431:     for (0..7) {
                   18432:         $ukey.=$hexstr[rand(15)];
                   18433:     }
                   18434:     return ($lkey,$ukey);
                   18435: }
                   18436: 
                   18437: sub des_decrypt {
                   18438:     my ($key,$cyphertext) = @_;
                   18439:     my $keybin=pack("H16",$key);
                   18440:     my $cypher;
                   18441:     if ($Crypt::DES::VERSION>=2.03) {
                   18442:         $cypher=new Crypt::DES $keybin;
                   18443:     } else {
                   18444:         $cypher=new DES $keybin;
                   18445:     }
1.1075.2.106  raeburn  18446:     my $plaintext='';
                   18447:     my $cypherlength = length($cyphertext);
                   18448:     my $numchunks = int($cypherlength/32);
                   18449:     for (my $j=0; $j<$numchunks; $j++) {
                   18450:         my $start = $j*32;
                   18451:         my $cypherblock = substr($cyphertext,$start,32);
                   18452:         my $chunk =
                   18453:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18454:         $chunk .=
                   18455:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18456:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18457:         $plaintext .= $chunk;
                   18458:     }
1.1075.2.64  raeburn  18459:     return $plaintext;
                   18460: }
                   18461: 
1.1075.2.161.  .1(raebu 18462:21): sub get_requested_shorturls {
                   18463:21):     my ($cdom,$cnum,$navmap) = @_;
                   18464:21):     return unless (ref($navmap));
                   18465:21):     my ($numnew,$errors);
                   18466:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18467:21):     if (@toshorten) {
                   18468:21):         my (%maps,%resources,%titles);
                   18469:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18470:21):                                                                'shorturls',$cdom,$cnum);
                   18471:21):         if (keys(%resources)) {
                   18472:21):             my %tocreate;
                   18473:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18474:21):                 my $symb = $resources{$item};
                   18475:21):                 if ($symb) {
                   18476:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18477:21):                 }
                   18478:21):             }
                   18479:21):             if (keys(%tocreate)) {
                   18480:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18481:21):                                                       \%tocreate);
                   18482:21):             }
                   18483:21):         }
                   18484:21):     }
                   18485:21):     return ($numnew,$errors);
                   18486:21): }
                   18487:21): 
                   18488:21): sub make_short_symbs {
                   18489:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18490:21):     my ($numnew,@errors);
                   18491:21):     if (ref($tocreateref) eq 'HASH') {
                   18492:21):         my %tocreate = %{$tocreateref};
                   18493:21):         if (keys(%tocreate)) {
                   18494:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18495:21):             my $su = Short::URL->new(no_vowels => 1);
                   18496:21):             my $init = '';
                   18497:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   18498:21):             # get lock on tiny db
                   18499:21):             my $now = time;
                   18500:21):             if ($lockuser eq '') {
                   18501:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18502:21):             }
                   18503:21):             my $lockhash = {
                   18504:21):                                 "lock\0$now" => $lockuser,
                   18505:21):                             };
                   18506:21):             my $tries = 0;
                   18507:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18508:21):             my ($code,$error);
                   18509:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   18510:21):                 $tries ++;
                   18511:21):                 sleep 1;
                   18512:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18513:21):             }
                   18514:21):             if ($gotlock eq 'ok') {
                   18515:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18516:21):                                        \%addcourse,\%courseonly,\%failed);
                   18517:21):                 if (keys(%failed)) {
                   18518:21):                     my $numfailed = scalar(keys(%failed));
                   18519:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18520:21):                 }
                   18521:21):                 if (keys(%newunique)) {
                   18522:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18523:21):                     if ($putres eq 'ok') {
                   18524:21):                         $numnew = scalar(keys(%newunique));
                   18525:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18526:21):                         unless ($newputres eq 'ok') {
                   18527:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18528:21):                         }
                   18529:21):                     } else {
                   18530:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18531:21):                     }
                   18532:21):                 }
                   18533:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18534:21):                 unless ($dellockres eq 'ok') {
                   18535:21):                     push(@errors,&mt('error: could not release lockfile'));
                   18536:21):                 }
                   18537:21):             } else {
                   18538:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   18539:21):             }
                   18540:21):             if (keys(%courseonly)) {
                   18541:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18542:21):                 if ($result ne 'ok') {
                   18543:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18544:21):                 }
                   18545:21):             }
                   18546:21):         }
                   18547:21):     }
                   18548:21):     return ($numnew,\@errors);
                   18549:21): }
                   18550:21): 
                   18551:21): sub shorten_symbs {
                   18552:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18553:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18554:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18555:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18556:21):     my (%possibles,%collisions);
                   18557:21):     foreach my $key (keys(%{$tocreate})) {
                   18558:21):         my $num = String::CRC32::crc32($key);
                   18559:21):         my $tiny = $su->encode($num,$init);
                   18560:21):         if ($tiny) {
                   18561:21):             $possibles{$tiny} = $key;
                   18562:21):         }
                   18563:21):     }
                   18564:21):     if (!$init) {
                   18565:21):         $init = 1;
                   18566:21):     } else {
                   18567:21):         $init ++;
                   18568:21):     }
                   18569:21):     if (keys(%possibles)) {
                   18570:21):         my @posstiny = keys(%possibles);
                   18571:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18572:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18573:21):         if (keys(%currtiny)) {
                   18574:21):             foreach my $key (keys(%currtiny)) {
                   18575:21):                 next if ($currtiny{$key} eq '');
                   18576:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   18577:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18578:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18579:21):                         $courseonly->{$tsymb} = $key;
                   18580:21):                     }
                   18581:21):                 } else {
                   18582:21):                     $collisions{$possibles{$key}} = 1;
                   18583:21):                 }
                   18584:21):                 delete($possibles{$key});
                   18585:21):             }
                   18586:21):         }
                   18587:21):         foreach my $key (keys(%possibles)) {
                   18588:21):             $newunique->{$key} = $possibles{$key};
                   18589:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18590:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18591:21):                 $addcourse->{$tsymb} = $key;
                   18592:21):             }
                   18593:21):         }
                   18594:21):     }
                   18595:21):     if (keys(%collisions)) {
                   18596:21):         if ($init <5) {
                   18597:21):             if (!$init) {
                   18598:21):                 $init = 1;
                   18599:21):             } else {
                   18600:21):                 $init ++;
                   18601:21):             }
                   18602:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18603:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   18604:21):         } else {
                   18605:21):             foreach my $key (keys(%collisions)) {
                   18606:21):                 $failed->{$key} = 1;
                   18607:21):                 $failed->{$key} = 1;
                   18608:21):             }
                   18609:21):         }
                   18610:21):     }
                   18611:21):     return $init;
                   18612:21): }
                   18613:21): 
1.1075.2.135  raeburn  18614: sub is_nonframeable {
                   18615:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18616:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   18617:     return if (($remprotocol eq '') || ($remhost eq ''));
                   18618: 
                   18619:     $remprotocol = lc($remprotocol);
                   18620:     $remhost = lc($remhost);
                   18621:     my $remport = 80;
                   18622:     if ($remprotocol eq 'https') {
                   18623:         $remport = 443;
                   18624:     }
                   18625:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   18626:     if ($cached) {
                   18627:         unless ($nocache) {
                   18628:             if ($result) {
                   18629:                 return 1;
                   18630:             } else {
                   18631:                 return 0;
                   18632:             }
                   18633:         }
                   18634:     }
                   18635:     my $uselink;
                   18636:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  18637:     my $ua = LWP::UserAgent->new;
                   18638:     $ua->timeout(5);
                   18639:     my $response=$ua->request($request);
1.1075.2.135  raeburn  18640:     if ($response->is_success()) {
                   18641:         my $secpolicy = lc($response->header('content-security-policy'));
                   18642:         my $xframeop = lc($response->header('x-frame-options'));
                   18643:         $secpolicy =~ s/^\s+|\s+$//g;
                   18644:         $xframeop =~ s/^\s+|\s+$//g;
                   18645:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   18646:             my $remotehost = $remprotocol.'://'.$remhost;
                   18647:             my ($origin,$protocol,$port);
                   18648:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18649:                 $port = $ENV{'SERVER_PORT'};
                   18650:             } else {
                   18651:                 $port = 80;
                   18652:             }
                   18653:             if ($absolute eq '') {
                   18654:                 $protocol = 'http:';
                   18655:                 if ($port == 443) {
                   18656:                     $protocol = 'https:';
                   18657:                 }
                   18658:                 $origin = $protocol.'//'.lc($hostname);
                   18659:             } else {
                   18660:                 $origin = lc($absolute);
                   18661:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18662:             }
                   18663:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18664:                 my $framepolicy = $1;
                   18665:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18666:                 my @policies = split(/\s+/,$framepolicy);
                   18667:                 if (@policies) {
                   18668:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18669:                         $uselink = 1;
                   18670:                     } else {
                   18671:                         $uselink = 1;
                   18672:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18673:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18674:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18675:                             undef($uselink);
                   18676:                         }
                   18677:                         if ($uselink) {
                   18678:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18679:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18680:                                     undef($uselink);
                   18681:                                 }
                   18682:                             }
                   18683:                         }
                   18684:                         if ($uselink) {
                   18685:                             my @possok;
                   18686:                             if ($ip ne '') {
                   18687:                                 push(@possok,$ip);
                   18688:                             }
                   18689:                             my $hoststr = '';
                   18690:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18691:                                 if ($hoststr eq '') {
                   18692:                                     $hoststr = $part;
                   18693:                                 } else {
                   18694:                                     $hoststr = "$part.$hoststr";
                   18695:                                 }
                   18696:                                 if ($hoststr eq $hostname) {
                   18697:                                     push(@possok,$hostname);
                   18698:                                 } else {
                   18699:                                     push(@possok,"*.$hoststr");
                   18700:                                 }
                   18701:                             }
                   18702:                             if (@possok) {
                   18703:                                 foreach my $poss (@possok) {
                   18704:                                     last if (!$uselink);
                   18705:                                     foreach my $policy (@policies) {
                   18706:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18707:                                             undef($uselink);
                   18708:                                             last;
                   18709:                                         }
                   18710:                                     }
                   18711:                                 }
                   18712:                             }
                   18713:                         }
                   18714:                     }
                   18715:                 }
                   18716:             } elsif ($xframeop ne '') {
                   18717:                 $uselink = 1;
                   18718:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18719:                 if (@policies) {
                   18720:                     unless (grep(/^deny$/,@policies)) {
                   18721:                         if ($origin ne '') {
                   18722:                             if (grep(/^sameorigin$/,@policies)) {
                   18723:                                 if ($remotehost eq $origin) {
                   18724:                                     undef($uselink);
                   18725:                                 }
                   18726:                             }
                   18727:                             if ($uselink) {
                   18728:                                 foreach my $policy (@policies) {
                   18729:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18730:                                         my $allowfrom = $1;
                   18731:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18732:                                             undef($uselink);
                   18733:                                             last;
                   18734:                                         }
                   18735:                                     }
                   18736:                                 }
                   18737:                             }
                   18738:                         }
                   18739:                     }
                   18740:                 }
                   18741:             }
                   18742:         }
                   18743:     }
                   18744:     if ($nocache) {
                   18745:         if ($cached) {
                   18746:             my $devalidate;
                   18747:             if ($uselink && !$result) {
                   18748:                 $devalidate = 1;
                   18749:             } elsif (!$uselink && $result) {
                   18750:                 $devalidate = 1;
                   18751:             }
                   18752:             if ($devalidate) {
                   18753:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18754:             }
                   18755:         }
                   18756:     } else {
                   18757:         if ($uselink) {
                   18758:             $result = 1;
                   18759:         } else {
                   18760:             $result = 0;
                   18761:         }
                   18762:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18763:     }
                   18764:     return $uselink;
                   18765: }
                   18766: 
1.1075.2.161.  .1(raebu 18767:21): sub page_menu {
                   18768:21):     my ($menucolls,$menunum) = @_;
                   18769:21):     my %menu;
                   18770:21):     foreach my $item (split(/;/,$menucolls)) {
                   18771:21):         my ($num,$value) = split(/\%/,$item);
                   18772:21):         if ($num eq $menunum) {
                   18773:21):             my @entries = split(/\&/,$value);
                   18774:21):             foreach my $entry (@entries) {
                   18775:21):                 my ($name,$fields) = split(/=/,$entry);
                   18776:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   18777:21):                     $menu{$name} = $fields;
                   18778:21):                 } else {
                   18779:21):                     my @shown;
                   18780:21):                     if ($fields =~ /,/) {
                   18781:21):                         @shown = split(/,/,$fields);
                   18782:21):                     } else {
                   18783:21):                         @shown = ($fields);
                   18784:21):                     }
                   18785:21):                     if (@shown) {
                   18786:21):                         foreach my $field (@shown) {
                   18787:21):                             next if ($field eq '');
                   18788:21):                             $menu{$field} = 1;
                   18789:21):                         }
                   18790:21):                     }
                   18791:21):                 }
                   18792:21):             }
                   18793:21):         }
                   18794:21):     }
                   18795:21):     return %menu;
                   18796:21): }
                   18797:21): 
1.112     bowersj2 18798: 1;
                   18799: __END__;
1.41      ng       18800: 

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