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

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.  .3(raebu    4:22): # $Id: loncommon.pm,v 1.1075.2.161.2.2 2022/01/16 23:25:47 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.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.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.1075.2.161.  .1(raebu   86:21): use String::CRC32();
                     87:21): use Short::URL();
1.117     www        88: 
1.517     raeburn    89: # ---------------------------------------------- Designs
                     90: use vars qw(%defaultdesign);
                     91: 
1.22      www        92: my $readit;
                     93: 
1.517     raeburn    94: 
1.157     matthew    95: ##
                     96: ## Global Variables
                     97: ##
1.46      matthew    98: 
1.643     foxr       99: 
                    100: # ----------------------------------------------- SSI with retries:
                    101: #
                    102: 
                    103: =pod
                    104: 
1.648     raeburn   105: =head1 Server Side include with retries:
1.643     foxr      106: 
                    107: =over 4
                    108: 
1.648     raeburn   109: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      110: 
                    111: Performs an ssi with some number of retries.  Retries continue either
                    112: until the result is ok or until the retry count supplied by the
                    113: caller is exhausted.  
                    114: 
                    115: Inputs:
1.648     raeburn   116: 
                    117: =over 4
                    118: 
1.643     foxr      119: resource   - Identifies the resource to insert.
1.648     raeburn   120: 
1.643     foxr      121: retries    - Count of the number of retries allowed.
1.648     raeburn   122: 
1.643     foxr      123: form       - Hash that identifies the rendering options.
                    124: 
1.648     raeburn   125: =back
                    126: 
                    127: Returns:
                    128: 
                    129: =over 4
                    130: 
1.643     foxr      131: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   132: 
1.643     foxr      133: response   - The response from the last attempt (which may or may not have been successful.
                    134: 
1.648     raeburn   135: =back
                    136: 
                    137: =back
                    138: 
1.643     foxr      139: =cut
                    140: 
                    141: sub ssi_with_retries {
                    142:     my ($resource, $retries, %form) = @_;
                    143: 
                    144: 
                    145:     my $ok = 0;			# True if we got a good response.
                    146:     my $content;
                    147:     my $response;
                    148: 
                    149:     # Try to get the ssi done. within the retries count:
                    150: 
                    151:     do {
                    152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    153: 	$ok      = $response->is_success;
1.650     www       154:         if (!$ok) {
                    155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    156:         }
1.643     foxr      157: 	$retries--;
                    158:     } while (!$ok && ($retries > 0));
                    159: 
                    160:     if (!$ok) {
                    161: 	$content = '';		# On error return an empty content.
                    162:     }
                    163:     return ($content, $response);
                    164: 
                    165: }
                    166: 
                    167: 
                    168: 
1.20      www       169: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  170: my %language;
1.124     www       171: my %supported_language;
1.1048    foxr      172: my %latex_language;		# For choosing hyphenation in <transl..>
                    173: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  174: my %cprtag;
1.192     taceyjo1  175: my %scprtag;
1.351     www       176: my %fe; my %fd; my %fm;
1.41      ng        177: my %category_extensions;
1.12      harris41  178: 
1.46      matthew   179: # ---------------------------------------------- Thesaurus variables
1.144     matthew   180: #
                    181: # %Keywords:
                    182: #      A hash used by &keyword to determine if a word is considered a keyword.
                    183: # $thesaurus_db_file 
                    184: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   185: 
                    186: my %Keywords;
                    187: my $thesaurus_db_file;
                    188: 
1.144     matthew   189: #
                    190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    191: # thesaurus.tab, and filecategories.tab.
                    192: #
1.18      www       193: BEGIN {
1.46      matthew   194:     # Variable initialization
                    195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    196:     #
1.22      www       197:     unless ($readit) {
1.12      harris41  198: # ------------------------------------------------------------------- languages
                    199:     {
1.158     raeburn   200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    201:                                    '/language.tab';
1.1075.2.128  raeburn   202:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
1.1048    foxr      206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   207:                 $language{$key}=$val.' - '.$enc;
                    208:                 if ($sup) {
                    209:                     $supported_language{$key}=$sup;
                    210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
                    213: 		    $latex_language{$two} = $latex;
                    214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
1.1075.2.128  raeburn   223:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   251:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
1.1075.2.128  raeburn   265:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   270:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
1.1075.2.128  raeburn   280:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.1075.2.143  raeburn   433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   448:         if (courseadv == 'condition') {
                    449:             if (document.getElementById('courseadv')) {
                    450:                 courseadv = document.getElementById('courseadv').value;
                    451:             }
                    452:         }
                    453:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       454:         var title = 'Student_Browser';
1.74      www       455:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    456:         options += ',width=700,height=600';
                    457:         stdeditbrowser = open(url,title,options,'1');
                    458:         stdeditbrowser.focus();
                    459:     }
1.824     bisitz    460: // ]]>
1.74      www       461: </script>
                    462: ENDSTDBRW
                    463: }
1.42      matthew   464: 
1.1003    www       465: sub resourcebrowser_javascript {
                    466:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       467:    return (<<'ENDRESBRW');
1.1003    www       468: <script type="text/javascript" language="Javascript">
                    469: // <![CDATA[
                    470:     var reseditbrowser;
1.1004    www       471:     function openresbrowser(formname,reslink) {
1.1005    www       472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       473:         var title = 'Resource_Browser';
                    474:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       475:         options += ',width=700,height=500';
1.1004    www       476:         reseditbrowser = open(url,title,options,'1');
                    477:         reseditbrowser.focus();
1.1003    www       478:     }
                    479: // ]]>
                    480: </script>
1.1004    www       481: ENDRESBRW
1.1003    www       482: }
                    483: 
1.74      www       484: sub selectstudent_link {
1.1075.2.143  raeburn   485:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  489:    if ($env{'request.course.id'}) {  
1.302     albertel  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    492: 					'/'.$env{'request.course.sec'})) {
1.111     www       493: 	   return '';
                    494:        }
1.999     www       495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   496:        if ($courseadv eq 'only') {
                    497:            $callargs .= ",'',1,'$courseadv'";
                    498:        } elsif ($courseadv eq 'none') {
                    499:            $callargs .= ",'','','$courseadv'";
                    500:        } elsif ($courseadv eq 'condition') {
                    501:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   502:        }
                    503:        return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    505:               &mt('Select User').'</a></span>';
1.74      www       506:    }
1.258     albertel  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       508:        $callargs .= ",'',1"; 
1.793     raeburn   509:        return '<span class="LC_nobreak">'.
                    510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    511:               &mt('Select User').'</a></span>';
1.111     www       512:    }
                    513:    return '';
1.91      www       514: }
                    515: 
1.1004    www       516: sub selectresource_link {
                    517:    my ($form,$reslink,$arg)=@_;
                    518:    
                    519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    521:    unless ($env{'request.course.id'}) { return $arg; }
                    522:    return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    524:               $arg.'</a></span>';
                    525: }
                    526: 
                    527: 
                    528: 
1.653     raeburn   529: sub authorbrowser_javascript {
                    530:     return <<"ENDAUTHORBRW";
1.776     bisitz    531: <script type="text/javascript" language="JavaScript">
1.824     bisitz    532: // <![CDATA[
1.653     raeburn   533: var stdeditbrowser;
                    534: 
                    535: function openauthorbrowser(formname,udom) {
                    536:     var url = '/adm/pickauthor?';
                    537:     url += 'form='+formname+'&roledom='+udom;
                    538:     var title = 'Author_Browser';
                    539:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    540:     options += ',width=700,height=600';
                    541:     stdeditbrowser = open(url,title,options,'1');
                    542:     stdeditbrowser.focus();
                    543: }
                    544: 
1.824     bisitz    545: // ]]>
1.653     raeburn   546: </script>
                    547: ENDAUTHORBRW
                    548: }
                    549: 
1.91      www       550: sub coursebrowser_javascript {
1.1075.2.31  raeburn   551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   552:         $credits_element,$instcode) = @_;
1.932     raeburn   553:     my $wintitle = 'Course_Browser';
1.931     raeburn   554:     if ($crstype eq 'Community') {
1.932     raeburn   555:         $wintitle = 'Community_Browser';
1.909     raeburn   556:     }
1.876     raeburn   557:     my $id_functions = &javascript_index_functions();
                    558:     my $output = '
1.776     bisitz    559: <script type="text/javascript" language="JavaScript">
1.824     bisitz    560: // <![CDATA[
1.468     raeburn   561:     var stdeditbrowser;'."\n";
1.876     raeburn   562: 
                    563:     $output .= <<"ENDSTDBRW";
1.909     raeburn   564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       565:         var url = '/adm/pickcourse?';
1.895     raeburn   566:         var formid = getFormIdByName(formname);
1.876     raeburn   567:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  568:         if (domainfilter != null) {
                    569:            if (domainfilter != '') {
                    570:                url += 'domainfilter='+domainfilter+'&';
                    571: 	   }
                    572:         }
1.91      www       573:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  574: 	                            '&cdomelement='+udom+
                    575:                                     '&cnameelement='+desc;
1.468     raeburn   576:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   577:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   578:                 url += '&roleelement='+extra_element;
                    579:                 if (domainfilter == null || domainfilter == '') {
                    580:                     url += '&domainfilter='+extra_element;
                    581:                 }
1.234     raeburn   582:             }
1.468     raeburn   583:             else {
                    584:                 if (formname == 'portform') {
                    585:                     url += '&setroles='+extra_element;
1.800     raeburn   586:                 } else {
                    587:                     if (formname == 'rules') {
                    588:                         url += '&fixeddom='+extra_element; 
                    589:                     }
1.468     raeburn   590:                 }
                    591:             }     
1.230     raeburn   592:         }
1.909     raeburn   593:         if (type != null && type != '') {
                    594:             url += '&type='+type;
                    595:         }
                    596:         if (type_elem != null && type_elem != '') {
                    597:             url += '&typeelement='+type_elem;
                    598:         }
1.872     raeburn   599:         if (formname == 'ccrs') {
                    600:             var ownername = document.forms[formid].ccuname.value;
                    601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   602:             url += '&cloner='+ownername+':'+ownerdom;
                    603:             if (type == 'Course') {
                    604:                 url += '&crscode='+document.forms[formid].crscode.value;
                    605:             }
1.1075.2.95  raeburn   606:         }
                    607:         if (formname == 'requestcrs') {
                    608:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   609:         }
1.293     raeburn   610:         if (multflag !=null && multflag != '') {
                    611:             url += '&multiple='+multflag;
                    612:         }
1.909     raeburn   613:         var title = '$wintitle';
1.91      www       614:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    615:         options += ',width=700,height=600';
                    616:         stdeditbrowser = open(url,title,options,'1');
                    617:         stdeditbrowser.focus();
                    618:     }
1.876     raeburn   619: $id_functions
                    620: ENDSTDBRW
1.1075.2.31  raeburn   621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    623:                                       $credits_element);
1.876     raeburn   624:     }
                    625:     $output .= '
                    626: // ]]>
                    627: </script>';
                    628:     return $output;
                    629: }
                    630: 
                    631: sub javascript_index_functions {
                    632:     return <<"ENDJS";
                    633: 
                    634: function getFormIdByName(formname) {
                    635:     for (var i=0;i<document.forms.length;i++) {
                    636:         if (document.forms[i].name == formname) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
                    642: 
                    643: function getIndexByName(formid,item) {
                    644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    645:         if (document.forms[formid].elements[i].name == item) {
                    646:             return i;
                    647:         }
                    648:     }
                    649:     return -1;
                    650: }
1.468     raeburn   651: 
1.876     raeburn   652: function getDomainFromSelectbox(formname,udom) {
                    653:     var userdom;
                    654:     var formid = getFormIdByName(formname);
                    655:     if (formid > -1) {
                    656:         var domid = getIndexByName(formid,udom);
                    657:         if (domid > -1) {
                    658:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    660:             }
                    661:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    662:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   663:             }
                    664:         }
                    665:     }
1.876     raeburn   666:     return userdom;
                    667: }
                    668: 
                    669: ENDJS
1.468     raeburn   670: 
1.876     raeburn   671: }
                    672: 
1.1017    raeburn   673: sub javascript_array_indexof {
1.1018    raeburn   674:     return <<ENDJS;
1.1017    raeburn   675: <script type="text/javascript" language="JavaScript">
                    676: // <![CDATA[
                    677: 
                    678: if (!Array.prototype.indexOf) {
                    679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    680:         "use strict";
                    681:         if (this === void 0 || this === null) {
                    682:             throw new TypeError();
                    683:         }
                    684:         var t = Object(this);
                    685:         var len = t.length >>> 0;
                    686:         if (len === 0) {
                    687:             return -1;
                    688:         }
                    689:         var n = 0;
                    690:         if (arguments.length > 0) {
                    691:             n = Number(arguments[1]);
                    692:             if (n !== n) { // shortcut for verifying if it's NaN
                    693:                 n = 0;
                    694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    696:             }
                    697:         }
                    698:         if (n >= len) {
                    699:             return -1;
                    700:         }
                    701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    702:         for (; k < len; k++) {
                    703:             if (k in t && t[k] === searchElement) {
                    704:                 return k;
                    705:             }
                    706:         }
                    707:         return -1;
                    708:     }
                    709: }
                    710: 
                    711: // ]]>
                    712: </script>
                    713: 
                    714: ENDJS
                    715: 
                    716: }
                    717: 
1.876     raeburn   718: sub userbrowser_javascript {
                    719:     my $id_functions = &javascript_index_functions();
                    720:     return <<"ENDUSERBRW";
                    721: 
1.888     raeburn   722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   723:     var url = '/adm/pickuser?';
                    724:     var userdom = getDomainFromSelectbox(formname,udom);
                    725:     if (userdom != null) {
                    726:        if (userdom != '') {
                    727:            url += 'srchdom='+userdom+'&';
                    728:        }
                    729:     }
                    730:     url += 'form=' + formname + '&unameelement='+uname+
                    731:                                 '&udomelement='+udom+
                    732:                                 '&ulastelement='+ulast+
                    733:                                 '&ufirstelement='+ufirst+
                    734:                                 '&uemailelement='+uemail+
1.881     raeburn   735:                                 '&hideudomelement='+hideudom+
                    736:                                 '&coursedom='+crsdom;
1.888     raeburn   737:     if ((caller != null) && (caller != undefined)) {
                    738:         url += '&caller='+caller;
                    739:     }
1.876     raeburn   740:     var title = 'User_Browser';
                    741:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    742:     options += ',width=700,height=600';
                    743:     var stdeditbrowser = open(url,title,options,'1');
                    744:     stdeditbrowser.focus();
                    745: }
                    746: 
1.888     raeburn   747: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   748:     var formid = getFormIdByName(formname);
                    749:     if (formid > -1) {
1.888     raeburn   750:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   751:         var domid = getIndexByName(formid,udom);
                    752:         var hidedomid = getIndexByName(formid,origdom);
                    753:         if (hidedomid > -1) {
                    754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   755:             var unameval = document.forms[formid].elements[unameid].value;
                    756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    757:                 if (domid > -1) {
                    758:                     var slct = document.forms[formid].elements[domid];
                    759:                     if (slct.type == 'select-one') {
                    760:                         var i;
                    761:                         for (i=0;i<slct.length;i++) {
                    762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    763:                         }
                    764:                     }
                    765:                     if (slct.type == 'hidden') {
                    766:                         slct.value = fixeddom;
1.876     raeburn   767:                     }
                    768:                 }
1.468     raeburn   769:             }
                    770:         }
                    771:     }
1.876     raeburn   772:     return;
                    773: }
                    774: 
                    775: $id_functions
                    776: ENDUSERBRW
1.468     raeburn   777: }
                    778: 
                    779: sub setsec_javascript {
1.1075.2.31  raeburn   780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    782:         $communityrolestr);
                    783:     if ($role_element ne '') {
                    784:         my @allroles = ('st','ta','ep','in','ad');
                    785:         foreach my $crstype ('Course','Community') {
                    786:             if ($crstype eq 'Community') {
                    787:                 foreach my $role (@allroles) {
                    788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    789:                 }
                    790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    791:             } else {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    796:             }
                    797:         }
                    798:         $rolestr = '"'.join('","',@allroles).'"';
                    799:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    801:     }
1.468     raeburn   802:     my $setsections = qq|
                    803: function setSect(sectionlist) {
1.629     raeburn   804:     var sectionsArray = new Array();
                    805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    806:         sectionsArray = sectionlist.split(",");
                    807:     }
1.468     raeburn   808:     var numSections = sectionsArray.length;
                    809:     document.$formname.$sec_element.length = 0;
                    810:     if (numSections == 0) {
                    811:         document.$formname.$sec_element.multiple=false;
                    812:         document.$formname.$sec_element.size=1;
                    813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    814:     } else {
                    815:         if (numSections == 1) {
                    816:             document.$formname.$sec_element.multiple=false;
                    817:             document.$formname.$sec_element.size=1;
                    818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    821:         } else {
                    822:             for (var i=0; i<numSections; i++) {
                    823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    824:             }
                    825:             document.$formname.$sec_element.multiple=true
                    826:             if (numSections < 3) {
                    827:                 document.$formname.$sec_element.size=numSections;
                    828:             } else {
                    829:                 document.$formname.$sec_element.size=3;
                    830:             }
                    831:             document.$formname.$sec_element.options[0].selected = false
                    832:         }
                    833:     }
1.91      www       834: }
1.905     raeburn   835: 
                    836: function setRole(crstype) {
1.468     raeburn   837: |;
1.905     raeburn   838:     if ($role_element eq '') {
                    839:         $setsections .= '    return;
                    840: }
                    841: ';
                    842:     } else {
                    843:         $setsections .= qq|
                    844:     var elementLength = document.$formname.$role_element.length;
                    845:     var allroles = Array($rolestr);
                    846:     var courserolenames = Array($courserolestr);
                    847:     var communityrolenames = Array($communityrolestr);
                    848:     if (elementLength != undefined) {
                    849:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    850:             if (crstype == 'Course') {
                    851:                 return;
                    852:             } else {
                    853:                 allroles[5] = 'co';
                    854:                 for (var i=0; i<6; i++) {
                    855:                     document.$formname.$role_element.options[i].value = allroles[i];
                    856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    857:                 }
                    858:             }
                    859:         } else {
                    860:             if (crstype == 'Community') {
                    861:                 return;
                    862:             } else {
                    863:                 allroles[5] = 'cc';
                    864:                 for (var i=0; i<6; i++) {
                    865:                     document.$formname.$role_element.options[i].value = allroles[i];
                    866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    867:                 }
                    868:             }
                    869:         }
                    870:     }
                    871:     return;
                    872: }
                    873: |;
                    874:     }
1.1075.2.31  raeburn   875:     if ($credits_element) {
                    876:         $setsections .= qq|
                    877: function setCredits(defaultcredits) {
                    878:     document.$formname.$credits_element.value = defaultcredits;
                    879:     return;
                    880: }
                    881: |;
                    882:     }
1.468     raeburn   883:     return $setsections;
                    884: }
                    885: 
1.91      www       886: sub selectcourse_link {
1.909     raeburn   887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    888:        $typeelement) = @_;
                    889:    my $type = $selecttype;
1.871     raeburn   890:    my $linktext = &mt('Select Course');
                    891:    if ($selecttype eq 'Community') {
1.909     raeburn   892:        $linktext = &mt('Select Community');
1.906     raeburn   893:    } elsif ($selecttype eq 'Course/Community') {
                    894:        $linktext = &mt('Select Course/Community');
1.909     raeburn   895:        $type = '';
1.1019    raeburn   896:    } elsif ($selecttype eq 'Select') {
                    897:        $linktext = &mt('Select');
                    898:        $type = '';
1.871     raeburn   899:    }
1.787     bisitz    900:    return '<span class="LC_nobreak">'
                    901:          ."<a href='"
                    902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   905:          ."'>".$linktext.'</a>'
1.787     bisitz    906:          .'</span>';
1.74      www       907: }
1.42      matthew   908: 
1.653     raeburn   909: sub selectauthor_link {
                    910:    my ($form,$udom)=@_;
                    911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    912:           &mt('Select Author').'</a>';
                    913: }
                    914: 
1.876     raeburn   915: sub selectuser_link {
1.881     raeburn   916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   917:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   920:            ');">'.$linktext.'</a>';
1.876     raeburn   921: }
                    922: 
1.273     raeburn   923: sub check_uncheck_jscript {
                    924:     my $jscript = <<"ENDSCRT";
                    925: function checkAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   928:             if (!field[i].disabled) {
                    929:                 field[i].checked = true;
                    930:             }
1.273     raeburn   931:         }
                    932:     } else {
1.1075.2.14  raeburn   933:         if (!field.disabled) {
                    934:             field.checked = true;
                    935:         }
1.273     raeburn   936:     }
                    937: }
                    938:  
                    939: function uncheckAll(field) {
                    940:     if (field.length > 0) {
                    941:         for (i = 0; i < field.length; i++) {
                    942:             field[i].checked = false ;
1.543     albertel  943:         }
                    944:     } else {
1.273     raeburn   945:         field.checked = false ;
                    946:     }
                    947: }
                    948: ENDSCRT
                    949:     return $jscript;
                    950: }
                    951: 
1.656     www       952: sub select_timezone {
1.1075.2.115  raeburn   953:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    954:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   955:    if ($includeempty) {
                    956:        $output .= '<option value=""';
                    957:        if (($selected eq '') || ($selected eq 'local')) {
                    958:            $output .= ' selected="selected" ';
                    959:        }
                    960:        $output .= '> </option>';
                    961:    }
1.657     raeburn   962:    my @timezones = DateTime::TimeZone->all_names;
                    963:    foreach my $tzone (@timezones) {
                    964:        $output.= '<option value="'.$tzone.'"';
                    965:        if ($tzone eq $selected) {
                    966:            $output.=' selected="selected"';
                    967:        }
                    968:        $output.=">$tzone</option>\n";
1.656     www       969:    }
                    970:    $output.="</select>";
                    971:    return $output;
                    972: }
1.273     raeburn   973: 
1.687     raeburn   974: sub select_datelocale {
1.1075.2.115  raeburn   975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   977:     if ($includeempty) {
                    978:         $output .= '<option value=""';
                    979:         if ($selected eq '') {
                    980:             $output .= ' selected="selected" ';
                    981:         }
                    982:         $output .= '> </option>';
                    983:     }
1.1075.2.102  raeburn   984:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   985:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   986:     my @locales = DateTime::Locale->ids();
                    987:     foreach my $id (@locales) {
                    988:         if ($id ne '') {
                    989:             my ($en_terr,$native_terr);
                    990:             my $loc = DateTime::Locale->load($id);
                    991:             if (ref($loc)) {
                    992:                 $en_terr = $loc->name();
                    993:                 $native_terr = $loc->native_name();
1.687     raeburn   994:                 if (grep(/^en$/,@languages) || !@languages) {
                    995:                     if ($en_terr ne '') {
                    996:                         $locale_names{$id} = '('.$en_terr.')';
                    997:                     } elsif ($native_terr ne '') {
                    998:                         $locale_names{$id} = $native_terr;
                    999:                     }
                   1000:                 } else {
                   1001:                     if ($native_terr ne '') {
                   1002:                         $locale_names{$id} = $native_terr.' ';
                   1003:                     } elsif ($en_terr ne '') {
                   1004:                         $locale_names{$id} = '('.$en_terr.')';
                   1005:                     }
                   1006:                 }
1.1075.2.94  raeburn  1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1008:                 push(@possibles,$id);
1.687     raeburn  1009:             }
                   1010:         }
                   1011:     }
                   1012:     foreach my $item (sort(@possibles)) {
                   1013:         $output.= '<option value="'.$item.'"';
                   1014:         if ($item eq $selected) {
                   1015:             $output.=' selected="selected"';
                   1016:         }
                   1017:         $output.=">$item";
                   1018:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1019:             $output.='  '.$locale_names{$item};
1.687     raeburn  1020:         }
                   1021:         $output.="</option>\n";
                   1022:     }
                   1023:     $output.="</select>";
                   1024:     return $output;
                   1025: }
                   1026: 
1.792     raeburn  1027: sub select_language {
1.1075.2.115  raeburn  1028:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1029:     my %langchoices;
                   1030:     if ($includeempty) {
1.1075.2.32  raeburn  1031:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1032:     }
                   1033:     foreach my $id (&languageids()) {
                   1034:         my $code = &supportedlanguagecode($id);
                   1035:         if ($code) {
                   1036:             $langchoices{$code} = &plainlanguagedescription($id);
                   1037:         }
                   1038:     }
1.1075.2.32  raeburn  1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1041: }
                   1042: 
1.42      matthew  1043: =pod
1.36      matthew  1044: 
1.648     raeburn  1045: =item * &linked_select_forms(...)
1.36      matthew  1046: 
                   1047: linked_select_forms returns a string containing a <script></script> block
                   1048: and html for two <select> menus.  The select menus will be linked in that
                   1049: changing the value of the first menu will result in new values being placed
                   1050: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1051: order unless a defined order is provided.
1.36      matthew  1052: 
                   1053: linked_select_forms takes the following ordered inputs:
                   1054: 
                   1055: =over 4
                   1056: 
1.112     bowersj2 1057: =item * $formname, the name of the <form> tag
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstdefault, the default value for the first menu
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1066: 
1.112     bowersj2 1067: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1068: 
1.609     raeburn  1069: =item * $menuorder, the order of values in the first menu
                   1070: 
1.1075.2.31  raeburn  1071: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1072:         event for the first <select> tag
                   1073: 
                   1074: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1075:         event for the second <select> tag
                   1076: 
1.41      ng       1077: =back 
                   1078: 
1.36      matthew  1079: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1081: values for the first select menu.  The text that coincides with the 
1.41      ng       1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1083: and text for the second menu are given in the hash pointed to by 
                   1084: $menu{$choice1}->{'select2'}.  
                   1085: 
1.112     bowersj2 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1087:                        default => "B3",
                   1088:                        select2 => { 
                   1089:                            B1 => "Choice B1",
                   1090:                            B2 => "Choice B2",
                   1091:                            B3 => "Choice B3",
                   1092:                            B4 => "Choice B4"
1.609     raeburn  1093:                            },
                   1094:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1095:                    },
                   1096:                A2 => { text =>"Choice A2" ,
                   1097:                        default => "C2",
                   1098:                        select2 => { 
                   1099:                            C1 => "Choice C1",
                   1100:                            C2 => "Choice C2",
                   1101:                            C3 => "Choice C3"
1.609     raeburn  1102:                            },
                   1103:                        order => ['C2','C1','C3'],
1.112     bowersj2 1104:                    },
                   1105:                A3 => { text =>"Choice A3" ,
                   1106:                        default => "D6",
                   1107:                        select2 => { 
                   1108:                            D1 => "Choice D1",
                   1109:                            D2 => "Choice D2",
                   1110:                            D3 => "Choice D3",
                   1111:                            D4 => "Choice D4",
                   1112:                            D5 => "Choice D5",
                   1113:                            D6 => "Choice D6",
                   1114:                            D7 => "Choice D7"
1.609     raeburn  1115:                            },
                   1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1117:                    }
                   1118:                );
1.36      matthew  1119: 
                   1120: =cut
                   1121: 
                   1122: sub linked_select_forms {
                   1123:     my ($formname,
                   1124:         $middletext,
                   1125:         $firstdefault,
                   1126:         $firstselectname,
                   1127:         $secondselectname, 
1.609     raeburn  1128:         $hashref,
                   1129:         $menuorder,
1.1075.2.31  raeburn  1130:         $onchangefirst,
                   1131:         $onchangesecond
1.36      matthew  1132:         ) = @_;
                   1133:     my $second = "document.$formname.$secondselectname";
                   1134:     my $first = "document.$formname.$firstselectname";
                   1135:     # output the javascript to do the changing
                   1136:     my $result = '';
1.776     bisitz   1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1138:     $result.="// <![CDATA[\n";
1.36      matthew  1139:     $result.="var select2data = new Object();\n";
                   1140:     $" = '","';
                   1141:     my $debug = '';
                   1142:     foreach my $s1 (sort(keys(%$hashref))) {
                   1143:         $result.="select2data.d_$s1 = new Object();\n";        
                   1144:         $result.="select2data.d_$s1.def = new String('".
                   1145:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1146:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1149:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1150:         }
1.36      matthew  1151:         $result.="\"@s2values\");\n";
                   1152:         $result.="select2data.d_$s1.texts = new Array(";        
                   1153:         my @s2texts;
                   1154:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1156:         }
                   1157:         $result.="\"@s2texts\");\n";
                   1158:     }
                   1159:     $"=' ';
                   1160:     $result.= <<"END";
                   1161: 
                   1162: function select1_changed() {
                   1163:     // Determine new choice
                   1164:     var newvalue = "d_" + $first.value;
                   1165:     // update select2
                   1166:     var values     = select2data[newvalue].values;
                   1167:     var texts      = select2data[newvalue].texts;
                   1168:     var select2def = select2data[newvalue].def;
                   1169:     var i;
                   1170:     // out with the old
                   1171:     for (i = 0; i < $second.options.length; i++) {
                   1172:         $second.options[i] = null;
                   1173:     }
                   1174:     // in with the nuclear
                   1175:     for (i=0;i<values.length; i++) {
                   1176:         $second.options[i] = new Option(values[i]);
1.143     matthew  1177:         $second.options[i].value = values[i];
1.36      matthew  1178:         $second.options[i].text = texts[i];
                   1179:         if (values[i] == select2def) {
                   1180:             $second.options[i].selected = true;
                   1181:         }
                   1182:     }
                   1183: }
1.824     bisitz   1184: // ]]>
1.36      matthew  1185: </script>
                   1186: END
                   1187:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1189:     my @order = sort(keys(%{$hashref}));
                   1190:     if (ref($menuorder) eq 'ARRAY') {
                   1191:         @order = @{$menuorder};
                   1192:     }
                   1193:     foreach my $value (@order) {
1.36      matthew  1194:         $result.="    <option value=\"$value\" ";
1.253     albertel 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1197:     }
                   1198:     $result .= "</select>\n";
                   1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1200:     $result .= $middletext;
1.1075.2.31  raeburn  1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1202:     if ($onchangesecond) {
                   1203:         $result .= ' onchange="'.$onchangesecond.'"';
                   1204:     }
                   1205:     $result .= ">\n";
1.36      matthew  1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1207:     
                   1208:     my @secondorder = sort(keys(%select2));
                   1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1211:     }
                   1212:     foreach my $value (@secondorder) {
1.36      matthew  1213:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1215:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1216:     }
                   1217:     $result .= "</select>\n";
                   1218:     #    return $debug;
                   1219:     return $result;
                   1220: }   #  end of sub linked_select_forms {
                   1221: 
1.45      matthew  1222: =pod
1.44      bowersj2 1223: 
1.973     raeburn  1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1225: 
1.112     bowersj2 1226: Returns a string corresponding to an HTML link to the given help
                   1227: $topic, where $topic corresponds to the name of a .tex file in
                   1228: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1229: spaces. 
                   1230: 
                   1231: $text will optionally be linked to the same topic, allowing you to
                   1232: link text in addition to the graphic. If you do not want to link
                   1233: text, but wish to specify one of the later parameters, pass an
                   1234: empty string. 
                   1235: 
                   1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1237: the link will not open a new window. If false, the link will open
                   1238: a new window using Javascript. (Default is false.) 
                   1239: 
                   1240: $width and $height are optional numerical parameters that will
                   1241: override the width and height of the popped up window, which may
1.973     raeburn  1242: be useful for certain help topics with big pictures included.
                   1243: 
                   1244: $imgid is the id of the img tag used for the help icon. This may be
                   1245: used in a javascript call to switch the image src.  See 
                   1246: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1247: 
                   1248: =cut
                   1249: 
                   1250: sub help_open_topic {
1.973     raeburn  1251:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1252:     $text = "" if (not defined $text);
1.44      bowersj2 1253:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1254:     $width = 500 if (not defined $width);
1.44      bowersj2 1255:     $height = 400 if (not defined $height);
                   1256:     my $filename = $topic;
                   1257:     $filename =~ s/ /_/g;
                   1258: 
1.48      bowersj2 1259:     my $template = "";
                   1260:     my $link;
1.572     banghart 1261:     
1.159     www      1262:     $topic=~s/\W/\_/g;
1.44      bowersj2 1263: 
1.572     banghart 1264:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1265:         if ($env{'browser.mobile'}) {
                   1266: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1267:         } else {
                   1268:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1269:         }
1.1037    www      1270:     } elsif ($stayOnPage eq 'popup') {
                   1271:         $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 1272:     } else {
1.48      bowersj2 1273: 	$link = "/adm/help/${filename}.hlp";
                   1274:     }
                   1275: 
                   1276:     # Add the text
1.755     neumanie 1277:     if ($text ne "") {	
1.763     bisitz   1278: 	$template.='<span class="LC_help_open_topic">'
                   1279:                   .'<a target="_top" href="'.$link.'">'
                   1280:                   .$text.'</a>';
1.48      bowersj2 1281:     }
                   1282: 
1.763     bisitz   1283:     # (Always) Add the graphic
1.179     matthew  1284:     my $title = &mt('Online Help');
1.667     raeburn  1285:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1286:     if ($imgid ne '') {
                   1287:         $imgid = ' id="'.$imgid.'"';
                   1288:     }
1.763     bisitz   1289:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1290:               .'<img src="'.$helpicon.'" border="0"'
                   1291:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1292:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1293:               .' /></a>';
                   1294:     if ($text ne "") {	
                   1295:         $template.='</span>';
                   1296:     }
1.44      bowersj2 1297:     return $template;
                   1298: 
1.106     bowersj2 1299: }
                   1300: 
                   1301: # This is a quicky function for Latex cheatsheet editing, since it 
                   1302: # appears in at least four places
                   1303: sub helpLatexCheatsheet {
1.1037    www      1304:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1305:     my $out;
1.106     bowersj2 1306:     my $addOther = '';
1.732     raeburn  1307:     if ($topic) {
1.1037    www      1308: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1309:     }
                   1310:     $out = '<span>' # Start cheatsheet
                   1311: 	  .$addOther
                   1312:           .'<span>'
1.1037    www      1313: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span> <span>'
1.1037    www      1315: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1316: 	  .'</span>';
1.732     raeburn  1317:     unless ($not_author) {
1.763     bisitz   1318:         $out .= ' <span>'
1.1037    www      1319: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320: 	       .'</span> <span>'
1.1075.2.78  raeburn  1321:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1322:                .'</span>';
1.732     raeburn  1323:     }
1.763     bisitz   1324:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1325:     return $out;
1.172     www      1326: }
                   1327: 
1.430     albertel 1328: sub general_help {
                   1329:     my $helptopic='Student_Intro';
                   1330:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1331: 	$helptopic='Authoring_Intro';
1.907     raeburn  1332:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1333: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1334:     } elsif ($env{'request.role'}=~/^dc/) {
                   1335:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1336:     }
                   1337:     return $helptopic;
                   1338: }
                   1339: 
                   1340: sub update_help_link {
                   1341:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1342:     my $origurl = $ENV{'REQUEST_URI'};
                   1343:     $origurl=~s|^/~|/priv/|;
                   1344:     my $timestamp = time;
                   1345:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1346:         $$datum = &escape($$datum);
                   1347:     }
                   1348: 
                   1349:     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";
                   1350:     my $output .= <<"ENDOUTPUT";
                   1351: <script type="text/javascript">
1.824     bisitz   1352: // <![CDATA[
1.430     albertel 1353: banner_link = '$banner_link';
1.824     bisitz   1354: // ]]>
1.430     albertel 1355: </script>
                   1356: ENDOUTPUT
                   1357:     return $output;
                   1358: }
                   1359: 
                   1360: # now just updates the help link and generates a blue icon
1.193     raeburn  1361: sub help_open_menu {
1.430     albertel 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1363: 	= @_;    
1.949     droeschl 1364:     $stayOnPage = 1;
1.430     albertel 1365:     my $output;
                   1366:     if ($component_help) {
                   1367: 	if (!$text) {
                   1368: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1369: 				       $width,$height);
                   1370: 	} else {
                   1371: 	    my $help_text;
                   1372: 	    $help_text=&unescape($topic);
                   1373: 	    $output='<table><tr><td>'.
                   1374: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1375: 				 $width,$height).'</td></tr></table>';
                   1376: 	}
                   1377:     }
                   1378:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1379:     return $output.$banner_link;
                   1380: }
                   1381: 
                   1382: sub top_nav_help {
1.1075.2.158  raeburn  1383:     my ($text,$linkattr) = @_;
1.436     albertel 1384:     $text = &mt($text);
1.1075.2.60  raeburn  1385:     my $stay_on_page;
                   1386:     unless ($env{'environment.remote'} eq 'on') {
                   1387:         $stay_on_page = 1;
                   1388:     }
1.1075.2.61  raeburn  1389:     my ($link,$banner_link);
                   1390:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1391:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1392: 	                         : "javascript:helpMenu('open')";
                   1393:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1394:     }
1.201     raeburn  1395:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1396:     if ($link) {
                   1397:         return <<"END";
1.436     albertel 1398: $banner_link
1.1075.2.158  raeburn  1399: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1400: END
1.1075.2.61  raeburn  1401:     } else {
                   1402:         return '&nbsp;'.$text.'&nbsp;';
                   1403:     }
1.436     albertel 1404: }
                   1405: 
                   1406: sub help_menu_js {
1.1075.2.52  raeburn  1407:     my ($httphost) = @_;
1.949     droeschl 1408:     my $stayOnPage = 1;
1.436     albertel 1409:     my $width = 620;
                   1410:     my $height = 600;
1.430     albertel 1411:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1412:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1413:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1414:     my $start_page =
                   1415:         &Apache::loncommon::start_page('Help Menu', undef,
                   1416: 				       {'frameset'    => 1,
                   1417: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1418:                                         'use_absolute' => $httphost,
1.331     albertel 1419: 					'add_entries' => {
                   1420: 					    'border' => '0',
1.579     raeburn  1421: 					    'rows'   => "110,*",},});
1.331     albertel 1422:     my $end_page =
                   1423:         &Apache::loncommon::end_page({'frameset' => 1,
                   1424: 				      'js_ready' => 1,});
                   1425: 
1.436     albertel 1426:     my $template .= <<"ENDTEMPLATE";
                   1427: <script type="text/javascript">
1.877     bisitz   1428: // <![CDATA[
1.253     albertel 1429: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1430: var banner_link = '';
1.243     raeburn  1431: function helpMenu(target) {
                   1432:     var caller = this;
                   1433:     if (target == 'open') {
                   1434:         var newWindow = null;
                   1435:         try {
1.262     albertel 1436:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1437:         }
                   1438:         catch(error) {
                   1439:             writeHelp(caller);
                   1440:             return;
                   1441:         }
                   1442:         if (newWindow) {
                   1443:             caller = newWindow;
                   1444:         }
1.193     raeburn  1445:     }
1.243     raeburn  1446:     writeHelp(caller);
                   1447:     return;
                   1448: }
                   1449: function writeHelp(caller) {
1.1075.2.61  raeburn  1450:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1451:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1452:     caller.document.close();
                   1453:     caller.focus();
1.193     raeburn  1454: }
1.877     bisitz   1455: // END LON-CAPA Internal -->
1.253     albertel 1456: // ]]>
1.436     albertel 1457: </script>
1.193     raeburn  1458: ENDTEMPLATE
                   1459:     return $template;
                   1460: }
                   1461: 
1.172     www      1462: sub help_open_bug {
                   1463:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1464:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1465:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1466:     $text = "" if (not defined $text);
                   1467: 	$stayOnPage=1;
1.184     albertel 1468:     $width = 600 if (not defined $width);
                   1469:     $height = 600 if (not defined $height);
1.172     www      1470: 
                   1471:     $topic=~s/\W+/\+/g;
                   1472:     my $link='';
                   1473:     my $template='';
1.379     albertel 1474:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1475: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1476:     if (!$stayOnPage)
                   1477:     {
                   1478: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1479:     }
                   1480:     else
                   1481:     {
                   1482: 	$link = $url;
                   1483:     }
                   1484:     # Add the text
                   1485:     if ($text ne "")
                   1486:     {
                   1487: 	$template .= 
                   1488:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1489:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1490:     }
                   1491: 
                   1492:     # Add the graphic
1.179     matthew  1493:     my $title = &mt('Report a Bug');
1.215     albertel 1494:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1495:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1496:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1497: ENDTEMPLATE
                   1498:     if ($text ne '') { $template.='</td></tr></table>' };
                   1499:     return $template;
                   1500: 
                   1501: }
                   1502: 
                   1503: sub help_open_faq {
                   1504:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1505:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1506:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1507:     $text = "" if (not defined $text);
                   1508: 	$stayOnPage=1;
                   1509:     $width = 350 if (not defined $width);
                   1510:     $height = 400 if (not defined $height);
                   1511: 
                   1512:     $topic=~s/\W+/\+/g;
                   1513:     my $link='';
                   1514:     my $template='';
                   1515:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1516:     if (!$stayOnPage)
                   1517:     {
                   1518: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1519:     }
                   1520:     else
                   1521:     {
                   1522: 	$link = $url;
                   1523:     }
                   1524: 
                   1525:     # Add the text
                   1526:     if ($text ne "")
                   1527:     {
                   1528: 	$template .= 
1.173     www      1529:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1530:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1531:     }
                   1532: 
                   1533:     # Add the graphic
1.179     matthew  1534:     my $title = &mt('View the FAQ');
1.215     albertel 1535:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1536:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1537:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1538: ENDTEMPLATE
                   1539:     if ($text ne '') { $template.='</td></tr></table>' };
                   1540:     return $template;
                   1541: 
1.44      bowersj2 1542: }
1.37      matthew  1543: 
1.180     matthew  1544: ###############################################################
                   1545: ###############################################################
                   1546: 
1.45      matthew  1547: =pod
                   1548: 
1.648     raeburn  1549: =item * &change_content_javascript():
1.256     matthew  1550: 
                   1551: This and the next function allow you to create small sections of an
                   1552: otherwise static HTML page that you can update on the fly with
                   1553: Javascript, even in Netscape 4.
                   1554: 
                   1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1556: must be written to the HTML page once. It will prove the Javascript
                   1557: function "change(name, content)". Calling the change function with the
                   1558: name of the section 
                   1559: you want to update, matching the name passed to C<changable_area>, and
                   1560: the new content you want to put in there, will put the content into
                   1561: that area.
                   1562: 
                   1563: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1564: to contain room for the original contents. You need to "make space"
                   1565: for whatever changes you wish to make, and be B<sure> to check your
                   1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1567: it's adequate for updating a one-line status display, but little more.
                   1568: This script will set the space to 100% width, so you only need to
                   1569: worry about height in Netscape 4.
                   1570: 
                   1571: Modern browsers are much less limiting, and if you can commit to the
                   1572: user not using Netscape 4, this feature may be used freely with
                   1573: pretty much any HTML.
                   1574: 
                   1575: =cut
                   1576: 
                   1577: sub change_content_javascript {
                   1578:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1579:     if ($env{'browser.type'} eq 'netscape' &&
                   1580: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1581: 	return (<<NETSCAPE4);
                   1582: 	function change(name, content) {
                   1583: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1584: 	    doc.open();
                   1585: 	    doc.write(content);
                   1586: 	    doc.close();
                   1587: 	}
                   1588: NETSCAPE4
                   1589:     } else {
                   1590: 	# Otherwise, we need to use semi-standards-compliant code
                   1591: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1592: 	# is really scary, and every useful browser supports it
                   1593: 	return (<<DOMBASED);
                   1594: 	function change(name, content) {
                   1595: 	    element = document.getElementById(name);
                   1596: 	    element.innerHTML = content;
                   1597: 	}
                   1598: DOMBASED
                   1599:     }
                   1600: }
                   1601: 
                   1602: =pod
                   1603: 
1.648     raeburn  1604: =item * &changable_area($name,$origContent):
1.256     matthew  1605: 
                   1606: This provides a "changable area" that can be modified on the fly via
                   1607: the Javascript code provided in C<change_content_javascript>. $name is
                   1608: the name you will use to reference the area later; do not repeat the
                   1609: same name on a given HTML page more then once. $origContent is what
                   1610: the area will originally contain, which can be left blank.
                   1611: 
                   1612: =cut
                   1613: 
                   1614: sub changable_area {
                   1615:     my ($name, $origContent) = @_;
                   1616: 
1.258     albertel 1617:     if ($env{'browser.type'} eq 'netscape' &&
                   1618: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1619: 	# If this is netscape 4, we need to use the Layer tag
                   1620: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1621:     } else {
                   1622: 	return "<span id='$name'>$origContent</span>";
                   1623:     }
                   1624: }
                   1625: 
                   1626: =pod
                   1627: 
1.648     raeburn  1628: =item * &viewport_geometry_js 
1.590     raeburn  1629: 
                   1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1631: 
                   1632: =cut
                   1633: 
                   1634: 
                   1635: sub viewport_geometry_js { 
                   1636:     return <<"GEOMETRY";
                   1637: var Geometry = {};
                   1638: function init_geometry() {
                   1639:     if (Geometry.init) { return };
                   1640:     Geometry.init=1;
                   1641:     if (window.innerHeight) {
                   1642:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1643:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1644:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1645:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1646:     }
                   1647:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1648:         Geometry.getViewportHeight =
                   1649:             function() { return document.documentElement.clientHeight; };
                   1650:         Geometry.getViewportWidth =
                   1651:             function() { return document.documentElement.clientWidth; };
                   1652: 
                   1653:         Geometry.getHorizontalScroll =
                   1654:             function() { return document.documentElement.scrollLeft; };
                   1655:         Geometry.getVerticalScroll =
                   1656:             function() { return document.documentElement.scrollTop; };
                   1657:     }
                   1658:     else if (document.body.clientHeight) {
                   1659:         Geometry.getViewportHeight =
                   1660:             function() { return document.body.clientHeight; };
                   1661:         Geometry.getViewportWidth =
                   1662:             function() { return document.body.clientWidth; };
                   1663:         Geometry.getHorizontalScroll =
                   1664:             function() { return document.body.scrollLeft; };
                   1665:         Geometry.getVerticalScroll =
                   1666:             function() { return document.body.scrollTop; };
                   1667:     }
                   1668: }
                   1669: 
                   1670: GEOMETRY
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_size_js()
1.590     raeburn  1676: 
                   1677: 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. 
                   1678: 
                   1679: =cut
                   1680: 
                   1681: sub viewport_size_js {
                   1682:     my $geometry = &viewport_geometry_js();
                   1683:     return <<"DIMS";
                   1684: 
                   1685: $geometry
                   1686: 
                   1687: function getViewportDims(width,height) {
                   1688:     init_geometry();
                   1689:     width.value = Geometry.getViewportWidth();
                   1690:     height.value = Geometry.getViewportHeight();
                   1691:     return;
                   1692: }
                   1693: 
                   1694: DIMS
                   1695: }
                   1696: 
                   1697: =pod
                   1698: 
1.648     raeburn  1699: =item * &resize_textarea_js()
1.565     albertel 1700: 
                   1701: emits the needed javascript to resize a textarea to be as big as possible
                   1702: 
                   1703: creates a function resize_textrea that takes two IDs first should be
                   1704: the id of the element to resize, second should be the id of a div that
                   1705: surrounds everything that comes after the textarea, this routine needs
                   1706: to be attached to the <body> for the onload and onresize events.
                   1707: 
1.648     raeburn  1708: =back
1.565     albertel 1709: 
                   1710: =cut
                   1711: 
                   1712: sub resize_textarea_js {
1.590     raeburn  1713:     my $geometry = &viewport_geometry_js();
1.565     albertel 1714:     return <<"RESIZE";
                   1715:     <script type="text/javascript">
1.824     bisitz   1716: // <![CDATA[
1.590     raeburn  1717: $geometry
1.565     albertel 1718: 
1.588     albertel 1719: function getX(element) {
                   1720:     var x = 0;
                   1721:     while (element) {
                   1722: 	x += element.offsetLeft;
                   1723: 	element = element.offsetParent;
                   1724:     }
                   1725:     return x;
                   1726: }
                   1727: function getY(element) {
                   1728:     var y = 0;
                   1729:     while (element) {
                   1730: 	y += element.offsetTop;
                   1731: 	element = element.offsetParent;
                   1732:     }
                   1733:     return y;
                   1734: }
                   1735: 
                   1736: 
1.565     albertel 1737: function resize_textarea(textarea_id,bottom_id) {
                   1738:     init_geometry();
                   1739:     var textarea        = document.getElementById(textarea_id);
                   1740:     //alert(textarea);
                   1741: 
1.588     albertel 1742:     var textarea_top    = getY(textarea);
1.565     albertel 1743:     var textarea_height = textarea.offsetHeight;
                   1744:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1745:     var bottom_top      = getY(bottom);
1.565     albertel 1746:     var bottom_height   = bottom.offsetHeight;
                   1747:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1748:     var fudge           = 23;
1.565     albertel 1749:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1750:     if (new_height < 300) {
                   1751: 	new_height = 300;
                   1752:     }
                   1753:     textarea.style.height=new_height+'px';
                   1754: }
1.824     bisitz   1755: // ]]>
1.565     albertel 1756: </script>
                   1757: RESIZE
                   1758: 
                   1759: }
                   1760: 
1.1075.2.112  raeburn  1761: sub colorfuleditor_js {
                   1762:     return <<"COLORFULEDIT"
                   1763: <script type="text/javascript">
                   1764: // <![CDATA[>
                   1765:     function fold_box(curDepth, lastresource){
                   1766: 
                   1767:     // we need a list because there can be several blocks you need to fold in one tag
                   1768:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1769:     // but there is only one folding button per tag
                   1770:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1771: 
                   1772:         if(block.item(0).style.display == 'none'){
                   1773: 
                   1774:             foldbutton.value = '@{[&mt("Hide")]}';
                   1775:             for (i = 0; i < block.length; i++){
                   1776:                 block.item(i).style.display = '';
                   1777:             }
                   1778:         }else{
                   1779: 
                   1780:             foldbutton.value = '@{[&mt("Show")]}';
                   1781:             for (i = 0; i < block.length; i++){
                   1782:                 // block.item(i).style.visibility = 'collapse';
                   1783:                 block.item(i).style.display = 'none';
                   1784:             }
                   1785:         };
                   1786:         saveState(lastresource);
                   1787:     }
                   1788: 
                   1789:     function saveState (lastresource) {
                   1790: 
                   1791:         var tag_list = getTagList();
                   1792:         if(tag_list != null){
                   1793:             var timestamp = new Date().getTime();
                   1794:             var key = lastresource;
                   1795: 
                   1796:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1797:             // starting with timestamp
                   1798:             var value = timestamp+';';
                   1799: 
                   1800:             // building the list of key-value pairs
                   1801:             for(var i = 0; i < tag_list.length; i++){
                   1802:                 value += tag_list[i]+',';
                   1803:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1804:             }
                   1805: 
                   1806:             // only iterate whole storage if nothing to override
                   1807:             if(localStorage.getItem(key) == null){
                   1808: 
                   1809:                 // prevent storage from growing large
                   1810:                 if(localStorage.length > 50){
                   1811:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1812:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1813:                     var oldest_key;
                   1814: 
                   1815:                     for(var i = 1; i < localStorage.length; i++){
                   1816:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1817:                             oldest_key = localStorage.key(i);
                   1818:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1819:                         }
                   1820:                     }
                   1821:                     localStorage.removeItem(oldest_key);
                   1822:                 }
                   1823:             }
                   1824:             localStorage.setItem(key,value);
                   1825:         }
                   1826:     }
                   1827: 
                   1828:     // restore folding status of blocks (on page load)
                   1829:     function restoreState (lastresource) {
                   1830:         if(localStorage.getItem(lastresource) != null){
                   1831:             var key = lastresource;
                   1832:             var value = localStorage.getItem(key);
                   1833:             var regex_delTimestamp = /^\d+;/;
                   1834: 
                   1835:             value.replace(regex_delTimestamp, '');
                   1836: 
                   1837:             var valueArr = value.split(';');
                   1838:             var pairs;
                   1839:             var elements;
                   1840:             for (var i = 0; i < valueArr.length; i++){
                   1841:                 pairs = valueArr[i].split(',');
                   1842:                 elements = document.getElementsByName(pairs[0]);
                   1843: 
                   1844:                 for (var j = 0; j < elements.length; j++){
                   1845:                     elements[j].style.display = pairs[1];
                   1846:                     if (pairs[1] == "none"){
                   1847:                         var regex_id = /([_\\d]+)\$/;
                   1848:                         regex_id.exec(pairs[0]);
                   1849:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1850:                     }
                   1851:                 }
                   1852:             }
                   1853:         }
                   1854:     }
                   1855: 
                   1856:     function getTagList () {
                   1857: 
                   1858:         var stringToSearch = document.lonhomework.innerHTML;
                   1859: 
                   1860:         var ret = new Array();
                   1861:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1862:         var tag_list = stringToSearch.match(regex_findBlock);
                   1863: 
                   1864:         if(tag_list != null){
                   1865:             for(var i = 0; i < tag_list.length; i++){
                   1866:                 ret.push(tag_list[i].replace(/"/, ''));
                   1867:             }
                   1868:         }
                   1869:         return ret;
                   1870:     }
                   1871: 
                   1872:     function saveScrollPosition (resource) {
                   1873:         var tag_list = getTagList();
                   1874: 
                   1875:         // we dont always want to jump to the first block
                   1876:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1877:         if(\$(window).scrollTop() > 170){
                   1878:             if(tag_list != null){
                   1879:                 var result;
                   1880:                 for(var i = 0; i < tag_list.length; i++){
                   1881:                     if(isElementInViewport(tag_list[i])){
                   1882:                         result += tag_list[i]+';';
                   1883:                     }
                   1884:                 }
                   1885:                 sessionStorage.setItem('anchor_'+resource, result);
                   1886:             }
                   1887:         } else {
                   1888:             // we dont need to save zero, just delete the item to leave everything tidy
                   1889:             sessionStorage.removeItem('anchor_'+resource);
                   1890:         }
                   1891:     }
                   1892: 
                   1893:     function restoreScrollPosition(resource){
                   1894: 
                   1895:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1896:         if(elem != null){
                   1897:             var tag_list = elem.split(';');
                   1898:             var elem_list;
                   1899: 
                   1900:             for(var i = 0; i < tag_list.length; i++){
                   1901:                 elem_list = document.getElementsByName(tag_list[i]);
                   1902: 
                   1903:                 if(elem_list.length > 0){
                   1904:                     elem = elem_list[0];
                   1905:                     break;
                   1906:                 }
                   1907:             }
                   1908:             elem.scrollIntoView();
                   1909:         }
                   1910:     }
                   1911: 
                   1912:     function isElementInViewport(el) {
                   1913: 
                   1914:         // change to last element instead of first
                   1915:         var elem = document.getElementsByName(el);
                   1916:         var rect = elem[0].getBoundingClientRect();
                   1917: 
                   1918:         return (
                   1919:             rect.top >= 0 &&
                   1920:             rect.left >= 0 &&
                   1921:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1922:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1923:         );
                   1924:     }
                   1925: 
                   1926:     function autosize(depth){
                   1927:         var cmInst = window['cm'+depth];
                   1928:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1929: 
                   1930:         // is fixed size, switching to dynamic
                   1931:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1932:             cmInst.setSize("","auto");
                   1933:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1934:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1935: 
                   1936:         // is dynamic size, switching to fixed
                   1937:         } else {
                   1938:             cmInst.setSize("","300px");
                   1939:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1940:             sessionStorage.removeItem("autosized_"+depth);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: 
                   1945: 
                   1946: // ]]>
                   1947: </script>
                   1948: COLORFULEDIT
                   1949: }
                   1950: 
                   1951: sub xmleditor_js {
                   1952:     return <<XMLEDIT
                   1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1954: <script type="text/javascript">
                   1955: // <![CDATA[>
                   1956: 
                   1957:     function saveScrollPosition (resource) {
                   1958: 
                   1959:         var scrollPos = \$(window).scrollTop();
                   1960:         sessionStorage.setItem(resource,scrollPos);
                   1961:     }
                   1962: 
                   1963:     function restoreScrollPosition(resource){
                   1964: 
                   1965:         var scrollPos = sessionStorage.getItem(resource);
                   1966:         \$(window).scrollTop(scrollPos);
                   1967:     }
                   1968: 
                   1969:     // unless internet explorer
                   1970:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1971: 
                   1972:         \$(document).ready(function() {
                   1973:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1974:         });
                   1975:     }
                   1976: 
                   1977:     // inserts text at cursor position into codemirror (xml editor only)
                   1978:     function insertText(text){
                   1979:         cm.focus();
                   1980:         var curPos = cm.getCursor();
                   1981:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1982:     }
                   1983: // ]]>
                   1984: </script>
                   1985: XMLEDIT
                   1986: }
                   1987: 
                   1988: sub insert_folding_button {
                   1989:     my $curDepth = $Apache::lonxml::curdepth;
                   1990:     my $lastresource = $env{'request.ambiguous'};
                   1991: 
                   1992:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1993:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1994: }
                   1995: 
                   1996: 
1.565     albertel 1997: =pod
                   1998: 
1.256     matthew  1999: =head1 Excel and CSV file utility routines
                   2000: 
                   2001: =cut
                   2002: 
                   2003: ###############################################################
                   2004: ###############################################################
                   2005: 
                   2006: =pod
                   2007: 
1.1075.2.56  raeburn  2008: =over 4
                   2009: 
1.648     raeburn  2010: =item * &csv_translate($text) 
1.37      matthew  2011: 
1.185     www      2012: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2013: format.
                   2014: 
                   2015: =cut
                   2016: 
1.180     matthew  2017: ###############################################################
                   2018: ###############################################################
1.37      matthew  2019: sub csv_translate {
                   2020:     my $text = shift;
                   2021:     $text =~ s/\"/\"\"/g;
1.209     albertel 2022:     $text =~ s/\n/ /g;
1.37      matthew  2023:     return $text;
                   2024: }
1.180     matthew  2025: 
                   2026: ###############################################################
                   2027: ###############################################################
                   2028: 
                   2029: =pod
                   2030: 
1.648     raeburn  2031: =item * &define_excel_formats()
1.180     matthew  2032: 
                   2033: Define some commonly used Excel cell formats.
                   2034: 
                   2035: Currently supported formats:
                   2036: 
                   2037: =over 4
                   2038: 
                   2039: =item header
                   2040: 
                   2041: =item bold
                   2042: 
                   2043: =item h1
                   2044: 
                   2045: =item h2
                   2046: 
                   2047: =item h3
                   2048: 
1.256     matthew  2049: =item h4
                   2050: 
                   2051: =item i
                   2052: 
1.180     matthew  2053: =item date
                   2054: 
                   2055: =back
                   2056: 
                   2057: Inputs: $workbook
                   2058: 
                   2059: Returns: $format, a hash reference.
                   2060: 
1.1057    foxr     2061: 
1.180     matthew  2062: =cut
                   2063: 
                   2064: ###############################################################
                   2065: ###############################################################
                   2066: sub define_excel_formats {
                   2067:     my ($workbook) = @_;
                   2068:     my $format;
                   2069:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2070:                                                 bottom    => 1,
                   2071:                                                 align     => 'center');
                   2072:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2073:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2074:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2075:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2076:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2077:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2078:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2079:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2080:     return $format;
                   2081: }
                   2082: 
                   2083: ###############################################################
                   2084: ###############################################################
1.113     bowersj2 2085: 
                   2086: =pod
                   2087: 
1.648     raeburn  2088: =item * &create_workbook()
1.255     matthew  2089: 
                   2090: Create an Excel worksheet.  If it fails, output message on the
                   2091: request object and return undefs.
                   2092: 
                   2093: Inputs: Apache request object
                   2094: 
                   2095: Returns (undef) on failure, 
                   2096:     Excel worksheet object, scalar with filename, and formats 
                   2097:     from &Apache::loncommon::define_excel_formats on success
                   2098: 
                   2099: =cut
                   2100: 
                   2101: ###############################################################
                   2102: ###############################################################
                   2103: sub create_workbook {
                   2104:     my ($r) = @_;
                   2105:         #
                   2106:     # Create the excel spreadsheet
                   2107:     my $filename = '/prtspool/'.
1.258     albertel 2108:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2109:         time.'_'.rand(1000000000).'.xls';
                   2110:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2111:     if (! defined($workbook)) {
                   2112:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2113:         $r->print(
                   2114:             '<p class="LC_error">'
                   2115:            .&mt('Problems occurred in creating the new Excel file.')
                   2116:            .' '.&mt('This error has been logged.')
                   2117:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2118:            .'</p>'
                   2119:         );
1.255     matthew  2120:         return (undef);
                   2121:     }
                   2122:     #
1.1014    foxr     2123:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2124:     #
                   2125:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2126:     return ($workbook,$filename,$format);
                   2127: }
                   2128: 
                   2129: ###############################################################
                   2130: ###############################################################
                   2131: 
                   2132: =pod
                   2133: 
1.648     raeburn  2134: =item * &create_text_file()
1.113     bowersj2 2135: 
1.542     raeburn  2136: Create a file to write to and eventually make available to the user.
1.256     matthew  2137: If file creation fails, outputs an error message on the request object and 
                   2138: return undefs.
1.113     bowersj2 2139: 
1.256     matthew  2140: Inputs: Apache request object, and file suffix
1.113     bowersj2 2141: 
1.256     matthew  2142: Returns (undef) on failure, 
                   2143:     Filehandle and filename on success.
1.113     bowersj2 2144: 
                   2145: =cut
                   2146: 
1.256     matthew  2147: ###############################################################
                   2148: ###############################################################
                   2149: sub create_text_file {
                   2150:     my ($r,$suffix) = @_;
                   2151:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2152:     my $fh;
                   2153:     my $filename = '/prtspool/'.
1.258     albertel 2154:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2155:         time.'_'.rand(1000000000).'.'.$suffix;
                   2156:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2157:     if (! defined($fh)) {
                   2158:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2159:         $r->print(
                   2160:             '<p class="LC_error">'
                   2161:            .&mt('Problems occurred in creating the output file.')
                   2162:            .' '.&mt('This error has been logged.')
                   2163:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2164:            .'</p>'
                   2165:         );
1.113     bowersj2 2166:     }
1.256     matthew  2167:     return ($fh,$filename)
1.113     bowersj2 2168: }
                   2169: 
                   2170: 
1.256     matthew  2171: =pod 
1.113     bowersj2 2172: 
                   2173: =back
                   2174: 
                   2175: =cut
1.37      matthew  2176: 
                   2177: ###############################################################
1.33      matthew  2178: ##        Home server <option> list generating code          ##
                   2179: ###############################################################
1.35      matthew  2180: 
1.169     www      2181: # ------------------------------------------
                   2182: 
                   2183: sub domain_select {
                   2184:     my ($name,$value,$multiple)=@_;
                   2185:     my %domains=map { 
1.514     albertel 2186: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2187:     } &Apache::lonnet::all_domains();
1.169     www      2188:     if ($multiple) {
                   2189: 	$domains{''}=&mt('Any domain');
1.550     albertel 2190: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2191: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2192:     } else {
1.550     albertel 2193: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2194: 	return &select_form($name,$value,\%domains);
1.169     www      2195:     }
                   2196: }
                   2197: 
1.282     albertel 2198: #-------------------------------------------
                   2199: 
                   2200: =pod
                   2201: 
1.519     raeburn  2202: =head1 Routines for form select boxes
                   2203: 
                   2204: =over 4
                   2205: 
1.648     raeburn  2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2207: 
                   2208: Returns a string containing a <select> element int multiple mode
                   2209: 
                   2210: 
                   2211: Args:
                   2212:   $name - name of the <select> element
1.506     raeburn  2213:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2214:   $size - number of rows long the select element is
1.283     albertel 2215:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2216:           (shown text should already have been &mt())
1.506     raeburn  2217:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2218: 
1.282     albertel 2219: =cut
                   2220: 
                   2221: #-------------------------------------------
1.169     www      2222: sub multiple_select_form {
1.284     albertel 2223:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2224:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2225:     my $output='';
1.191     matthew  2226:     if (! defined($size)) {
                   2227:         $size = 4;
1.283     albertel 2228:         if (scalar(keys(%$hash))<4) {
                   2229:             $size = scalar(keys(%$hash));
1.191     matthew  2230:         }
                   2231:     }
1.734     bisitz   2232:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2233:     my @order;
1.506     raeburn  2234:     if (ref($order) eq 'ARRAY')  {
                   2235:         @order = @{$order};
                   2236:     } else {
                   2237:         @order = sort(keys(%$hash));
1.501     banghart 2238:     }
                   2239:     if (exists($$hash{'select_form_order'})) {
                   2240:         @order = @{$$hash{'select_form_order'}};
                   2241:     }
                   2242:         
1.284     albertel 2243:     foreach my $key (@order) {
1.356     albertel 2244:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2245:         $output.='selected="selected" ' if ($selected{$key});
                   2246:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2247:     }
                   2248:     $output.="</select>\n";
                   2249:     return $output;
                   2250: }
                   2251: 
1.88      www      2252: #-------------------------------------------
                   2253: 
                   2254: =pod
                   2255: 
1.1075.2.115  raeburn  2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2257: 
                   2258: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2259: allow a user to select options from a ref to a hash containing:
                   2260: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2261: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2262: An optional arg -- $readonly -- if true will cause the select form
                   2263: to be disabled, e.g., for the case where an instructor has a section-
                   2264: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2265: 
1.88      www      2266: See lonrights.pm for an example invocation and use.
                   2267: 
                   2268: =cut
                   2269: 
                   2270: #-------------------------------------------
                   2271: sub select_form {
1.1075.2.115  raeburn  2272:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2273:     return unless (ref($hashref) eq 'HASH');
                   2274:     if ($onchange) {
                   2275:         $onchange = ' onchange="'.$onchange.'"';
                   2276:     }
1.1075.2.129  raeburn  2277:     my $disabled;
                   2278:     if ($readonly) {
                   2279:         $disabled = ' disabled="disabled"';
                   2280:     }
                   2281:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2282:     my @keys;
1.970     raeburn  2283:     if (exists($hashref->{'select_form_order'})) {
                   2284: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2285:     } else {
1.970     raeburn  2286: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2287:     }
1.356     albertel 2288:     foreach my $key (@keys) {
                   2289:         $selectform.=
                   2290: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2291:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2292:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2293:     }
                   2294:     $selectform.="</select>";
                   2295:     return $selectform;
                   2296: }
                   2297: 
1.475     www      2298: # For display filters
                   2299: 
                   2300: sub display_filter {
1.1074    raeburn  2301:     my ($context) = @_;
1.475     www      2302:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2303:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2304:     my $phraseinput = 'hidden';
                   2305:     my $includeinput = 'hidden';
                   2306:     my ($checked,$includetypestext);
                   2307:     if ($env{'form.displayfilter'} eq 'containing') {
                   2308:         $phraseinput = 'text'; 
                   2309:         if ($context eq 'parmslog') {
                   2310:             $includeinput = 'checkbox';
                   2311:             if ($env{'form.includetypes'}) {
                   2312:                 $checked = ' checked="checked"';
                   2313:             }
                   2314:             $includetypestext = &mt('Include parameter types');
                   2315:         }
                   2316:     } else {
                   2317:         $includetypestext = '&nbsp;';
                   2318:     }
                   2319:     my ($additional,$secondid,$thirdid);
                   2320:     if ($context eq 'parmslog') {
                   2321:         $additional = 
                   2322:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2323:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2324:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2325:             '</label>';
                   2326:         $secondid = 'includetypes';
                   2327:         $thirdid = 'includetypestext';
                   2328:     }
                   2329:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2330:                                                     '$secondid','$thirdid')";
                   2331:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2332: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2333: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2334: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2335:            &mt('Filter: [_1]',
1.477     www      2336: 	   &select_form($env{'form.displayfilter'},
                   2337: 			'displayfilter',
1.970     raeburn  2338: 			{'currentfolder' => 'Current folder/page',
1.477     www      2339: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2340: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2341: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2342:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2343:                          '" />'.$additional;
                   2344: }
                   2345: 
                   2346: sub display_filter_js {
                   2347:     my $includetext = &mt('Include parameter types');
                   2348:     return <<"ENDJS";
                   2349:   
                   2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2351:     var firstType = 'hidden';
                   2352:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2353:         firstType = 'text';
                   2354:     }
                   2355:     firstObject = document.getElementById(firstid);
                   2356:     if (typeof(firstObject) == 'object') {
                   2357:         if (firstObject.type != firstType) {
                   2358:             changeInputType(firstObject,firstType);
                   2359:         }
                   2360:     }
                   2361:     if (context == 'parmslog') {
                   2362:         var secondType = 'hidden';
                   2363:         if (firstType == 'text') {
                   2364:             secondType = 'checkbox';
                   2365:         }
                   2366:         secondObject = document.getElementById(secondid);  
                   2367:         if (typeof(secondObject) == 'object') {
                   2368:             if (secondObject.type != secondType) {
                   2369:                 changeInputType(secondObject,secondType);
                   2370:             }
                   2371:         }
                   2372:         var textItem = document.getElementById(thirdid);
                   2373:         var currtext = textItem.innerHTML;
                   2374:         var newtext;
                   2375:         if (firstType == 'text') {
                   2376:             newtext = '$includetext';
                   2377:         } else {
                   2378:             newtext = '&nbsp;';
                   2379:         }
                   2380:         if (currtext != newtext) {
                   2381:             textItem.innerHTML = newtext;
                   2382:         }
                   2383:     }
                   2384:     return;
                   2385: }
                   2386: 
                   2387: function changeInputType(oldObject,newType) {
                   2388:     var newObject = document.createElement('input');
                   2389:     newObject.type = newType;
                   2390:     if (oldObject.size) {
                   2391:         newObject.size = oldObject.size;
                   2392:     }
                   2393:     if (oldObject.value) {
                   2394:         newObject.value = oldObject.value;
                   2395:     }
                   2396:     if (oldObject.name) {
                   2397:         newObject.name = oldObject.name;
                   2398:     }
                   2399:     if (oldObject.id) {
                   2400:         newObject.id = oldObject.id;
                   2401:     }
                   2402:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2403:     return;
                   2404: }
                   2405: 
                   2406: ENDJS
1.475     www      2407: }
                   2408: 
1.167     www      2409: sub gradeleveldescription {
                   2410:     my $gradelevel=shift;
                   2411:     my %gradelevels=(0 => 'Not specified',
                   2412: 		     1 => 'Grade 1',
                   2413: 		     2 => 'Grade 2',
                   2414: 		     3 => 'Grade 3',
                   2415: 		     4 => 'Grade 4',
                   2416: 		     5 => 'Grade 5',
                   2417: 		     6 => 'Grade 6',
                   2418: 		     7 => 'Grade 7',
                   2419: 		     8 => 'Grade 8',
                   2420: 		     9 => 'Grade 9',
                   2421: 		     10 => 'Grade 10',
                   2422: 		     11 => 'Grade 11',
                   2423: 		     12 => 'Grade 12',
                   2424: 		     13 => 'Grade 13',
                   2425: 		     14 => '100 Level',
                   2426: 		     15 => '200 Level',
                   2427: 		     16 => '300 Level',
                   2428: 		     17 => '400 Level',
                   2429: 		     18 => 'Graduate Level');
                   2430:     return &mt($gradelevels{$gradelevel});
                   2431: }
                   2432: 
1.163     www      2433: sub select_level_form {
                   2434:     my ($deflevel,$name)=@_;
                   2435:     unless ($deflevel) { $deflevel=0; }
1.167     www      2436:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2437:     for (my $i=0; $i<=18; $i++) {
                   2438:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2439:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2440:                 ">".&gradeleveldescription($i)."</option>\n";
                   2441:     }
                   2442:     $selectform.="</select>";
                   2443:     return $selectform;
1.163     www      2444: }
1.167     www      2445: 
1.35      matthew  2446: #-------------------------------------------
                   2447: 
1.45      matthew  2448: =pod
                   2449: 
1.1075.2.115  raeburn  2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2451: 
                   2452: Returns a string containing a <select name='$name' size='1'> form to 
                   2453: allow a user to select the domain to preform an operation in.  
                   2454: See loncreateuser.pm for an example invocation and use.
                   2455: 
1.90      www      2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2457: selected");
                   2458: 
1.743     raeburn  2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2460: 
1.910     raeburn  2461: 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.
                   2462: 
1.1075.2.36  raeburn  2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2464: 
1.1075.2.115  raeburn  2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2466: 
                   2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2468: 
1.35      matthew  2469: =cut
                   2470: 
                   2471: #-------------------------------------------
1.34      matthew  2472: sub select_dom_form {
1.1075.2.115  raeburn  2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2474:     if ($onchange) {
1.874     raeburn  2475:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2476:     }
1.1075.2.115  raeburn  2477:     if ($disabled) {
                   2478:         $disabled = ' disabled="disabled"';
                   2479:     }
1.1075.2.36  raeburn  2480:     my (@domains,%exclude);
1.910     raeburn  2481:     if (ref($incdoms) eq 'ARRAY') {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2483:     } else {
                   2484:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2485:     }
1.90      www      2486:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2487:     if (ref($excdoms) eq 'ARRAY') {
                   2488:         map { $exclude{$_} = 1; } @{$excdoms};
                   2489:     }
1.1075.2.115  raeburn  2490:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2491:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2492:         next if ($exclude{$dom});
1.356     albertel 2493:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2494:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2495:         if ($showdomdesc) {
                   2496:             if ($dom ne '') {
                   2497:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2498:                 if ($domdesc ne '') {
                   2499:                     $selectdomain .= ' ('.$domdesc.')';
                   2500:                 }
                   2501:             } 
                   2502:         }
                   2503:         $selectdomain .= "</option>\n";
1.34      matthew  2504:     }
                   2505:     $selectdomain.="</select>";
                   2506:     return $selectdomain;
                   2507: }
                   2508: 
1.35      matthew  2509: #-------------------------------------------
                   2510: 
1.45      matthew  2511: =pod
                   2512: 
1.648     raeburn  2513: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2514: 
1.586     raeburn  2515: input: 4 arguments (two required, two optional) - 
                   2516:     $domain - domain of new user
                   2517:     $name - name of form element
                   2518:     $default - Value of 'default' causes a default item to be first 
                   2519:                             option, and selected by default. 
                   2520:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2521:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2522: output: returns 2 items: 
1.586     raeburn  2523: (a) form element which contains either:
                   2524:    (i) <select name="$name">
                   2525:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2526:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2527:        </select>
                   2528:        form item if there are multiple library servers in $domain, or
                   2529:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2530:        if there is only one library server in $domain.
                   2531: 
                   2532: (b) number of library servers found.
                   2533: 
                   2534: See loncreateuser.pm for example of use.
1.35      matthew  2535: 
                   2536: =cut
                   2537: 
                   2538: #-------------------------------------------
1.586     raeburn  2539: sub home_server_form_item {
                   2540:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2541:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2542:     my $result;
                   2543:     my $numlib = keys(%servers);
                   2544:     if ($numlib > 1) {
                   2545:         $result .= '<select name="'.$name.'" />'."\n";
                   2546:         if ($default) {
1.804     bisitz   2547:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2548:                        '</option>'."\n";
                   2549:         }
                   2550:         foreach my $hostid (sort(keys(%servers))) {
                   2551:             $result.= '<option value="'.$hostid.'">'.
                   2552: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2553:         }
                   2554:         $result .= '</select>'."\n";
                   2555:     } elsif ($numlib == 1) {
                   2556:         my $hostid;
                   2557:         foreach my $item (keys(%servers)) {
                   2558:             $hostid = $item;
                   2559:         }
                   2560:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2561:                    $hostid.'" />';
                   2562:                    if (!$hide) {
                   2563:                        $result .= $hostid.' '.$servers{$hostid};
                   2564:                    }
                   2565:                    $result .= "\n";
                   2566:     } elsif ($default) {
                   2567:         $result .= '<input type="hidden" name="'.$name.
                   2568:                    '" value="default" />';
                   2569:                    if (!$hide) {
                   2570:                        $result .= &mt('default');
                   2571:                    }
                   2572:                    $result .= "\n";
1.33      matthew  2573:     }
1.586     raeburn  2574:     return ($result,$numlib);
1.33      matthew  2575: }
1.112     bowersj2 2576: 
                   2577: =pod
                   2578: 
1.534     albertel 2579: =back 
                   2580: 
1.112     bowersj2 2581: =cut
1.87      matthew  2582: 
                   2583: ###############################################################
1.112     bowersj2 2584: ##                  Decoding User Agent                      ##
1.87      matthew  2585: ###############################################################
                   2586: 
                   2587: =pod
                   2588: 
1.112     bowersj2 2589: =head1 Decoding the User Agent
                   2590: 
                   2591: =over 4
                   2592: 
                   2593: =item * &decode_user_agent()
1.87      matthew  2594: 
                   2595: Inputs: $r
                   2596: 
                   2597: Outputs:
                   2598: 
                   2599: =over 4
                   2600: 
1.112     bowersj2 2601: =item * $httpbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientbrowser
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientversion
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientmathml
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientunicode
1.87      matthew  2610: 
1.112     bowersj2 2611: =item * $clientos
1.87      matthew  2612: 
1.1075.2.42  raeburn  2613: =item * $clientmobile
                   2614: 
                   2615: =item * $clientinfo
                   2616: 
1.1075.2.77  raeburn  2617: =item * $clientosversion
                   2618: 
1.87      matthew  2619: =back
                   2620: 
1.157     matthew  2621: =back 
                   2622: 
1.87      matthew  2623: =cut
                   2624: 
                   2625: ###############################################################
                   2626: ###############################################################
                   2627: sub decode_user_agent {
1.247     albertel 2628:     my ($r)=@_;
1.87      matthew  2629:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2630:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2631:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2632:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2633:     my $clientbrowser='unknown';
                   2634:     my $clientversion='0';
                   2635:     my $clientmathml='';
                   2636:     my $clientunicode='0';
1.1075.2.42  raeburn  2637:     my $clientmobile=0;
1.1075.2.77  raeburn  2638:     my $clientosversion='';
1.87      matthew  2639:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2640:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2641: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2642: 	    $clientbrowser=$bname;
                   2643:             $httpbrowser=~/$vreg/i;
                   2644: 	    $clientversion=$1;
                   2645:             $clientmathml=($clientversion>=$minv);
                   2646:             $clientunicode=($clientversion>=$univ);
                   2647: 	}
                   2648:     }
                   2649:     my $clientos='unknown';
1.1075.2.42  raeburn  2650:     my $clientinfo;
1.87      matthew  2651:     if (($httpbrowser=~/linux/i) ||
                   2652:         ($httpbrowser=~/unix/i) ||
                   2653:         ($httpbrowser=~/ux/i) ||
                   2654:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2655:     if (($httpbrowser=~/vax/i) ||
                   2656:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2657:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2658:     if (($httpbrowser=~/mac/i) ||
                   2659:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2660:     if ($httpbrowser=~/win/i) {
                   2661:         $clientos='win';
                   2662:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2663:             $clientosversion = $1;
                   2664:         }
                   2665:     }
1.87      matthew  2666:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2667:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2668:         $clientmobile=lc($1);
                   2669:     }
                   2670:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2671:         $clientinfo = 'firefox-'.$1;
                   2672:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2673:         $clientinfo = 'chromeframe-'.$1;
                   2674:     }
1.87      matthew  2675:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2676:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2677:             $clientosversion);
1.87      matthew  2678: }
                   2679: 
1.32      matthew  2680: ###############################################################
                   2681: ##    Authentication changing form generation subroutines    ##
                   2682: ###############################################################
                   2683: ##
                   2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2685: ## hash, and have reasonable default values.
                   2686: ##
                   2687: ##    formname = the name given in the <form> tag.
1.35      matthew  2688: #-------------------------------------------
                   2689: 
1.45      matthew  2690: =pod
                   2691: 
1.112     bowersj2 2692: =head1 Authentication Routines
                   2693: 
                   2694: =over 4
                   2695: 
1.648     raeburn  2696: =item * &authform_xxxxxx()
1.35      matthew  2697: 
                   2698: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2699: handle some of the conveniences required for authentication forms.  
                   2700: This is not an optimal method, but it works.  
                   2701: 
                   2702: =over 4
                   2703: 
1.112     bowersj2 2704: =item * authform_header
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_authorwarning
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_nochange
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_kerberos
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_internal
1.35      matthew  2713: 
1.112     bowersj2 2714: =item * authform_filesystem
1.35      matthew  2715: 
                   2716: =back
                   2717: 
1.648     raeburn  2718: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2719: 
1.35      matthew  2720: =cut
                   2721: 
                   2722: #-------------------------------------------
1.32      matthew  2723: sub authform_header{  
                   2724:     my %in = (
                   2725:         formname => 'cu',
1.80      albertel 2726:         kerb_def_dom => '',
1.32      matthew  2727:         @_,
                   2728:     );
                   2729:     $in{'formname'} = 'document.' . $in{'formname'};
                   2730:     my $result='';
1.80      albertel 2731: 
                   2732: #---------------------------------------------- Code for upper case translation
                   2733:     my $Javascript_toUpperCase;
                   2734:     unless ($in{kerb_def_dom}) {
                   2735:         $Javascript_toUpperCase =<<"END";
                   2736:         switch (choice) {
                   2737:            case 'krb': currentform.elements[choicearg].value =
                   2738:                currentform.elements[choicearg].value.toUpperCase();
                   2739:                break;
                   2740:            default:
                   2741:         }
                   2742: END
                   2743:     } else {
                   2744:         $Javascript_toUpperCase = "";
                   2745:     }
                   2746: 
1.165     raeburn  2747:     my $radioval = "'nochange'";
1.591     raeburn  2748:     if (defined($in{'curr_authtype'})) {
                   2749:         if ($in{'curr_authtype'} ne '') {
                   2750:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2751:         }
1.174     matthew  2752:     }
1.165     raeburn  2753:     my $argfield = 'null';
1.591     raeburn  2754:     if (defined($in{'mode'})) {
1.165     raeburn  2755:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2756:             if (defined($in{'curr_autharg'})) {
                   2757:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2758:                     $argfield = "'$in{'curr_autharg'}'";
                   2759:                 }
                   2760:             }
                   2761:         }
                   2762:     }
                   2763: 
1.32      matthew  2764:     $result.=<<"END";
                   2765: var current = new Object();
1.165     raeburn  2766: current.radiovalue = $radioval;
                   2767: current.argfield = $argfield;
1.32      matthew  2768: 
                   2769: function changed_radio(choice,currentform) {
                   2770:     var choicearg = choice + 'arg';
                   2771:     // If a radio button in changed, we need to change the argfield
                   2772:     if (current.radiovalue != choice) {
                   2773:         current.radiovalue = choice;
                   2774:         if (current.argfield != null) {
                   2775:             currentform.elements[current.argfield].value = '';
                   2776:         }
                   2777:         if (choice == 'nochange') {
                   2778:             current.argfield = null;
                   2779:         } else {
                   2780:             current.argfield = choicearg;
                   2781:             switch(choice) {
                   2782:                 case 'krb': 
                   2783:                     currentform.elements[current.argfield].value = 
                   2784:                         "$in{'kerb_def_dom'}";
                   2785:                 break;
                   2786:               default:
                   2787:                 break;
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return;
                   2792: }
1.22      www      2793: 
1.32      matthew  2794: function changed_text(choice,currentform) {
                   2795:     var choicearg = choice + 'arg';
                   2796:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2797:         $Javascript_toUpperCase
1.32      matthew  2798:         // clear old field
                   2799:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2800:             currentform.elements[current.argfield].value = '';
                   2801:         }
                   2802:         current.argfield = choicearg;
                   2803:     }
                   2804:     set_auth_radio_buttons(choice,currentform);
                   2805:     return;
1.20      www      2806: }
1.32      matthew  2807: 
                   2808: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2809:     var numauthchoices = currentform.login.length;
                   2810:     if (typeof numauthchoices  == "undefined") {
                   2811:         return;
                   2812:     } 
1.32      matthew  2813:     var i=0;
1.986     raeburn  2814:     while (i < numauthchoices) {
1.32      matthew  2815:         if (currentform.login[i].value == newvalue) { break; }
                   2816:         i++;
                   2817:     }
1.986     raeburn  2818:     if (i == numauthchoices) {
1.32      matthew  2819:         return;
                   2820:     }
                   2821:     current.radiovalue = newvalue;
                   2822:     currentform.login[i].checked = true;
                   2823:     return;
                   2824: }
                   2825: END
                   2826:     return $result;
                   2827: }
                   2828: 
1.1075.2.20  raeburn  2829: sub authform_authorwarning {
1.32      matthew  2830:     my $result='';
1.144     matthew  2831:     $result='<i>'.
                   2832:         &mt('As a general rule, only authors or co-authors should be '.
                   2833:             'filesystem authenticated '.
                   2834:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2835:     return $result;
                   2836: }
                   2837: 
1.1075.2.20  raeburn  2838: sub authform_nochange {
1.32      matthew  2839:     my %in = (
                   2840:               formname => 'document.cu',
                   2841:               kerb_def_dom => 'MSU.EDU',
                   2842:               @_,
                   2843:           );
1.1075.2.20  raeburn  2844:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2845:     my $result;
1.1075.2.20  raeburn  2846:     if (!$authnum) {
                   2847:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2848:     } else {
                   2849:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2850:                   '<input type="radio" name="login" value="nochange" '.
                   2851:                   'checked="checked" onclick="'.
1.281     albertel 2852:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2853: 	    '</label>';
1.586     raeburn  2854:     }
1.32      matthew  2855:     return $result;
                   2856: }
                   2857: 
1.591     raeburn  2858: sub authform_kerberos {
1.32      matthew  2859:     my %in = (
                   2860:               formname => 'document.cu',
                   2861:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2862:               kerb_def_auth => 'krb4',
1.32      matthew  2863:               @_,
                   2864:               );
1.586     raeburn  2865:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2866:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2867:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2868:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2869:        $check5 = ' checked="checked"';
1.80      albertel 2870:     } else {
1.772     bisitz   2871:        $check4 = ' checked="checked"';
1.80      albertel 2872:     }
1.1075.2.117  raeburn  2873:     if ($in{'readonly'}) {
                   2874:         $disabled = ' disabled="disabled"';
                   2875:     }
1.165     raeburn  2876:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2877:     if (defined($in{'curr_authtype'})) {
                   2878:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2879:             $krbcheck = ' checked="checked"';
1.623     raeburn  2880:             if (defined($in{'mode'})) {
                   2881:                 if ($in{'mode'} eq 'modifyuser') {
                   2882:                     $krbcheck = '';
                   2883:                 }
                   2884:             }
1.591     raeburn  2885:             if (defined($in{'curr_kerb_ver'})) {
                   2886:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2887:                     $check5 = ' checked="checked"';
1.591     raeburn  2888:                     $check4 = '';
                   2889:                 } else {
1.772     bisitz   2890:                     $check4 = ' checked="checked"';
1.591     raeburn  2891:                     $check5 = '';
                   2892:                 }
1.586     raeburn  2893:             }
1.591     raeburn  2894:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2895:                 $krbarg = $in{'curr_autharg'};
                   2896:             }
1.586     raeburn  2897:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2898:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2899:                     $result = 
                   2900:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2901:         $in{'curr_autharg'},$krbver);
                   2902:                 } else {
                   2903:                     $result =
                   2904:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2905:                 }
                   2906:                 return $result; 
                   2907:             }
                   2908:         }
                   2909:     } else {
                   2910:         if ($authnum == 1) {
1.784     bisitz   2911:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2912:         }
                   2913:     }
1.586     raeburn  2914:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2915:         return;
1.587     raeburn  2916:     } elsif ($authtype eq '') {
1.591     raeburn  2917:         if (defined($in{'mode'})) {
1.587     raeburn  2918:             if ($in{'mode'} eq 'modifycourse') {
                   2919:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2920:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2921:                 }
                   2922:             }
                   2923:         }
1.586     raeburn  2924:     }
                   2925:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2926:     if ($authtype eq '') {
                   2927:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2928:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2929:                     $krbcheck.$disabled.' />';
1.586     raeburn  2930:     }
                   2931:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2932:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2934:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2935:          $in{'curr_authtype'} eq 'krb4')) {
                   2936:         $result .= &mt
1.144     matthew  2937:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2938:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2939:          '<label>'.$authtype,
1.281     albertel 2940:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2941:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2942:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2943:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2944:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2945: 	 '</label>');
1.586     raeburn  2946:     } elsif ($can_assign{'krb4'}) {
                   2947:         $result .= &mt
                   2948:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2949:          '[_3] Version 4 [_4]',
                   2950:          '<label>'.$authtype,
                   2951:          '</label><input type="text" size="10" name="krbarg" '.
                   2952:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2953:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2954:          '<label><input type="hidden" name="krbver" value="4" />',
                   2955:          '</label>');
                   2956:     } elsif ($can_assign{'krb5'}) {
                   2957:         $result .= &mt
                   2958:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2959:          '[_3] Version 5 [_4]',
                   2960:          '<label>'.$authtype,
                   2961:          '</label><input type="text" size="10" name="krbarg" '.
                   2962:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2963:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2964:          '<label><input type="hidden" name="krbver" value="5" />',
                   2965:          '</label>');
                   2966:     }
1.32      matthew  2967:     return $result;
                   2968: }
                   2969: 
1.1075.2.20  raeburn  2970: sub authform_internal {
1.586     raeburn  2971:     my %in = (
1.32      matthew  2972:                 formname => 'document.cu',
                   2973:                 kerb_def_dom => 'MSU.EDU',
                   2974:                 @_,
                   2975:                 );
1.1075.2.117  raeburn  2976:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2977:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2978:     if ($in{'readonly'}) {
                   2979:         $disabled = ' disabled="disabled"';
                   2980:     }
1.591     raeburn  2981:     if (defined($in{'curr_authtype'})) {
                   2982:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2983:             if ($can_assign{'int'}) {
1.772     bisitz   2984:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2985:                 if (defined($in{'mode'})) {
                   2986:                     if ($in{'mode'} eq 'modifyuser') {
                   2987:                         $intcheck = '';
                   2988:                     }
                   2989:                 }
1.591     raeburn  2990:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2991:                     $intarg = $in{'curr_autharg'};
                   2992:                 }
                   2993:             } else {
                   2994:                 $result = &mt('Currently internally authenticated.');
                   2995:                 return $result;
1.165     raeburn  2996:             }
                   2997:         }
1.586     raeburn  2998:     } else {
                   2999:         if ($authnum == 1) {
1.784     bisitz   3000:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3001:         }
                   3002:     }
                   3003:     if (!$can_assign{'int'}) {
                   3004:         return;
1.587     raeburn  3005:     } elsif ($authtype eq '') {
1.591     raeburn  3006:         if (defined($in{'mode'})) {
1.587     raeburn  3007:             if ($in{'mode'} eq 'modifycourse') {
                   3008:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3009:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3010:                 }
                   3011:             }
                   3012:         }
1.165     raeburn  3013:     }
1.586     raeburn  3014:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3015:     if ($authtype eq '') {
                   3016:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3017:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3018:     }
1.605     bisitz   3019:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3020:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3021:     $result = &mt
1.144     matthew  3022:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3023:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3024:     $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  3025:     return $result;
                   3026: }
                   3027: 
1.1075.2.20  raeburn  3028: sub authform_local {
1.32      matthew  3029:     my %in = (
                   3030:               formname => 'document.cu',
                   3031:               kerb_def_dom => 'MSU.EDU',
                   3032:               @_,
                   3033:               );
1.1075.2.117  raeburn  3034:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3035:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3036:     if ($in{'readonly'}) {
                   3037:         $disabled = ' disabled="disabled"';
                   3038:     }
1.591     raeburn  3039:     if (defined($in{'curr_authtype'})) {
                   3040:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3041:             if ($can_assign{'loc'}) {
1.772     bisitz   3042:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3043:                 if (defined($in{'mode'})) {
                   3044:                     if ($in{'mode'} eq 'modifyuser') {
                   3045:                         $loccheck = '';
                   3046:                     }
                   3047:                 }
1.591     raeburn  3048:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3049:                     $locarg = $in{'curr_autharg'};
                   3050:                 }
                   3051:             } else {
                   3052:                 $result = &mt('Currently using local (institutional) authentication.');
                   3053:                 return $result;
1.165     raeburn  3054:             }
                   3055:         }
1.586     raeburn  3056:     } else {
                   3057:         if ($authnum == 1) {
1.784     bisitz   3058:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3059:         }
                   3060:     }
                   3061:     if (!$can_assign{'loc'}) {
                   3062:         return;
1.587     raeburn  3063:     } elsif ($authtype eq '') {
1.591     raeburn  3064:         if (defined($in{'mode'})) {
1.587     raeburn  3065:             if ($in{'mode'} eq 'modifycourse') {
                   3066:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3067:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3068:                 }
                   3069:             }
                   3070:         }
1.165     raeburn  3071:     }
1.586     raeburn  3072:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3073:     if ($authtype eq '') {
                   3074:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3075:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3076:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3077:     }
                   3078:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3079:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3080:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3081:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3082:     return $result;
                   3083: }
                   3084: 
1.1075.2.20  raeburn  3085: sub authform_filesystem {
1.32      matthew  3086:     my %in = (
                   3087:               formname => 'document.cu',
                   3088:               kerb_def_dom => 'MSU.EDU',
                   3089:               @_,
                   3090:               );
1.1075.2.117  raeburn  3091:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3092:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3093:     if ($in{'readonly'}) {
                   3094:         $disabled = ' disabled="disabled"';
                   3095:     }
1.591     raeburn  3096:     if (defined($in{'curr_authtype'})) {
                   3097:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3098:             if ($can_assign{'fsys'}) {
1.772     bisitz   3099:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3100:                 if (defined($in{'mode'})) {
                   3101:                     if ($in{'mode'} eq 'modifyuser') {
                   3102:                         $fsyscheck = '';
                   3103:                     }
                   3104:                 }
1.586     raeburn  3105:             } else {
                   3106:                 $result = &mt('Currently Filesystem Authenticated.');
                   3107:                 return $result;
                   3108:             }           
                   3109:         }
                   3110:     } else {
                   3111:         if ($authnum == 1) {
1.784     bisitz   3112:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3113:         }
                   3114:     }
                   3115:     if (!$can_assign{'fsys'}) {
                   3116:         return;
1.587     raeburn  3117:     } elsif ($authtype eq '') {
1.591     raeburn  3118:         if (defined($in{'mode'})) {
1.587     raeburn  3119:             if ($in{'mode'} eq 'modifycourse') {
                   3120:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3121:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3122:                 }
                   3123:             }
                   3124:         }
1.586     raeburn  3125:     }
                   3126:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3127:     if ($authtype eq '') {
                   3128:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3129:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3130:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3131:     }
1.1075.2.158  raeburn  3132:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3133:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3134:     $result = &mt
1.144     matthew  3135:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3136:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3137:     return $result;
                   3138: }
                   3139: 
1.586     raeburn  3140: sub get_assignable_auth {
                   3141:     my ($dom) = @_;
                   3142:     if ($dom eq '') {
                   3143:         $dom = $env{'request.role.domain'};
                   3144:     }
                   3145:     my %can_assign = (
                   3146:                           krb4 => 1,
                   3147:                           krb5 => 1,
                   3148:                           int  => 1,
                   3149:                           loc  => 1,
                   3150:                      );
                   3151:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3152:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3153:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3154:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3155:             my $context;
                   3156:             if ($env{'request.role'} =~ /^au/) {
                   3157:                 $context = 'author';
1.1075.2.117  raeburn  3158:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3159:                 $context = 'domain';
                   3160:             } elsif ($env{'request.course.id'}) {
                   3161:                 $context = 'course';
                   3162:             }
                   3163:             if ($context) {
                   3164:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3165:                    %can_assign = %{$authhash->{$context}}; 
                   3166:                 }
                   3167:             }
                   3168:         }
                   3169:     }
                   3170:     my $authnum = 0;
                   3171:     foreach my $key (keys(%can_assign)) {
                   3172:         if ($can_assign{$key}) {
                   3173:             $authnum ++;
                   3174:         }
                   3175:     }
                   3176:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3177:         $authnum --;
                   3178:     }
                   3179:     return ($authnum,%can_assign);
                   3180: }
                   3181: 
1.1075.2.137  raeburn  3182: sub check_passwd_rules {
                   3183:     my ($domain,$plainpass) = @_;
                   3184:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3185:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3186:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3187:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3188:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3189:             if ($passwdconf{'min'} > $min) {
                   3190:                 $min = $passwdconf{'min'};
                   3191:             }
1.1075.2.137  raeburn  3192:         }
                   3193:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3194:             $max = $passwdconf{'max'};
                   3195:         }
                   3196:         @chars = @{$passwdconf{'chars'}};
                   3197:     }
                   3198:     if (($min) && (length($plainpass) < $min)) {
                   3199:         push(@brokerule,'min');
                   3200:     }
                   3201:     if (($max) && (length($plainpass) > $max)) {
                   3202:         push(@brokerule,'max');
                   3203:     }
                   3204:     if (@chars) {
                   3205:         my %rules;
                   3206:         map { $rules{$_} = 1; } @chars;
                   3207:         if ($rules{'uc'}) {
                   3208:             unless ($plainpass =~ /[A-Z]/) {
                   3209:                 push(@brokerule,'uc');
                   3210:             }
                   3211:         }
                   3212:         if ($rules{'lc'}) {
                   3213:             unless ($plainpass =~ /[a-z]/) {
                   3214:                 push(@brokerule,'lc');
                   3215:             }
                   3216:         }
                   3217:         if ($rules{'num'}) {
                   3218:             unless ($plainpass =~ /\d/) {
                   3219:                 push(@brokerule,'num');
                   3220:             }
                   3221:         }
                   3222:         if ($rules{'spec'}) {
                   3223:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3224:                 push(@brokerule,'spec');
                   3225:             }
                   3226:         }
                   3227:     }
                   3228:     if (@brokerule) {
                   3229:         my %rulenames = &Apache::lonlocal::texthash(
                   3230:             uc   => 'At least one upper case letter',
                   3231:             lc   => 'At least one lower case letter',
                   3232:             num  => 'At least one number',
                   3233:             spec => 'At least one non-alphanumeric',
                   3234:         );
                   3235:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3236:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3237:         $rulenames{'num'} .= ': 0123456789';
                   3238:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3239:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3240:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3241:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3242:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3243:             if (grep(/^$rule$/,@brokerule)) {
                   3244:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3245:             }
                   3246:         }
                   3247:         $warning .= '</ul>';
                   3248:     }
                   3249:     if (wantarray) {
                   3250:         return @brokerule;
                   3251:     }
                   3252:     return $warning;
                   3253: }
                   3254: 
1.80      albertel 3255: ###############################################################
                   3256: ##    Get Kerberos Defaults for Domain                 ##
                   3257: ###############################################################
                   3258: ##
                   3259: ## Returns default kerberos version and an associated argument
                   3260: ## as listed in file domain.tab. If not listed, provides
                   3261: ## appropriate default domain and kerberos version.
                   3262: ##
                   3263: #-------------------------------------------
                   3264: 
                   3265: =pod
                   3266: 
1.648     raeburn  3267: =item * &get_kerberos_defaults()
1.80      albertel 3268: 
                   3269: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3270: version and domain. If not found, it defaults to version 4 and the 
                   3271: domain of the server.
1.80      albertel 3272: 
1.648     raeburn  3273: =over 4
                   3274: 
1.80      albertel 3275: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3276: 
1.648     raeburn  3277: =back
                   3278: 
                   3279: =back
                   3280: 
1.80      albertel 3281: =cut
                   3282: 
                   3283: #-------------------------------------------
                   3284: sub get_kerberos_defaults {
                   3285:     my $domain=shift;
1.641     raeburn  3286:     my ($krbdef,$krbdefdom);
                   3287:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3288:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3289:         $krbdef = $domdefaults{'auth_def'};
                   3290:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3291:     } else {
1.80      albertel 3292:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3293:         my $krbdefdom=$1;
                   3294:         $krbdefdom=~tr/a-z/A-Z/;
                   3295:         $krbdef = "krb4";
                   3296:     }
                   3297:     return ($krbdef,$krbdefdom);
                   3298: }
1.112     bowersj2 3299: 
1.32      matthew  3300: 
1.46      matthew  3301: ###############################################################
                   3302: ##                Thesaurus Functions                        ##
                   3303: ###############################################################
1.20      www      3304: 
1.46      matthew  3305: =pod
1.20      www      3306: 
1.112     bowersj2 3307: =head1 Thesaurus Functions
                   3308: 
                   3309: =over 4
                   3310: 
1.648     raeburn  3311: =item * &initialize_keywords()
1.46      matthew  3312: 
                   3313: Initializes the package variable %Keywords if it is empty.  Uses the
                   3314: package variable $thesaurus_db_file.
                   3315: 
                   3316: =cut
                   3317: 
                   3318: ###################################################
                   3319: 
                   3320: sub initialize_keywords {
                   3321:     return 1 if (scalar keys(%Keywords));
                   3322:     # If we are here, %Keywords is empty, so fill it up
                   3323:     #   Make sure the file we need exists...
                   3324:     if (! -e $thesaurus_db_file) {
                   3325:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3326:                                  " failed because it does not exist");
                   3327:         return 0;
                   3328:     }
                   3329:     #   Set up the hash as a database
                   3330:     my %thesaurus_db;
                   3331:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3332:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3333:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3334:                                  $thesaurus_db_file);
                   3335:         return 0;
                   3336:     } 
                   3337:     #  Get the average number of appearances of a word.
                   3338:     my $avecount = $thesaurus_db{'average.count'};
                   3339:     #  Put keywords (those that appear > average) into %Keywords
                   3340:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3341:         my ($count,undef) = split /:/,$data;
                   3342:         $Keywords{$word}++ if ($count > $avecount);
                   3343:     }
                   3344:     untie %thesaurus_db;
                   3345:     # Remove special values from %Keywords.
1.356     albertel 3346:     foreach my $value ('total.count','average.count') {
                   3347:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3348:   }
1.46      matthew  3349:     return 1;
                   3350: }
                   3351: 
                   3352: ###################################################
                   3353: 
                   3354: =pod
                   3355: 
1.648     raeburn  3356: =item * &keyword($word)
1.46      matthew  3357: 
                   3358: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3359: than the average number of times in the thesaurus database.  Calls 
                   3360: &initialize_keywords
                   3361: 
                   3362: =cut
                   3363: 
                   3364: ###################################################
1.20      www      3365: 
                   3366: sub keyword {
1.46      matthew  3367:     return if (!&initialize_keywords());
                   3368:     my $word=lc(shift());
                   3369:     $word=~s/\W//g;
                   3370:     return exists($Keywords{$word});
1.20      www      3371: }
1.46      matthew  3372: 
                   3373: ###############################################################
                   3374: 
                   3375: =pod 
1.20      www      3376: 
1.648     raeburn  3377: =item * &get_related_words()
1.46      matthew  3378: 
1.160     matthew  3379: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3380: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3381: will be returned.  The order of the words returned is determined by the
                   3382: database which holds them.
                   3383: 
                   3384: Uses global $thesaurus_db_file.
                   3385: 
1.1057    foxr     3386: 
1.46      matthew  3387: =cut
                   3388: 
                   3389: ###############################################################
                   3390: sub get_related_words {
                   3391:     my $keyword = shift;
                   3392:     my %thesaurus_db;
                   3393:     if (! -e $thesaurus_db_file) {
                   3394:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3395:                                  "failed because the file does not exist");
                   3396:         return ();
                   3397:     }
                   3398:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3399:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3400:         return ();
                   3401:     } 
                   3402:     my @Words=();
1.429     www      3403:     my $count=0;
1.46      matthew  3404:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3405: 	# The first element is the number of times
                   3406: 	# the word appears.  We do not need it now.
1.429     www      3407: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3408: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3409: 	my $threshold=$mostfrequentcount/10;
                   3410:         foreach my $possibleword (@RelatedWords) {
                   3411:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3412:             if ($wordcount>$threshold) {
                   3413: 		push(@Words,$word);
                   3414:                 $count++;
                   3415:                 if ($count>10) { last; }
                   3416: 	    }
1.20      www      3417:         }
                   3418:     }
1.46      matthew  3419:     untie %thesaurus_db;
                   3420:     return @Words;
1.14      harris41 3421: }
1.46      matthew  3422: 
1.112     bowersj2 3423: =pod
                   3424: 
                   3425: =back
                   3426: 
                   3427: =cut
1.61      www      3428: 
                   3429: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3430: =pod
                   3431: 
1.112     bowersj2 3432: =head1 User Name Functions
                   3433: 
                   3434: =over 4
                   3435: 
1.648     raeburn  3436: =item * &plainname($uname,$udom,$first)
1.81      albertel 3437: 
1.112     bowersj2 3438: Takes a users logon name and returns it as a string in
1.226     albertel 3439: "first middle last generation" form 
                   3440: if $first is set to 'lastname' then it returns it as
                   3441: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3442: 
                   3443: =cut
1.61      www      3444: 
1.295     www      3445: 
1.81      albertel 3446: ###############################################################
1.61      www      3447: sub plainname {
1.226     albertel 3448:     my ($uname,$udom,$first)=@_;
1.537     albertel 3449:     return if (!defined($uname) || !defined($udom));
1.295     www      3450:     my %names=&getnames($uname,$udom);
1.226     albertel 3451:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3452: 					  $names{'middlename'},
                   3453: 					  $names{'lastname'},
                   3454: 					  $names{'generation'},$first);
                   3455:     $name=~s/^\s+//;
1.62      www      3456:     $name=~s/\s+$//;
                   3457:     $name=~s/\s+/ /g;
1.353     albertel 3458:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3459:     return $name;
1.61      www      3460: }
1.66      www      3461: 
                   3462: # -------------------------------------------------------------------- Nickname
1.81      albertel 3463: =pod
                   3464: 
1.648     raeburn  3465: =item * &nickname($uname,$udom)
1.81      albertel 3466: 
                   3467: Gets a users name and returns it as a string as
                   3468: 
                   3469: "&quot;nickname&quot;"
1.66      www      3470: 
1.81      albertel 3471: if the user has a nickname or
                   3472: 
                   3473: "first middle last generation"
                   3474: 
                   3475: if the user does not
                   3476: 
                   3477: =cut
1.66      www      3478: 
                   3479: sub nickname {
                   3480:     my ($uname,$udom)=@_;
1.537     albertel 3481:     return if (!defined($uname) || !defined($udom));
1.295     www      3482:     my %names=&getnames($uname,$udom);
1.68      albertel 3483:     my $name=$names{'nickname'};
1.66      www      3484:     if ($name) {
                   3485:        $name='&quot;'.$name.'&quot;'; 
                   3486:     } else {
                   3487:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3488: 	     $names{'lastname'}.' '.$names{'generation'};
                   3489:        $name=~s/\s+$//;
                   3490:        $name=~s/\s+/ /g;
                   3491:     }
                   3492:     return $name;
                   3493: }
                   3494: 
1.295     www      3495: sub getnames {
                   3496:     my ($uname,$udom)=@_;
1.537     albertel 3497:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3498:     if ($udom eq 'public' && $uname eq 'public') {
                   3499: 	return ('lastname' => &mt('Public'));
                   3500:     }
1.295     www      3501:     my $id=$uname.':'.$udom;
                   3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3503:     if ($cached) {
                   3504: 	return %{$names};
                   3505:     } else {
                   3506: 	my %loadnames=&Apache::lonnet::get('environment',
                   3507:                     ['firstname','middlename','lastname','generation','nickname'],
                   3508: 					 $udom,$uname);
                   3509: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3510: 	return %loadnames;
                   3511:     }
                   3512: }
1.61      www      3513: 
1.542     raeburn  3514: # -------------------------------------------------------------------- getemails
1.648     raeburn  3515: 
1.542     raeburn  3516: =pod
                   3517: 
1.648     raeburn  3518: =item * &getemails($uname,$udom)
1.542     raeburn  3519: 
                   3520: Gets a user's email information and returns it as a hash with keys:
                   3521: notification, critnotification, permanentemail
                   3522: 
                   3523: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3524: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3525:  
1.648     raeburn  3526: 
1.542     raeburn  3527: =cut
                   3528: 
1.648     raeburn  3529: 
1.466     albertel 3530: sub getemails {
                   3531:     my ($uname,$udom)=@_;
                   3532:     if ($udom eq 'public' && $uname eq 'public') {
                   3533: 	return;
                   3534:     }
1.467     www      3535:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3536:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3537:     my $id=$uname.':'.$udom;
                   3538:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3539:     if ($cached) {
                   3540: 	return %{$names};
                   3541:     } else {
                   3542: 	my %loadnames=&Apache::lonnet::get('environment',
                   3543:                     			   ['notification','critnotification',
                   3544: 					    'permanentemail'],
                   3545: 					   $udom,$uname);
                   3546: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3547: 	return %loadnames;
                   3548:     }
                   3549: }
                   3550: 
1.551     albertel 3551: sub flush_email_cache {
                   3552:     my ($uname,$udom)=@_;
                   3553:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3554:     if (!$uname) { $uname=$env{'user.name'};   }
                   3555:     return if ($udom eq 'public' && $uname eq 'public');
                   3556:     my $id=$uname.':'.$udom;
                   3557:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3558: }
                   3559: 
1.728     raeburn  3560: # -------------------------------------------------------------------- getlangs
                   3561: 
                   3562: =pod
                   3563: 
                   3564: =item * &getlangs($uname,$udom)
                   3565: 
                   3566: Gets a user's language preference and returns it as a hash with key:
                   3567: language.
                   3568: 
                   3569: =cut
                   3570: 
                   3571: 
                   3572: sub getlangs {
                   3573:     my ($uname,$udom) = @_;
                   3574:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3575:     if (!$uname) { $uname=$env{'user.name'};   }
                   3576:     my $id=$uname.':'.$udom;
                   3577:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3578:     if ($cached) {
                   3579:         return %{$langs};
                   3580:     } else {
                   3581:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3582:                                            $udom,$uname);
                   3583:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3584:         return %loadlangs;
                   3585:     }
                   3586: }
                   3587: 
                   3588: sub flush_langs_cache {
                   3589:     my ($uname,$udom)=@_;
                   3590:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3591:     if (!$uname) { $uname=$env{'user.name'};   }
                   3592:     return if ($udom eq 'public' && $uname eq 'public');
                   3593:     my $id=$uname.':'.$udom;
                   3594:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3595: }
                   3596: 
1.61      www      3597: # ------------------------------------------------------------------ Screenname
1.81      albertel 3598: 
                   3599: =pod
                   3600: 
1.648     raeburn  3601: =item * &screenname($uname,$udom)
1.81      albertel 3602: 
                   3603: Gets a users screenname and returns it as a string
                   3604: 
                   3605: =cut
1.61      www      3606: 
                   3607: sub screenname {
                   3608:     my ($uname,$udom)=@_;
1.258     albertel 3609:     if ($uname eq $env{'user.name'} &&
                   3610: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3611:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3612:     return $names{'screenname'};
1.62      www      3613: }
                   3614: 
1.212     albertel 3615: 
1.802     bisitz   3616: # ------------------------------------------------------------- Confirm Wrapper
                   3617: =pod
                   3618: 
1.1075.2.42  raeburn  3619: =item * &confirmwrapper($message)
1.802     bisitz   3620: 
                   3621: Wrap messages about completion of operation in box
                   3622: 
                   3623: =cut
                   3624: 
                   3625: sub confirmwrapper {
                   3626:     my ($message)=@_;
                   3627:     if ($message) {
                   3628:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3629:                .$message."\n"
                   3630:                .'</div>'."\n";
                   3631:     } else {
                   3632:         return $message;
                   3633:     }
                   3634: }
                   3635: 
1.62      www      3636: # ------------------------------------------------------------- Message Wrapper
                   3637: 
                   3638: sub messagewrapper {
1.369     www      3639:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3640:     return 
1.441     albertel 3641:         '<a href="/adm/email?compose=individual&amp;'.
                   3642:         'recname='.$username.'&amp;recdom='.$domain.
                   3643: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3644:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3645: }
1.802     bisitz   3646: 
1.74      www      3647: # --------------------------------------------------------------- Notes Wrapper
                   3648: 
                   3649: sub noteswrapper {
                   3650:     my ($link,$un,$do)=@_;
                   3651:     return 
1.896     amueller 3652: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3653: }
1.802     bisitz   3654: 
1.62      www      3655: # ------------------------------------------------------------- Aboutme Wrapper
                   3656: 
                   3657: sub aboutmewrapper {
1.1070    raeburn  3658:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3659:     if (!defined($username)  && !defined($domain)) {
                   3660:         return;
                   3661:     }
1.1075.2.15  raeburn  3662:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3663: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3664: }
                   3665: 
                   3666: # ------------------------------------------------------------ Syllabus Wrapper
                   3667: 
                   3668: sub syllabuswrapper {
1.707     bisitz   3669:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3670:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3671: }
1.14      harris41 3672: 
1.802     bisitz   3673: # -----------------------------------------------------------------------------
                   3674: 
1.208     matthew  3675: sub track_student_link {
1.887     raeburn  3676:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3677:     my $link ="/adm/trackstudent?";
1.208     matthew  3678:     my $title = 'View recent activity';
                   3679:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3680:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3681:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3682:         $title .= ' of this student';
1.268     albertel 3683:     } 
1.208     matthew  3684:     if (defined($target) && $target !~ /^\s*$/) {
                   3685:         $target = qq{target="$target"};
                   3686:     } else {
                   3687:         $target = '';
                   3688:     }
1.268     albertel 3689:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3690:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3691:     $title = &mt($title);
                   3692:     $linktext = &mt($linktext);
1.448     albertel 3693:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3694: 	&help_open_topic('View_recent_activity');
1.208     matthew  3695: }
                   3696: 
1.781     raeburn  3697: sub slot_reservations_link {
                   3698:     my ($linktext,$sname,$sdom,$target) = @_;
                   3699:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3700:     my $title = 'View slot reservation history';
                   3701:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3702:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3703:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3704:         $title .= ' of this student';
                   3705:     }
                   3706:     if (defined($target) && $target !~ /^\s*$/) {
                   3707:         $target = qq{target="$target"};
                   3708:     } else {
                   3709:         $target = '';
                   3710:     }
                   3711:     $title = &mt($title);
                   3712:     $linktext = &mt($linktext);
                   3713:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3714: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3715: 
                   3716: }
                   3717: 
1.508     www      3718: # ===================================================== Display a student photo
                   3719: 
                   3720: 
1.509     albertel 3721: sub student_image_tag {
1.508     www      3722:     my ($domain,$user)=@_;
                   3723:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3724:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3725: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3726:     } else {
                   3727: 	return '';
                   3728:     }
                   3729: }
                   3730: 
1.112     bowersj2 3731: =pod
                   3732: 
                   3733: =back
                   3734: 
                   3735: =head1 Access .tab File Data
                   3736: 
                   3737: =over 4
                   3738: 
1.648     raeburn  3739: =item * &languageids() 
1.112     bowersj2 3740: 
                   3741: returns list of all language ids
                   3742: 
                   3743: =cut
                   3744: 
1.14      harris41 3745: sub languageids {
1.16      harris41 3746:     return sort(keys(%language));
1.14      harris41 3747: }
                   3748: 
1.112     bowersj2 3749: =pod
                   3750: 
1.648     raeburn  3751: =item * &languagedescription() 
1.112     bowersj2 3752: 
                   3753: returns description of a specified language id
                   3754: 
                   3755: =cut
                   3756: 
1.14      harris41 3757: sub languagedescription {
1.125     www      3758:     my $code=shift;
                   3759:     return  ($supported_language{$code}?'* ':'').
                   3760:             $language{$code}.
1.126     www      3761: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3762: }
                   3763: 
1.1048    foxr     3764: =pod
                   3765: 
                   3766: =item * &plainlanguagedescription
                   3767: 
                   3768: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3769: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3770: 
                   3771: =cut
                   3772: 
1.145     www      3773: sub plainlanguagedescription {
                   3774:     my $code=shift;
                   3775:     return $language{$code};
                   3776: }
                   3777: 
1.1048    foxr     3778: =pod
                   3779: 
                   3780: =item * &supportedlanguagecode
                   3781: 
                   3782: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3783: code.
                   3784: 
                   3785: =cut
                   3786: 
1.145     www      3787: sub supportedlanguagecode {
                   3788:     my $code=shift;
                   3789:     return $supported_language{$code};
1.97      www      3790: }
                   3791: 
1.112     bowersj2 3792: =pod
                   3793: 
1.1048    foxr     3794: =item * &latexlanguage()
                   3795: 
                   3796: Given a language key code returns the correspondnig language to use
                   3797: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3798: is no supported hyphenation for the language code.
                   3799: 
                   3800: =cut
                   3801: 
                   3802: sub latexlanguage {
                   3803:     my $code = shift;
                   3804:     return $latex_language{$code};
                   3805: }
                   3806: 
                   3807: =pod
                   3808: 
                   3809: =item * &latexhyphenation()
                   3810: 
                   3811: Same as above but what's supplied is the language as it might be stored
                   3812: in the metadata.
                   3813: 
                   3814: =cut
                   3815: 
                   3816: sub latexhyphenation {
                   3817:     my $key = shift;
                   3818:     return $latex_language_bykey{$key};
                   3819: }
                   3820: 
                   3821: =pod
                   3822: 
1.648     raeburn  3823: =item * &copyrightids() 
1.112     bowersj2 3824: 
                   3825: returns list of all copyrights
                   3826: 
                   3827: =cut
                   3828: 
                   3829: sub copyrightids {
                   3830:     return sort(keys(%cprtag));
                   3831: }
                   3832: 
                   3833: =pod
                   3834: 
1.648     raeburn  3835: =item * &copyrightdescription() 
1.112     bowersj2 3836: 
                   3837: returns description of a specified copyright id
                   3838: 
                   3839: =cut
                   3840: 
                   3841: sub copyrightdescription {
1.166     www      3842:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3843: }
1.197     matthew  3844: 
                   3845: =pod
                   3846: 
1.648     raeburn  3847: =item * &source_copyrightids() 
1.192     taceyjo1 3848: 
                   3849: returns list of all source copyrights
                   3850: 
                   3851: =cut
                   3852: 
                   3853: sub source_copyrightids {
                   3854:     return sort(keys(%scprtag));
                   3855: }
                   3856: 
                   3857: =pod
                   3858: 
1.648     raeburn  3859: =item * &source_copyrightdescription() 
1.192     taceyjo1 3860: 
                   3861: returns description of a specified source copyright id
                   3862: 
                   3863: =cut
                   3864: 
                   3865: sub source_copyrightdescription {
                   3866:     return &mt($scprtag{shift(@_)});
                   3867: }
1.112     bowersj2 3868: 
                   3869: =pod
                   3870: 
1.648     raeburn  3871: =item * &filecategories() 
1.112     bowersj2 3872: 
                   3873: returns list of all file categories
                   3874: 
                   3875: =cut
                   3876: 
                   3877: sub filecategories {
                   3878:     return sort(keys(%category_extensions));
                   3879: }
                   3880: 
                   3881: =pod
                   3882: 
1.648     raeburn  3883: =item * &filecategorytypes() 
1.112     bowersj2 3884: 
                   3885: returns list of file types belonging to a given file
                   3886: category
                   3887: 
                   3888: =cut
                   3889: 
                   3890: sub filecategorytypes {
1.356     albertel 3891:     my ($cat) = @_;
                   3892:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3893: }
                   3894: 
                   3895: =pod
                   3896: 
1.648     raeburn  3897: =item * &fileembstyle() 
1.112     bowersj2 3898: 
                   3899: returns embedding style for a specified file type
                   3900: 
                   3901: =cut
                   3902: 
                   3903: sub fileembstyle {
                   3904:     return $fe{lc(shift(@_))};
1.169     www      3905: }
                   3906: 
1.351     www      3907: sub filemimetype {
                   3908:     return $fm{lc(shift(@_))};
                   3909: }
                   3910: 
1.169     www      3911: 
                   3912: sub filecategoryselect {
                   3913:     my ($name,$value)=@_;
1.189     matthew  3914:     return &select_form($value,$name,
1.970     raeburn  3915:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3916: }
                   3917: 
                   3918: =pod
                   3919: 
1.648     raeburn  3920: =item * &filedescription() 
1.112     bowersj2 3921: 
                   3922: returns description for a specified file type
                   3923: 
                   3924: =cut
                   3925: 
                   3926: sub filedescription {
1.188     matthew  3927:     my $file_description = $fd{lc(shift())};
                   3928:     $file_description =~ s:([\[\]]):~$1:g;
                   3929:     return &mt($file_description);
1.112     bowersj2 3930: }
                   3931: 
                   3932: =pod
                   3933: 
1.648     raeburn  3934: =item * &filedescriptionex() 
1.112     bowersj2 3935: 
                   3936: returns description for a specified file type with
                   3937: extra formatting
                   3938: 
                   3939: =cut
                   3940: 
                   3941: sub filedescriptionex {
                   3942:     my $ex=shift;
1.188     matthew  3943:     my $file_description = $fd{lc($ex)};
                   3944:     $file_description =~ s:([\[\]]):~$1:g;
                   3945:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3946: }
                   3947: 
                   3948: # End of .tab access
                   3949: =pod
                   3950: 
                   3951: =back
                   3952: 
                   3953: =cut
                   3954: 
                   3955: # ------------------------------------------------------------------ File Types
                   3956: sub fileextensions {
                   3957:     return sort(keys(%fe));
                   3958: }
                   3959: 
1.97      www      3960: # ----------------------------------------------------------- Display Languages
                   3961: # returns a hash with all desired display languages
                   3962: #
                   3963: 
                   3964: sub display_languages {
                   3965:     my %languages=();
1.695     raeburn  3966:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3967: 	$languages{$lang}=1;
1.97      www      3968:     }
                   3969:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3970:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3971: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3972: 	    $languages{$lang}=1;
1.97      www      3973:         }
                   3974:     }
                   3975:     return %languages;
1.14      harris41 3976: }
                   3977: 
1.582     albertel 3978: sub languages {
                   3979:     my ($possible_langs) = @_;
1.695     raeburn  3980:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3981:     if (!ref($possible_langs)) {
                   3982: 	if( wantarray ) {
                   3983: 	    return @preferred_langs;
                   3984: 	} else {
                   3985: 	    return $preferred_langs[0];
                   3986: 	}
                   3987:     }
                   3988:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3989:     my @preferred_possibilities;
                   3990:     foreach my $preferred_lang (@preferred_langs) {
                   3991: 	if (exists($possibilities{$preferred_lang})) {
                   3992: 	    push(@preferred_possibilities, $preferred_lang);
                   3993: 	}
                   3994:     }
                   3995:     if( wantarray ) {
                   3996: 	return @preferred_possibilities;
                   3997:     }
                   3998:     return $preferred_possibilities[0];
                   3999: }
                   4000: 
1.742     raeburn  4001: sub user_lang {
                   4002:     my ($touname,$toudom,$fromcid) = @_;
                   4003:     my @userlangs;
                   4004:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4005:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4006:                     $env{'course.'.$fromcid.'.languages'}));
                   4007:     } else {
                   4008:         my %langhash = &getlangs($touname,$toudom);
                   4009:         if ($langhash{'languages'} ne '') {
                   4010:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4011:         } else {
                   4012:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4013:             if ($domdefs{'lang_def'} ne '') {
                   4014:                 @userlangs = ($domdefs{'lang_def'});
                   4015:             }
                   4016:         }
                   4017:     }
                   4018:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4019:     my $user_lh = Apache::localize->get_handle(@languages);
                   4020:     return $user_lh;
                   4021: }
                   4022: 
                   4023: 
1.112     bowersj2 4024: ###############################################################
                   4025: ##               Student Answer Attempts                     ##
                   4026: ###############################################################
                   4027: 
                   4028: =pod
                   4029: 
                   4030: =head1 Alternate Problem Views
                   4031: 
                   4032: =over 4
                   4033: 
1.648     raeburn  4034: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4035:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4036: 
                   4037: Return string with previous attempt on problem. Arguments:
                   4038: 
                   4039: =over 4
                   4040: 
                   4041: =item * $symb: Problem, including path
                   4042: 
                   4043: =item * $username: username of the desired student
                   4044: 
                   4045: =item * $domain: domain of the desired student
1.14      harris41 4046: 
1.112     bowersj2 4047: =item * $course: Course ID
1.14      harris41 4048: 
1.112     bowersj2 4049: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4050:     something
1.14      harris41 4051: 
1.112     bowersj2 4052: =item * $regexp: if string matches this regexp, the string will be
                   4053:     sent to $gradesub
1.14      harris41 4054: 
1.112     bowersj2 4055: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4056: 
1.1075.2.86  raeburn  4057: =item * $usec: section of the desired student
                   4058: 
                   4059: =item * $identifier: counter for student (multiple students one problem) or
                   4060:     problem (one student; whole sequence).
                   4061: 
1.112     bowersj2 4062: =back
1.14      harris41 4063: 
1.112     bowersj2 4064: The output string is a table containing all desired attempts, if any.
1.16      harris41 4065: 
1.112     bowersj2 4066: =cut
1.1       albertel 4067: 
                   4068: sub get_previous_attempt {
1.1075.2.86  raeburn  4069:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4070:   my $prevattempts='';
1.43      ng       4071:   no strict 'refs';
1.1       albertel 4072:   if ($symb) {
1.3       albertel 4073:     my (%returnhash)=
                   4074:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4075:     if ($returnhash{'version'}) {
                   4076:       my %lasthash=();
                   4077:       my $version;
                   4078:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4079:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4080:             if ($key =~ /\.rawrndseed$/) {
                   4081:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4082:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4083:             } else {
                   4084:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4085:             }
1.19      harris41 4086:         }
1.1       albertel 4087:       }
1.596     albertel 4088:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4089:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4090:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4091:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4092:       foreach my $key (sort(keys(%lasthash))) {
                   4093: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4094: 	if ($#parts > 0) {
1.31      albertel 4095: 	  my $data=$parts[-1];
1.989     raeburn  4096:           next if ($data eq 'foilorder');
1.31      albertel 4097: 	  pop(@parts);
1.1010    www      4098:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4099:           if ($data eq 'type') {
                   4100:               unless ($showsurv) {
                   4101:                   my $id = join(',',@parts);
                   4102:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4103:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4104:                       $lasthidden{$ign.'.'.$id} = 1;
                   4105:                   }
1.945     raeburn  4106:               }
1.1075.2.86  raeburn  4107:               if ($identifier ne '') {
                   4108:                   my $id = join(',',@parts);
                   4109:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4110:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4111:                       $hidestatus{$ign.'.'.$id} = 1;
                   4112:                   }
                   4113:               }
                   4114:           } elsif ($data eq 'regrader') {
                   4115:               if (($identifier ne '') && (@parts)) {
                   4116:                   my $id = join(',',@parts);
                   4117:                   $regraded{$ign.'.'.$id} = 1;
                   4118:               }
1.1010    www      4119:           } 
1.31      albertel 4120: 	} else {
1.41      ng       4121: 	  if ($#parts == 0) {
                   4122: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4123: 	  } else {
                   4124: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4125: 	  }
1.31      albertel 4126: 	}
1.16      harris41 4127:       }
1.596     albertel 4128:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4129:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4130:         my (%solved,%resets,%probstatus);
                   4131:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4132:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4133:                 foreach my $id (keys(%regraded)) {
                   4134:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4135:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4136:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4137:                         push(@{$resets{$id}},$version);
                   4138:                     }
                   4139:                 }
                   4140:             }
                   4141:         }
1.40      ng       4142: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4143:             my (@hidden,@unsolved);
1.945     raeburn  4144:             if (%typeparts) {
                   4145:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4146:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4147:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4148:                         push(@hidden,$id);
1.1075.2.86  raeburn  4149:                     } elsif ($identifier ne '') {
                   4150:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4151:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4152:                                 ($hidestatus{$id})) {
                   4153:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4154:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4155:                                 push(@{$solved{$id}},$version);
                   4156:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4157:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4158:                                 my $skip;
                   4159:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4160:                                     foreach my $reset (@{$resets{$id}}) {
                   4161:                                         if ($reset > $solved{$id}[-1]) {
                   4162:                                             $skip=1;
                   4163:                                             last;
                   4164:                                         }
                   4165:                                     }
                   4166:                                 }
                   4167:                                 unless ($skip) {
                   4168:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4169:                                     push(@unsolved,$partslist);
                   4170:                                 }
                   4171:                             }
                   4172:                         }
1.945     raeburn  4173:                     }
                   4174:                 }
                   4175:             }
                   4176:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4177:                            '<td>'.&mt('Transaction [_1]',$version);
                   4178:             if (@unsolved) {
                   4179:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4180:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4181:                                  &mt('Hide').'</label></span>';
                   4182:             }
                   4183:             $prevattempts .= '</td>';
1.945     raeburn  4184:             if (@hidden) {
                   4185:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4186:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4187:                     my $hide;
                   4188:                     foreach my $id (@hidden) {
                   4189:                         if ($key =~ /^\Q$id\E/) {
                   4190:                             $hide = 1;
                   4191:                             last;
                   4192:                         }
                   4193:                     }
                   4194:                     if ($hide) {
                   4195:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4196:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4197:                             my $value = &format_previous_attempt_value($key,
                   4198:                                              $returnhash{$version.':'.$key});
                   4199:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4200:                         } else {
                   4201:                             $prevattempts.='<td>&nbsp;</td>';
                   4202:                         }
                   4203:                     } else {
                   4204:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4205:                             my $value = $returnhash{$version.':'.$key};
                   4206:                             if ($key =~ /\.rndseed$/) {
                   4207:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4208:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4209:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4210:                                 }
                   4211:                             }
                   4212:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4213:                                            '&nbsp;</td>';
1.945     raeburn  4214:                         } else {
                   4215:                             $prevattempts.='<td>&nbsp;</td>';
                   4216:                         }
                   4217:                     }
                   4218:                 }
                   4219:             } else {
                   4220: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4221:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4222:                     my $value = $returnhash{$version.':'.$key};
                   4223:                     if ($key =~ /\.rndseed$/) {
                   4224:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4225:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4226:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4227:                         }
                   4228:                     }
                   4229:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4230:                                    '&nbsp;</td>';
1.945     raeburn  4231: 	        }
                   4232:             }
                   4233: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4234: 	 }
1.1       albertel 4235:       }
1.945     raeburn  4236:       my @currhidden = keys(%lasthidden);
1.596     albertel 4237:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4238:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4239:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4240:           if (%typeparts) {
                   4241:               my $hidden;
                   4242:               foreach my $id (@currhidden) {
                   4243:                   if ($key =~ /^\Q$id\E/) {
                   4244:                       $hidden = 1;
                   4245:                       last;
                   4246:                   }
                   4247:               }
                   4248:               if ($hidden) {
                   4249:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4250:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4251:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4252:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4253:                           $value = &$gradesub($value);
                   4254:                       }
                   4255:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4256:                   } else {
                   4257:                       $prevattempts.='<td>&nbsp;</td>';
                   4258:                   }
                   4259:               } else {
                   4260:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4261:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4262:                       $value = &$gradesub($value);
                   4263:                   }
                   4264:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4265:               }
                   4266:           } else {
                   4267: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4268: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4269:                   $value = &$gradesub($value);
                   4270:               }
                   4271: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4272:           }
1.16      harris41 4273:       }
1.596     albertel 4274:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4275:     } else {
1.596     albertel 4276:       $prevattempts=
                   4277: 	  &start_data_table().&start_data_table_row().
                   4278: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4279: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4280:     }
                   4281:   } else {
1.596     albertel 4282:     $prevattempts=
                   4283: 	  &start_data_table().&start_data_table_row().
                   4284: 	  '<td>'.&mt('No data.').'</td>'.
                   4285: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4286:   }
1.10      albertel 4287: }
                   4288: 
1.581     albertel 4289: sub format_previous_attempt_value {
                   4290:     my ($key,$value) = @_;
1.1011    www      4291:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4292: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4293:     } elsif (ref($value) eq 'ARRAY') {
                   4294: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4295:     } elsif ($key =~ /answerstring$/) {
                   4296:         my %answers = &Apache::lonnet::str2hash($value);
                   4297:         my @anskeys = sort(keys(%answers));
                   4298:         if (@anskeys == 1) {
                   4299:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4300:             if ($answer =~ m{\0}) {
                   4301:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4302:             }
                   4303:             my $tag_internal_answer_name = 'INTERNAL';
                   4304:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4305:                 $value = $answer; 
                   4306:             } else {
                   4307:                 $value = $anskeys[0].'='.$answer;
                   4308:             }
                   4309:         } else {
                   4310:             foreach my $ans (@anskeys) {
                   4311:                 my $answer = $answers{$ans};
1.1001    raeburn  4312:                 if ($answer =~ m{\0}) {
                   4313:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4314:                 }
                   4315:                 $value .=  $ans.'='.$answer.'<br />';;
                   4316:             } 
                   4317:         }
1.581     albertel 4318:     } else {
                   4319: 	$value = &unescape($value);
                   4320:     }
                   4321:     return $value;
                   4322: }
                   4323: 
                   4324: 
1.107     albertel 4325: sub relative_to_absolute {
                   4326:     my ($url,$output)=@_;
                   4327:     my $parser=HTML::TokeParser->new(\$output);
                   4328:     my $token;
                   4329:     my $thisdir=$url;
                   4330:     my @rlinks=();
                   4331:     while ($token=$parser->get_token) {
                   4332: 	if ($token->[0] eq 'S') {
                   4333: 	    if ($token->[1] eq 'a') {
                   4334: 		if ($token->[2]->{'href'}) {
                   4335: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4336: 		}
                   4337: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4338: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4339: 	    } elsif ($token->[1] eq 'base') {
                   4340: 		$thisdir=$token->[2]->{'href'};
                   4341: 	    }
                   4342: 	}
                   4343:     }
                   4344:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4345:     foreach my $link (@rlinks) {
1.726     raeburn  4346: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4347: 		($link=~/^\//) ||
                   4348: 		($link=~/^javascript:/i) ||
                   4349: 		($link=~/^mailto:/i) ||
                   4350: 		($link=~/^\#/)) {
                   4351: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4352: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4353: 	}
                   4354:     }
                   4355: # -------------------------------------------------- Deal with Applet codebases
                   4356:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4357:     return $output;
                   4358: }
                   4359: 
1.112     bowersj2 4360: =pod
                   4361: 
1.648     raeburn  4362: =item * &get_student_view()
1.112     bowersj2 4363: 
                   4364: show a snapshot of what student was looking at
                   4365: 
                   4366: =cut
                   4367: 
1.10      albertel 4368: sub get_student_view {
1.186     albertel 4369:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4370:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4371:   my (%form);
1.10      albertel 4372:   my @elements=('symb','courseid','domain','username');
                   4373:   foreach my $element (@elements) {
1.186     albertel 4374:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4375:   }
1.186     albertel 4376:   if (defined($moreenv)) {
                   4377:       %form=(%form,%{$moreenv});
                   4378:   }
1.236     albertel 4379:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4380:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4381:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4382:   $userview=~s/\<body[^\>]*\>//gi;
                   4383:   $userview=~s/\<\/body\>//gi;
                   4384:   $userview=~s/\<html\>//gi;
                   4385:   $userview=~s/\<\/html\>//gi;
                   4386:   $userview=~s/\<head\>//gi;
                   4387:   $userview=~s/\<\/head\>//gi;
                   4388:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4389:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4390:   if (wantarray) {
                   4391:      return ($userview,$response);
                   4392:   } else {
                   4393:      return $userview;
                   4394:   }
                   4395: }
                   4396: 
                   4397: sub get_student_view_with_retries {
                   4398:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4399: 
                   4400:     my $ok = 0;                 # True if we got a good response.
                   4401:     my $content;
                   4402:     my $response;
                   4403: 
                   4404:     # Try to get the student_view done. within the retries count:
                   4405:     
                   4406:     do {
                   4407:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4408:          $ok      = $response->is_success;
                   4409:          if (!$ok) {
                   4410:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4411:          }
                   4412:          $retries--;
                   4413:     } while (!$ok && ($retries > 0));
                   4414:     
                   4415:     if (!$ok) {
                   4416:        $content = '';          # On error return an empty content.
                   4417:     }
1.651     www      4418:     if (wantarray) {
                   4419:        return ($content, $response);
                   4420:     } else {
                   4421:        return $content;
                   4422:     }
1.11      albertel 4423: }
                   4424: 
1.1075.2.149  raeburn  4425: sub css_links {
                   4426:     my ($currsymb,$level) = @_;
                   4427:     my ($links,@symbs,%cssrefs,%httpref);
                   4428:     if ($level eq 'map') {
                   4429:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4430:         if (ref($navmap)) {
                   4431:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4432:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4433:             foreach my $res (@resources) {
                   4434:                 if (ref($res) && $res->symb()) {
                   4435:                     push(@symbs,$res->symb());
                   4436:                 }
                   4437:             }
                   4438:         }
                   4439:     } else {
                   4440:         @symbs = ($currsymb);
                   4441:     }
                   4442:     foreach my $symb (@symbs) {
                   4443:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4444:         if ($css_href =~ /\S/) {
                   4445:             unless ($css_href =~ m{https?://}) {
                   4446:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4447:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4448:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4449:                 unless ($css_href =~ m{^/}) {
                   4450:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4451:                 }
                   4452:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4453:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4454:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4455:                         my $thisurl = $proburl;
                   4456:                         if ($env{'httpref.'.$proburl}) {
                   4457:                             $thisurl = $env{'httpref.'.$proburl};
                   4458:                         }
                   4459:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4460:                     }
                   4461:                 }
                   4462:             }
                   4463:             $cssrefs{$css_href} = 1;
                   4464:         }
                   4465:     }
                   4466:     if (keys(%httpref)) {
                   4467:         &Apache::lonnet::appenv(\%httpref);
                   4468:     }
                   4469:     if (keys(%cssrefs)) {
                   4470:         foreach my $css_href (keys(%cssrefs)) {
                   4471:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4472:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4473:         }
                   4474:     }
                   4475:     return $links;
                   4476: }
                   4477: 
1.112     bowersj2 4478: =pod
                   4479: 
1.648     raeburn  4480: =item * &get_student_answers() 
1.112     bowersj2 4481: 
                   4482: show a snapshot of how student was answering problem
                   4483: 
                   4484: =cut
                   4485: 
1.11      albertel 4486: sub get_student_answers {
1.100     sakharuk 4487:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4488:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4489:   my (%moreenv);
1.11      albertel 4490:   my @elements=('symb','courseid','domain','username');
                   4491:   foreach my $element (@elements) {
1.186     albertel 4492:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4493:   }
1.186     albertel 4494:   $moreenv{'grade_target'}='answer';
                   4495:   %moreenv=(%form,%moreenv);
1.497     raeburn  4496:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4497:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4498:   return $userview;
1.1       albertel 4499: }
1.116     albertel 4500: 
                   4501: =pod
                   4502: 
                   4503: =item * &submlink()
                   4504: 
1.242     albertel 4505: Inputs: $text $uname $udom $symb $target
1.116     albertel 4506: 
                   4507: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4508: 
                   4509: =cut
                   4510: 
                   4511: ###############################################
                   4512: sub submlink {
1.242     albertel 4513:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4514:     if (!($uname && $udom)) {
                   4515: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4516: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4517: 	if (!$symb) { $symb=$cursymb; }
                   4518:     }
1.254     matthew  4519:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4520:     $symb=&escape($symb);
1.960     bisitz   4521:     if ($target) { $target=" target=\"$target\""; }
                   4522:     return
                   4523:         '<a href="/adm/grades?command=submission'.
                   4524:         '&amp;symb='.$symb.
                   4525:         '&amp;student='.$uname.
                   4526:         '&amp;userdom='.$udom.'"'.
                   4527:         $target.'>'.$text.'</a>';
1.242     albertel 4528: }
                   4529: ##############################################
                   4530: 
                   4531: =pod
                   4532: 
                   4533: =item * &pgrdlink()
                   4534: 
                   4535: Inputs: $text $uname $udom $symb $target
                   4536: 
                   4537: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4538: 
                   4539: =cut
                   4540: 
                   4541: ###############################################
                   4542: sub pgrdlink {
                   4543:     my $link=&submlink(@_);
                   4544:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4545:     return $link;
                   4546: }
                   4547: ##############################################
                   4548: 
                   4549: =pod
                   4550: 
                   4551: =item * &pprmlink()
                   4552: 
                   4553: Inputs: $text $uname $udom $symb $target
                   4554: 
                   4555: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4556: student and a specific resource
1.242     albertel 4557: 
                   4558: =cut
                   4559: 
                   4560: ###############################################
                   4561: sub pprmlink {
                   4562:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4563:     if (!($uname && $udom)) {
                   4564: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4565: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4566: 	if (!$symb) { $symb=$cursymb; }
                   4567:     }
1.254     matthew  4568:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4569:     $symb=&escape($symb);
1.242     albertel 4570:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4571:     return '<a href="/adm/parmset?command=set&amp;'.
                   4572: 	'symb='.$symb.'&amp;uname='.$uname.
                   4573: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4574: }
                   4575: ##############################################
1.37      matthew  4576: 
1.112     bowersj2 4577: =pod
                   4578: 
                   4579: =back
                   4580: 
                   4581: =cut
                   4582: 
1.37      matthew  4583: ###############################################
1.51      www      4584: 
                   4585: 
                   4586: sub timehash {
1.687     raeburn  4587:     my ($thistime) = @_;
                   4588:     my $timezone = &Apache::lonlocal::gettimezone();
                   4589:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4590:                      ->set_time_zone($timezone);
                   4591:     my $wday = $dt->day_of_week();
                   4592:     if ($wday == 7) { $wday = 0; }
                   4593:     return ( 'second' => $dt->second(),
                   4594:              'minute' => $dt->minute(),
                   4595:              'hour'   => $dt->hour(),
                   4596:              'day'     => $dt->day_of_month(),
                   4597:              'month'   => $dt->month(),
                   4598:              'year'    => $dt->year(),
                   4599:              'weekday' => $wday,
                   4600:              'dayyear' => $dt->day_of_year(),
                   4601:              'dlsav'   => $dt->is_dst() );
1.51      www      4602: }
                   4603: 
1.370     www      4604: sub utc_string {
                   4605:     my ($date)=@_;
1.371     www      4606:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4607: }
                   4608: 
1.51      www      4609: sub maketime {
                   4610:     my %th=@_;
1.687     raeburn  4611:     my ($epoch_time,$timezone,$dt);
                   4612:     $timezone = &Apache::lonlocal::gettimezone();
                   4613:     eval {
                   4614:         $dt = DateTime->new( year   => $th{'year'},
                   4615:                              month  => $th{'month'},
                   4616:                              day    => $th{'day'},
                   4617:                              hour   => $th{'hour'},
                   4618:                              minute => $th{'minute'},
                   4619:                              second => $th{'second'},
                   4620:                              time_zone => $timezone,
                   4621:                          );
                   4622:     };
                   4623:     if (!$@) {
                   4624:         $epoch_time = $dt->epoch;
                   4625:         if ($epoch_time) {
                   4626:             return $epoch_time;
                   4627:         }
                   4628:     }
1.51      www      4629:     return POSIX::mktime(
                   4630:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4631:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4632: }
                   4633: 
                   4634: #########################################
1.51      www      4635: 
                   4636: sub findallcourses {
1.482     raeburn  4637:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4638:     my %roles;
                   4639:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4640:     my %courses;
1.51      www      4641:     my $now=time;
1.482     raeburn  4642:     if (!defined($uname)) {
                   4643:         $uname = $env{'user.name'};
                   4644:     }
                   4645:     if (!defined($udom)) {
                   4646:         $udom = $env{'user.domain'};
                   4647:     }
                   4648:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4649:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4650:         if (!%roles) {
                   4651:             %roles = (
                   4652:                        cc => 1,
1.907     raeburn  4653:                        co => 1,
1.482     raeburn  4654:                        in => 1,
                   4655:                        ep => 1,
                   4656:                        ta => 1,
                   4657:                        cr => 1,
                   4658:                        st => 1,
                   4659:              );
                   4660:         }
                   4661:         foreach my $entry (keys(%roleshash)) {
                   4662:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4663:             if ($trole =~ /^cr/) { 
                   4664:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4665:             } else {
                   4666:                 next if (!exists($roles{$trole}));
                   4667:             }
                   4668:             if ($tend) {
                   4669:                 next if ($tend < $now);
                   4670:             }
                   4671:             if ($tstart) {
                   4672:                 next if ($tstart > $now);
                   4673:             }
1.1058    raeburn  4674:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4675:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4676:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4677:             if ($secpart eq '') {
                   4678:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4679:                 $sec = 'none';
1.1058    raeburn  4680:                 $value .= $cnum.'/';
1.482     raeburn  4681:             } else {
                   4682:                 $cnum = $cnumpart;
                   4683:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4684:                 $value .= $cnum.'/'.$sec;
                   4685:             }
                   4686:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4687:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4688:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4689:                 }
                   4690:             } else {
                   4691:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4692:             }
1.482     raeburn  4693:         }
                   4694:     } else {
                   4695:         foreach my $key (keys(%env)) {
1.483     albertel 4696: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4697:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4698: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4699: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4700: 	        next if (%roles && !exists($roles{$role}));
                   4701: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4702:                 my $active=1;
                   4703:                 if ($starttime) {
                   4704: 		    if ($now<$starttime) { $active=0; }
                   4705:                 }
                   4706:                 if ($endtime) {
                   4707:                     if ($now>$endtime) { $active=0; }
                   4708:                 }
                   4709:                 if ($active) {
1.1058    raeburn  4710:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4711:                     if ($sec eq '') {
                   4712:                         $sec = 'none';
1.1058    raeburn  4713:                     } else {
                   4714:                         $value .= $sec;
                   4715:                     }
                   4716:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4717:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4718:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4719:                         }
                   4720:                     } else {
                   4721:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4722:                     }
1.474     raeburn  4723:                 }
                   4724:             }
1.51      www      4725:         }
                   4726:     }
1.474     raeburn  4727:     return %courses;
1.51      www      4728: }
1.37      matthew  4729: 
1.54      www      4730: ###############################################
1.474     raeburn  4731: 
                   4732: sub blockcheck {
1.1075.2.158  raeburn  4733:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4734: 
1.1075.2.158  raeburn  4735:     unless ($activity eq 'docs') {
                   4736:         my ($has_evb,$check_ipaccess);
                   4737:         my $dom = $env{'user.domain'};
                   4738:         if ($env{'request.course.id'}) {
                   4739:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4740:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4741:             my $checkrole = "cm./$cdom/$cnum";
                   4742:             my $sec = $env{'request.course.sec'};
                   4743:             if ($sec ne '') {
                   4744:                 $checkrole .= "/$sec";
                   4745:             }
                   4746:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   4747:                 ($env{'request.role'} !~ /^st/)) {
                   4748:                 $has_evb = 1;
                   4749:             }
                   4750:             unless ($has_evb) {
                   4751:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   4752:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   4753:                     if ($udom eq $cdom) {
                   4754:                         $check_ipaccess = 1;
                   4755:                     }
                   4756:                 }
                   4757:             }
1.1075.2.161.  .3(raebu 4758:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   4759:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   4760:22):             my $checkrole;
                   4761:22):             if ($env{'request.role.domain'} eq '') {
                   4762:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   4763:22):             } else {
                   4764:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   4765:22):             }
                   4766:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   4767:22):                 $has_evb = 1;
                   4768:22):             }
1.1075.2.158  raeburn  4769:         }
                   4770:         unless ($has_evb || $check_ipaccess) {
                   4771:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   4772:             if (($dom eq 'public') && ($activity eq 'port')) {
                   4773:                 $dom = $udom;
                   4774:             }
                   4775:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   4776:                 $check_ipaccess = 1;
                   4777:             } else {
                   4778:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   4779:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   4780:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   4781:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   4782:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   4783:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   4784:                         $check_ipaccess = 1;
                   4785:                     }
                   4786:                 }
                   4787:             }
                   4788:         }
                   4789:         if ($check_ipaccess) {
                   4790:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   4791:             unless (defined($cached)) {
                   4792:                 my %domconfig =
                   4793:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   4794:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   4795:             }
                   4796:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   4797:                 foreach my $id (keys(%{$ipaccessref})) {
                   4798:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   4799:                         my $range = $ipaccessref->{$id}->{'ip'};
                   4800:                         if ($range) {
                   4801:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   4802:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   4803:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   4804:                                         return ('','','',$id,$dom);
                   4805:                                         last;
                   4806:                                     }
                   4807:                                 }
                   4808:                             }
                   4809:                         }
                   4810:                     }
                   4811:                 }
                   4812:             }
                   4813:         }
                   4814:     }
1.1075.2.73  raeburn  4815:     if (defined($udom) && defined($uname)) {
                   4816:         # If uname and udom are for a course, check for blocks in the course.
                   4817:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4818:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  4819:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  4820:             return ($startblock,$endblock,$triggerblock);
                   4821:         }
                   4822:     } else {
1.490     raeburn  4823:         $udom = $env{'user.domain'};
                   4824:         $uname = $env{'user.name'};
                   4825:     }
                   4826: 
1.502     raeburn  4827:     my $startblock = 0;
                   4828:     my $endblock = 0;
1.1062    raeburn  4829:     my $triggerblock = '';
1.1075.2.160  raeburn  4830:     my %live_courses;
                   4831:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   4832:         %live_courses = &findallcourses(undef,$uname,$udom);
                   4833:     }
1.474     raeburn  4834: 
1.490     raeburn  4835:     # If uname is for a user, and activity is course-specific, i.e.,
                   4836:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4837: 
1.490     raeburn  4838:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 4839:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   4840:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   4841:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  4842:         foreach my $key (keys(%live_courses)) {
                   4843:             if ($key ne $env{'request.course.id'}) {
                   4844:                 delete($live_courses{$key});
                   4845:             }
                   4846:         }
                   4847:     }
                   4848: 
                   4849:     my $otheruser = 0;
                   4850:     my %own_courses;
                   4851:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4852:         # Resource belongs to user other than current user.
                   4853:         $otheruser = 1;
                   4854:         # Gather courses for current user
                   4855:         %own_courses = 
                   4856:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4857:     }
                   4858: 
                   4859:     # Gather active course roles - course coordinator, instructor, 
                   4860:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4861: 
                   4862:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4863:         my ($cdom,$cnum);
                   4864:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4865:             $cdom = $env{'course.'.$course.'.domain'};
                   4866:             $cnum = $env{'course.'.$course.'.num'};
                   4867:         } else {
1.490     raeburn  4868:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4869:         }
                   4870:         my $no_ownblock = 0;
                   4871:         my $no_userblock = 0;
1.533     raeburn  4872:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4873:             # Check if current user has 'evb' priv for this
                   4874:             if (defined($own_courses{$course})) {
                   4875:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4876:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4877:                     if ($sec ne 'none') {
                   4878:                         $checkrole .= '/'.$sec;
                   4879:                     }
                   4880:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4881:                         $no_ownblock = 1;
                   4882:                         last;
                   4883:                     }
                   4884:                 }
                   4885:             }
                   4886:             # if they have 'evb' priv and are currently not playing student
                   4887:             next if (($no_ownblock) &&
                   4888:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4889:         }
1.474     raeburn  4890:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4891:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4892:             if ($sec ne 'none') {
1.482     raeburn  4893:                 $checkrole .= '/'.$sec;
1.474     raeburn  4894:             }
1.490     raeburn  4895:             if ($otheruser) {
                   4896:                 # Resource belongs to user other than current user.
                   4897:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4898:                 my (%allroles,%userroles);
                   4899:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4900:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4901:                         my ($trole,$tdom,$tnum,$tsec);
                   4902:                         if ($entry =~ /^cr/) {
                   4903:                             ($trole,$tdom,$tnum,$tsec) = 
                   4904:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4905:                         } else {
                   4906:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4907:                         }
                   4908:                         my ($spec,$area,$trest);
                   4909:                         $area = '/'.$tdom.'/'.$tnum;
                   4910:                         $trest = $tnum;
                   4911:                         if ($tsec ne '') {
                   4912:                             $area .= '/'.$tsec;
                   4913:                             $trest .= '/'.$tsec;
                   4914:                         }
                   4915:                         $spec = $trole.'.'.$area;
                   4916:                         if ($trole =~ /^cr/) {
                   4917:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4918:                                                               $tdom,$spec,$trest,$area);
                   4919:                         } else {
                   4920:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4921:                                                                 $tdom,$spec,$trest,$area);
                   4922:                         }
                   4923:                     }
1.1075.2.124  raeburn  4924:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4925:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4926:                         if ($1) {
                   4927:                             $no_userblock = 1;
                   4928:                             last;
                   4929:                         }
1.486     raeburn  4930:                     }
                   4931:                 }
1.490     raeburn  4932:             } else {
                   4933:                 # Resource belongs to current user
                   4934:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4935:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4936:                     $no_ownblock = 1;
                   4937:                     last;
                   4938:                 }
1.474     raeburn  4939:             }
                   4940:         }
                   4941:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4942:         next if (($no_ownblock) &&
1.491     albertel 4943:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4944:         next if ($no_userblock);
1.474     raeburn  4945: 
1.1075.2.128  raeburn  4946:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4947:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4948:         
1.1062    raeburn  4949:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  4950:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  4951:         if (($start != 0) && 
                   4952:             (($startblock == 0) || ($startblock > $start))) {
                   4953:             $startblock = $start;
1.1062    raeburn  4954:             if ($trigger ne '') {
                   4955:                 $triggerblock = $trigger;
                   4956:             }
1.502     raeburn  4957:         }
                   4958:         if (($end != 0)  &&
                   4959:             (($endblock == 0) || ($endblock < $end))) {
                   4960:             $endblock = $end;
1.1062    raeburn  4961:             if ($trigger ne '') {
                   4962:                 $triggerblock = $trigger;
                   4963:             }
1.502     raeburn  4964:         }
1.490     raeburn  4965:     }
1.1062    raeburn  4966:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4967: }
                   4968: 
                   4969: sub get_blocks {
1.1075.2.147  raeburn  4970:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  4971:     my $startblock = 0;
                   4972:     my $endblock = 0;
1.1062    raeburn  4973:     my $triggerblock = '';
1.490     raeburn  4974:     my $course = $cdom.'_'.$cnum;
                   4975:     $setters->{$course} = {};
                   4976:     $setters->{$course}{'staff'} = [];
                   4977:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4978:     $setters->{$course}{'triggers'} = [];
                   4979:     my (@blockers,%triggered);
                   4980:     my $now = time;
                   4981:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4982:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  4983:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  4984:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   4985:             $blocked = 1;
                   4986:             $nosymbcache = 1;
1.1075.2.148  raeburn  4987:             $noenccheck = 1;
1.1075.2.147  raeburn  4988:         }
1.1075.2.148  raeburn  4989:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  4990:         foreach my $block (@blockers) {
                   4991:             if ($block =~ /^firstaccess____(.+)$/) {
                   4992:                 my $item = $1;
                   4993:                 my $type = 'map';
                   4994:                 my $timersymb = $item;
                   4995:                 if ($item eq 'course') {
                   4996:                     $type = 'course';
                   4997:                 } elsif ($item =~ /___\d+___/) {
                   4998:                     $type = 'resource';
                   4999:                 } else {
                   5000:                     $timersymb = &Apache::lonnet::symbread($item);
                   5001:                 }
                   5002:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5003:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5004:                 $triggered{$block} = {
                   5005:                                        start => $start,
                   5006:                                        end   => $end,
                   5007:                                        type  => $type,
                   5008:                                      };
                   5009:             }
                   5010:         }
                   5011:     } else {
                   5012:         foreach my $block (keys(%commblocks)) {
                   5013:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5014:                 my ($start,$end) = ($1,$2);
                   5015:                 if ($start <= time && $end >= time) {
                   5016:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5017:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5018:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5019:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5020:                                     push(@blockers,$block);
                   5021:                                 }
                   5022:                             }
                   5023:                         }
                   5024:                     }
                   5025:                 }
                   5026:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5027:                 my $item = $1;
                   5028:                 my $timersymb = $item; 
                   5029:                 my $type = 'map';
                   5030:                 if ($item eq 'course') {
                   5031:                     $type = 'course';
                   5032:                 } elsif ($item =~ /___\d+___/) {
                   5033:                     $type = 'resource';
                   5034:                 } else {
                   5035:                     $timersymb = &Apache::lonnet::symbread($item);
                   5036:                 }
                   5037:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5038:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5039:                 if ($start && $end) {
                   5040:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5041:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5042:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5043:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5044:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5045:                                         push(@blockers,$block);
                   5046:                                         $triggered{$block} = {
                   5047:                                                                start => $start,
                   5048:                                                                end   => $end,
                   5049:                                                                type  => $type,
                   5050:                                                              };
                   5051:                                     }
                   5052:                                 }
                   5053:                             }
1.1062    raeburn  5054:                         }
                   5055:                     }
1.490     raeburn  5056:                 }
1.1062    raeburn  5057:             }
                   5058:         }
                   5059:     }
                   5060:     foreach my $blocker (@blockers) {
                   5061:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5062:             &parse_block_record($commblocks{$blocker});
                   5063:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5064:         my ($start,$end,$triggertype);
                   5065:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5066:             ($start,$end) = ($1,$2);
                   5067:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5068:             $start = $triggered{$blocker}{'start'};
                   5069:             $end = $triggered{$blocker}{'end'};
                   5070:             $triggertype = $triggered{$blocker}{'type'};
                   5071:         }
                   5072:         if ($start) {
                   5073:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5074:             if ($triggertype) {
                   5075:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5076:             } else {
                   5077:                 push(@{$$setters{$course}{'triggers'}},0);
                   5078:             }
                   5079:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5080:                 $startblock = $start;
                   5081:                 if ($triggertype) {
                   5082:                     $triggerblock = $blocker;
1.474     raeburn  5083:                 }
                   5084:             }
1.1062    raeburn  5085:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5086:                $endblock = $end;
                   5087:                if ($triggertype) {
                   5088:                    $triggerblock = $blocker;
                   5089:                }
                   5090:             }
1.474     raeburn  5091:         }
                   5092:     }
1.1062    raeburn  5093:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5094: }
                   5095: 
                   5096: sub parse_block_record {
                   5097:     my ($record) = @_;
                   5098:     my ($setuname,$setudom,$title,$blocks);
                   5099:     if (ref($record) eq 'HASH') {
                   5100:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5101:         $title = &unescape($record->{'event'});
                   5102:         $blocks = $record->{'blocks'};
                   5103:     } else {
                   5104:         my @data = split(/:/,$record,3);
                   5105:         if (scalar(@data) eq 2) {
                   5106:             $title = $data[1];
                   5107:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5108:         } else {
                   5109:             ($setuname,$setudom,$title) = @data;
                   5110:         }
                   5111:         $blocks = { 'com' => 'on' };
                   5112:     }
                   5113:     return ($setuname,$setudom,$title,$blocks);
                   5114: }
                   5115: 
1.854     kalberla 5116: sub blocking_status {
1.1075.2.158  raeburn  5117:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5118:     my %setters;
1.890     droeschl 5119: 
1.1061    raeburn  5120: # check for active blocking
1.1075.2.158  raeburn  5121:     if ($clientip eq '') {
                   5122:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5123:     }
                   5124:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5125:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5126:     my $blocked = 0;
1.1075.2.158  raeburn  5127:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5128:         $blocked = 1;
                   5129:     }
1.890     droeschl 5130: 
1.1061    raeburn  5131: # caller just wants to know whether a block is active
                   5132:     if (!wantarray) { return $blocked; }
                   5133: 
                   5134: # build a link to a popup window containing the details
                   5135:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5136: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5137:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5138:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5139:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5140:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5141:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5142:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5143:         if ($symb) {
                   5144:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5145:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5146:         }
1.1062    raeburn  5147:     }
1.1061    raeburn  5148: 
                   5149:     my $output .= <<'END_MYBLOCK';
                   5150: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5151:     var options = "width=" + w + ",height=" + h + ",";
                   5152:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5153:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5154:     var newWin = window.open(url, wdwName, options);
                   5155:     newWin.focus();
                   5156: }
1.890     droeschl 5157: END_MYBLOCK
1.854     kalberla 5158: 
1.1061    raeburn  5159:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5160:   
1.1061    raeburn  5161:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5162:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5163:     my $class = 'LC_comblock';
1.1062    raeburn  5164:     if ($activity eq 'docs') {
                   5165:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5166:         $class = '';
1.1063    raeburn  5167:     } elsif ($activity eq 'printout') {
                   5168:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5169:     } elsif ($activity eq 'passwd') {
                   5170:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5171:     } elsif ($activity eq 'grades') {
                   5172:         $text = &mt('Gradebook Blocked');
                   5173:     } elsif ($activity eq 'search') {
                   5174:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5175:21):     } elsif ($activity eq 'alert') {
                   5176:21):         $text = &mt('Checking Critical Messages Blocked');
                   5177:21):     } elsif ($activity eq 'reinit') {
                   5178:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5179:     } elsif ($activity eq 'about') {
                   5180:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5181:     } elsif ($activity eq 'wishlist') {
                   5182:         $text = &mt('Access to Stored Links Blocked');
                   5183:     } elsif ($activity eq 'annotate') {
                   5184:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5185:     }
1.1061    raeburn  5186:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5187: <div class='$class'>
1.869     kalberla 5188:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5189:   title='$text'>
                   5190:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5191:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5192:   title='$text'>$text</a>
1.867     kalberla 5193: </div>
                   5194: 
                   5195: END_BLOCK
1.474     raeburn  5196: 
1.1061    raeburn  5197:     return ($blocked, $output);
1.854     kalberla 5198: }
1.490     raeburn  5199: 
1.60      matthew  5200: ###############################################
                   5201: 
1.682     raeburn  5202: sub check_ip_acc {
1.1075.2.105  raeburn  5203:     my ($acc,$clientip)=@_;
1.682     raeburn  5204:     &Apache::lonxml::debug("acc is $acc");
                   5205:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5206:         return 1;
                   5207:     }
                   5208:     my $allowed=0;
1.1075.2.144  raeburn  5209:     my $ip;
                   5210:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5211:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5212:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5213:     } else {
1.1075.2.150  raeburn  5214:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5215:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5216:     }
1.682     raeburn  5217: 
                   5218:     my $name;
1.1075.2.161.  .1(raebu 5219:21):     my %access = (
                   5220:21):                      allowfrom => 1,
                   5221:21):                      denyfrom  => 0,
                   5222:21):                  );
                   5223:21):     my @allows;
                   5224:21):     my @denies;
                   5225:21):     foreach my $item (split(',',$acc)) {
                   5226:21):         $item =~ s/^\s*//;
                   5227:21):         $item =~ s/\s*$//;
                   5228:21):         if ($item =~ /^\!(.+)$/) {
                   5229:21):             push(@denies,$1);
                   5230:21):         } else {
                   5231:21):             push(@allows,$item);
                   5232:21):         }
                   5233:21):     }
                   5234:21):     my $numdenies = scalar(@denies);
                   5235:21):     my $numallows = scalar(@allows);
                   5236:21):     my $count = 0;
                   5237:21):     foreach my $pattern (@denies,@allows) {
                   5238:21):         $count ++;
                   5239:21):         my $acctype = 'allowfrom';
                   5240:21):         if ($count <= $numdenies) {
                   5241:21):             $acctype = 'denyfrom';
                   5242:21):         }
1.682     raeburn  5243:         if ($pattern =~ /\*$/) {
                   5244:             #35.8.*
                   5245:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5246:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5247:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5248:             #35.8.3.[34-56]
                   5249:             my $low=$2;
                   5250:             my $high=$3;
                   5251:             $pattern=$1;
                   5252:             if ($ip =~ /^\Q$pattern\E/) {
                   5253:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5254:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5255:             }
                   5256:         } elsif ($pattern =~ /^\*/) {
                   5257:             #*.msu.edu
                   5258:             $pattern=~s/\*//;
                   5259:             if (!defined($name)) {
                   5260:                 use Socket;
                   5261:                 my $netaddr=inet_aton($ip);
                   5262:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5263:             }
1.1075.2.161.  .1(raebu 5264:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5265:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5266:             #127.0.0.1
1.1075.2.161.  .1(raebu 5267:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5268:         } else {
                   5269:             #some.name.com
                   5270:             if (!defined($name)) {
                   5271:                 use Socket;
                   5272:                 my $netaddr=inet_aton($ip);
                   5273:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5274:             }
1.1075.2.161.  .1(raebu 5275:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5276:21):         }
                   5277:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5278:21):     }
                   5279:21):     if ($allowed eq '') {
                   5280:21):         if ($numdenies && !$numallows) {
                   5281:21):             $allowed = 1;
                   5282:21):         } else {
                   5283:21):             $allowed = 0;
1.682     raeburn  5284:         }
                   5285:     }
                   5286:     return $allowed;
                   5287: }
                   5288: 
                   5289: ###############################################
                   5290: 
1.60      matthew  5291: =pod
                   5292: 
1.112     bowersj2 5293: =head1 Domain Template Functions
                   5294: 
                   5295: =over 4
                   5296: 
                   5297: =item * &determinedomain()
1.60      matthew  5298: 
                   5299: Inputs: $domain (usually will be undef)
                   5300: 
1.63      www      5301: Returns: Determines which domain should be used for designs
1.60      matthew  5302: 
                   5303: =cut
1.54      www      5304: 
1.60      matthew  5305: ###############################################
1.63      www      5306: sub determinedomain {
                   5307:     my $domain=shift;
1.531     albertel 5308:     if (! $domain) {
1.60      matthew  5309:         # Determine domain if we have not been given one
1.893     raeburn  5310:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5311:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5312:         if ($env{'request.role.domain'}) { 
                   5313:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5314:         }
                   5315:     }
1.63      www      5316:     return $domain;
                   5317: }
                   5318: ###############################################
1.517     raeburn  5319: 
1.518     albertel 5320: sub devalidate_domconfig_cache {
                   5321:     my ($udom)=@_;
                   5322:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5323: }
                   5324: 
                   5325: # ---------------------- Get domain configuration for a domain
                   5326: sub get_domainconf {
                   5327:     my ($udom) = @_;
                   5328:     my $cachetime=1800;
                   5329:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5330:     if (defined($cached)) { return %{$result}; }
                   5331: 
                   5332:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5333: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5334:     my (%designhash,%legacy);
1.518     albertel 5335:     if (keys(%domconfig) > 0) {
                   5336:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5337:             if (keys(%{$domconfig{'login'}})) {
                   5338:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5339:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5340:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5341:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5342:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5343:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5344:                                         if ($key eq 'loginvia') {
                   5345:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5346:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5347:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5348:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5349:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5350:                                                 } else {
                   5351:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5352:                                                 }
1.948     raeburn  5353:                                             }
1.1075.2.87  raeburn  5354:                                         } elsif ($key eq 'headtag') {
                   5355:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5356:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5357:                                             }
1.946     raeburn  5358:                                         }
1.1075.2.87  raeburn  5359:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5360:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5361:                                         }
1.946     raeburn  5362:                                     }
                   5363:                                 }
                   5364:                             }
1.1075.2.158  raeburn  5365:                         } elsif ($key eq 'saml') {
                   5366:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5367:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5368:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5369:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   5370:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   5371:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5372:                                         }
                   5373:                                     }
                   5374:                                 }
                   5375:                             }
1.946     raeburn  5376:                         } else {
                   5377:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5378:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5379:                                     $domconfig{'login'}{$key}{$img};
                   5380:                             }
1.699     raeburn  5381:                         }
                   5382:                     } else {
                   5383:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5384:                     }
1.632     raeburn  5385:                 }
                   5386:             } else {
                   5387:                 $legacy{'login'} = 1;
1.518     albertel 5388:             }
1.632     raeburn  5389:         } else {
                   5390:             $legacy{'login'} = 1;
1.518     albertel 5391:         }
                   5392:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5393:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5394:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5395:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5396:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5397:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5398:                         }
1.518     albertel 5399:                     }
                   5400:                 }
1.632     raeburn  5401:             } else {
                   5402:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5403:             }
1.632     raeburn  5404:         } else {
                   5405:             $legacy{'rolecolors'} = 1;
1.518     albertel 5406:         }
1.948     raeburn  5407:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5408:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5409:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5410:             }
                   5411:         }
1.632     raeburn  5412:         if (keys(%legacy) > 0) {
                   5413:             my %legacyhash = &get_legacy_domconf($udom);
                   5414:             foreach my $item (keys(%legacyhash)) {
                   5415:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5416:                     if ($legacy{'login'}) { 
                   5417:                         $designhash{$item} = $legacyhash{$item};
                   5418:                     }
                   5419:                 } else {
                   5420:                     if ($legacy{'rolecolors'}) {
                   5421:                         $designhash{$item} = $legacyhash{$item};
                   5422:                     }
1.518     albertel 5423:                 }
                   5424:             }
                   5425:         }
1.632     raeburn  5426:     } else {
                   5427:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5428:     }
                   5429:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5430: 				  $cachetime);
                   5431:     return %designhash;
                   5432: }
                   5433: 
1.632     raeburn  5434: sub get_legacy_domconf {
                   5435:     my ($udom) = @_;
                   5436:     my %legacyhash;
                   5437:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5438:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5439:     if (-e $designfile) {
1.1075.2.128  raeburn  5440:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5441:             while (my $line = <$fh>) {
                   5442:                 next if ($line =~ /^\#/);
                   5443:                 chomp($line);
                   5444:                 my ($key,$val)=(split(/\=/,$line));
                   5445:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5446:             }
                   5447:             close($fh);
                   5448:         }
                   5449:     }
1.1026    raeburn  5450:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5451:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5452:     }
                   5453:     return %legacyhash;
                   5454: }
                   5455: 
1.63      www      5456: =pod
                   5457: 
1.112     bowersj2 5458: =item * &domainlogo()
1.63      www      5459: 
                   5460: Inputs: $domain (usually will be undef)
                   5461: 
                   5462: Returns: A link to a domain logo, if the domain logo exists.
                   5463: If the domain logo does not exist, a description of the domain.
                   5464: 
                   5465: =cut
1.112     bowersj2 5466: 
1.63      www      5467: ###############################################
                   5468: sub domainlogo {
1.517     raeburn  5469:     my $domain = &determinedomain(shift);
1.518     albertel 5470:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5471:     # See if there is a logo
                   5472:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5473:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5474:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5475: 	    if ($imgsrc =~ m{^/res/}) {
                   5476: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5477: 		&Apache::lonnet::repcopy($local_name);
                   5478: 	    }
                   5479: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5480:22):         }
                   5481:22):         my $alttext = $domain;
                   5482:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5483:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5484:22):         }
                   5485:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5486:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5487:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5488:     } else {
1.60      matthew  5489:         return '';
1.59      www      5490:     }
                   5491: }
1.63      www      5492: ##############################################
                   5493: 
                   5494: =pod
                   5495: 
1.112     bowersj2 5496: =item * &designparm()
1.63      www      5497: 
                   5498: Inputs: $which parameter; $domain (usually will be undef)
                   5499: 
                   5500: Returns: value of designparamter $which
                   5501: 
                   5502: =cut
1.112     bowersj2 5503: 
1.397     albertel 5504: 
1.400     albertel 5505: ##############################################
1.397     albertel 5506: sub designparm {
                   5507:     my ($which,$domain)=@_;
                   5508:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5509:         return $env{'environment.color.'.$which};
1.96      www      5510:     }
1.63      www      5511:     $domain=&determinedomain($domain);
1.1016    raeburn  5512:     my %domdesign;
                   5513:     unless ($domain eq 'public') {
                   5514:         %domdesign = &get_domainconf($domain);
                   5515:     }
1.520     raeburn  5516:     my $output;
1.517     raeburn  5517:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5518:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5519:     } else {
1.520     raeburn  5520:         $output = $defaultdesign{$which};
                   5521:     }
                   5522:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5523:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5524:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5525:             if ($output =~ m{^/res/}) {
                   5526:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5527:                 &Apache::lonnet::repcopy($local_name);
                   5528:             }
1.520     raeburn  5529:             $output = &lonhttpdurl($output);
                   5530:         }
1.63      www      5531:     }
1.520     raeburn  5532:     return $output;
1.63      www      5533: }
1.59      www      5534: 
1.822     bisitz   5535: ##############################################
                   5536: =pod
                   5537: 
1.832     bisitz   5538: =item * &authorspace()
                   5539: 
1.1028    raeburn  5540: Inputs: $url (usually will be undef).
1.832     bisitz   5541: 
1.1075.2.40  raeburn  5542: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5543:          directory being viewed (or for which action is being taken). 
                   5544:          If $url is provided, and begins /priv/<domain>/<uname>
                   5545:          the path will be that portion of the $context argument.
                   5546:          Otherwise the path will be for the author space of the current
                   5547:          user when the current role is author, or for that of the 
                   5548:          co-author/assistant co-author space when the current role 
                   5549:          is co-author or assistant co-author.
1.832     bisitz   5550: 
                   5551: =cut
                   5552: 
                   5553: sub authorspace {
1.1028    raeburn  5554:     my ($url) = @_;
                   5555:     if ($url ne '') {
                   5556:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5557:            return $1;
                   5558:         }
                   5559:     }
1.832     bisitz   5560:     my $caname = '';
1.1024    www      5561:     my $cadom = '';
1.1028    raeburn  5562:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5563:         ($cadom,$caname) =
1.832     bisitz   5564:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5565:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5566:         $caname = $env{'user.name'};
1.1024    www      5567:         $cadom = $env{'user.domain'};
1.832     bisitz   5568:     }
1.1028    raeburn  5569:     if (($caname ne '') && ($cadom ne '')) {
                   5570:         return "/priv/$cadom/$caname/";
                   5571:     }
                   5572:     return;
1.832     bisitz   5573: }
                   5574: 
                   5575: ##############################################
                   5576: =pod
                   5577: 
1.822     bisitz   5578: =item * &head_subbox()
                   5579: 
                   5580: Inputs: $content (contains HTML code with page functions, etc.)
                   5581: 
                   5582: Returns: HTML div with $content
                   5583:          To be included in page header
                   5584: 
                   5585: =cut
                   5586: 
                   5587: sub head_subbox {
                   5588:     my ($content)=@_;
                   5589:     my $output =
1.993     raeburn  5590:         '<div class="LC_head_subbox">'
1.822     bisitz   5591:        .$content
                   5592:        .'</div>'
                   5593: }
                   5594: 
                   5595: ##############################################
                   5596: =pod
                   5597: 
                   5598: =item * &CSTR_pageheader()
                   5599: 
1.1026    raeburn  5600: Input: (optional) filename from which breadcrumb trail is built.
                   5601:        In most cases no input as needed, as $env{'request.filename'}
                   5602:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5603: 
                   5604: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5605:          To be included on Authoring Space pages
1.822     bisitz   5606: 
                   5607: =cut
                   5608: 
                   5609: sub CSTR_pageheader {
1.1026    raeburn  5610:     my ($trailfile) = @_;
                   5611:     if ($trailfile eq '') {
                   5612:         $trailfile = $env{'request.filename'};
                   5613:     }
                   5614: 
                   5615: # this is for resources; directories have customtitle, and crumbs
                   5616: # and select recent are created in lonpubdir.pm
                   5617: 
                   5618:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5619:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5620:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5621:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5622:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5623: 
                   5624:     my $parentpath = '';
                   5625:     my $lastitem = '';
                   5626:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5627:         $parentpath = $1;
                   5628:         $lastitem = $2;
                   5629:     } else {
                   5630:         $lastitem = $thisdisfn;
                   5631:     }
1.921     bisitz   5632: 
                   5633:     my $output =
1.822     bisitz   5634:          '<div>'
                   5635:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5636:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5637:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5638:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5639:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5640: 
                   5641:     if ($lastitem) {
                   5642:         $output .=
                   5643:              '<span class="LC_filename">'
                   5644:             .$lastitem
                   5645:             .'</span>';
                   5646:     }
                   5647:     $output .=
                   5648:          '<br />'
1.822     bisitz   5649:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5650:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5651:         .'</form>'
                   5652:         .&Apache::lonmenu::constspaceform()
                   5653:         .'</div>';
1.921     bisitz   5654: 
                   5655:     return $output;
1.822     bisitz   5656: }
                   5657: 
1.60      matthew  5658: ###############################################
                   5659: ###############################################
                   5660: 
                   5661: =pod
                   5662: 
1.112     bowersj2 5663: =back
                   5664: 
1.549     albertel 5665: =head1 HTML Helpers
1.112     bowersj2 5666: 
                   5667: =over 4
                   5668: 
                   5669: =item * &bodytag()
1.60      matthew  5670: 
                   5671: Returns a uniform header for LON-CAPA web pages.
                   5672: 
                   5673: Inputs: 
                   5674: 
1.112     bowersj2 5675: =over 4
                   5676: 
                   5677: =item * $title, A title to be displayed on the page.
                   5678: 
                   5679: =item * $function, the current role (can be undef).
                   5680: 
                   5681: =item * $addentries, extra parameters for the <body> tag.
                   5682: 
                   5683: =item * $bodyonly, if defined, only return the <body> tag.
                   5684: 
                   5685: =item * $domain, if defined, force a given domain.
                   5686: 
                   5687: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5688:             text interface only)
1.60      matthew  5689: 
1.814     bisitz   5690: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5691:                      navigational links
1.317     albertel 5692: 
1.338     albertel 5693: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5694: 
1.1075.2.12  raeburn  5695: =item * $no_inline_link, if true and in remote mode, don't show the
                   5696:          'Switch To Inline Menu' link
                   5697: 
1.460     albertel 5698: =item * $args, optional argument valid values are
                   5699:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5700:             use_absolute     -> for external resource or syllabus, this will
                   5701:                                 contain https://<hostname> if server uses
                   5702:                                 https (as per hosts.tab), but request is for http
                   5703:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5704: 
1.1075.2.15  raeburn  5705: =item * $advtoolsref, optional argument, ref to an array containing
                   5706:             inlineremote items to be added in "Functions" menu below
                   5707:             breadcrumbs.
                   5708: 
1.1075.2.161.  .1(raebu 5709:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   5710:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   5711:21):             the scope of use, i.e., launch was for access to a single, a map
                   5712:21):             or the entire course.
                   5713:21): 
                   5714:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   5715:21):             context, this will contain the URL for the landing item in
                   5716:21):             the course, after launch from an LTI Consumer
                   5717:21): 
                   5718:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   5719:21):             context, this will contain a reference to hash of items
                   5720:21):             to be included in the page header and/or inline menu.
                   5721:21): 
1.112     bowersj2 5722: =back
                   5723: 
1.60      matthew  5724: Returns: A uniform header for LON-CAPA web pages.  
                   5725: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5726: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5727: other decorations will be returned.
                   5728: 
                   5729: =cut
                   5730: 
1.54      www      5731: sub bodytag {
1.831     bisitz   5732:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 5733:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
                   5734:21):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 5735: 
1.954     raeburn  5736:     my $public;
                   5737:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5738:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5739:         $public = 1;
                   5740:     }
1.460     albertel 5741:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5742:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5743:     my $hostname = $args->{'hostname'};
1.339     albertel 5744: 
1.183     matthew  5745:     $function = &get_users_function() if (!$function);
1.339     albertel 5746:     my $img =    &designparm($function.'.img',$domain);
                   5747:     my $font =   &designparm($function.'.font',$domain);
                   5748:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5749: 
1.803     bisitz   5750:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5751: 		   'bgcolor' => $pgbg,
1.339     albertel 5752: 		   'text'    => $font,
                   5753:                    'alink'   => &designparm($function.'.alink',$domain),
                   5754: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5755: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5756:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5757: 
1.63      www      5758:  # role and realm
1.1075.2.68  raeburn  5759:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5760:     if ($realm) {
                   5761:         $realm = '/'.$realm;
                   5762:     }
1.1075.2.159  raeburn  5763:     if ($role eq 'ca') {
1.479     albertel 5764:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5765:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5766:     } 
1.55      www      5767: # realm
1.1075.2.158  raeburn  5768:     my ($cid,$sec);
1.258     albertel 5769:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  5770:         $cid = $env{'request.course.id'};
                   5771:         if ($env{'request.course.sec'}) {
                   5772:             $sec = $env{'request.course.sec'};
                   5773:         }
                   5774:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   5775:         if (&Apache::lonnet::is_course($1,$2)) {
                   5776:             $cid = $1.'_'.$2;
                   5777:             $sec = $3;
                   5778:         }
                   5779:     }
                   5780:     if ($cid) {
1.378     raeburn  5781:         if ($env{'request.role'} !~ /^cr/) {
                   5782:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5783:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5784:             if ($env{'request.role.desc'}) {
                   5785:                 $role = $env{'request.role.desc'};
                   5786:             } else {
                   5787:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5788:             }
1.1075.2.115  raeburn  5789:         } else {
                   5790:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5791:         }
1.1075.2.158  raeburn  5792:         if ($sec) {
                   5793:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  5794:         }   
1.1075.2.158  raeburn  5795: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  5796:     } else {
                   5797:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5798:     }
1.433     albertel 5799: 
1.359     albertel 5800:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5801: 
1.438     albertel 5802:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5803: 
1.101     www      5804: # construct main body tag
1.359     albertel 5805:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5806: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5807: 
1.1075.2.38  raeburn  5808:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5809: 
                   5810:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5811:         return $bodytag;
1.1075.2.38  raeburn  5812:     }
1.359     albertel 5813: 
1.954     raeburn  5814:     if ($public) {
1.433     albertel 5815: 	undef($role);
                   5816:     }
1.1075.2.158  raeburn  5817: 
1.1075.2.161.  .1(raebu 5818:21):     my $showcrstitle = 1;
                   5819:21):     if (($cid) && ($env{'request.lti.login'})) {
                   5820:21):         if (ref($ltimenu) eq 'HASH') {
                   5821:21):             unless ($ltimenu->{'role'}) {
                   5822:21):                 undef($role);
                   5823:21):             }
                   5824:21):             unless ($ltimenu->{'coursetitle'}) {
                   5825:21):                 $realm='&nbsp;';
                   5826:21):                 $showcrstitle = 0;
                   5827:21):             }
                   5828:21):         }
                   5829:21):     } elsif (($cid) && ($menucoll)) {
                   5830:21):         if (ref($menuref) eq 'HASH') {
                   5831:21):             unless ($menuref->{'role'}) {
                   5832:21):                 undef($role);
                   5833:21):             }
                   5834:21):             unless ($menuref->{'crs'}) {
                   5835:21):                 $realm='&nbsp;';
                   5836:21):                 $showcrstitle = 0;
                   5837:21):             }
                   5838:21):         }
                   5839:21):     }
                   5840:21): 
1.762     bisitz   5841:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5842:     #
                   5843:     # Extra info if you are the DC
                   5844:     my $dc_info = '';
1.1075.2.161.  .1(raebu 5845:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  5846:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  5847:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5848:         $dc_info =~ s/\s+$//;
1.359     albertel 5849:     }
                   5850: 
1.1075.2.161.  .1(raebu 5851:21):     my $crstype;
                   5852:21):     if ($cid) {
                   5853:21):         $crstype = $env{'course.'.$cid.'.type'};
                   5854:21):     } elsif ($args->{'crstype'}) {
                   5855:21):         $crstype = $args->{'crstype'};
                   5856:21):     }
                   5857:21): 
1.1075.2.108  raeburn  5858:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5859: 
1.1075.2.13  raeburn  5860:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5861: 
1.1075.2.38  raeburn  5862: 
                   5863: 
1.1075.2.21  raeburn  5864:     my $funclist;
                   5865:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5866:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5867:                     Apache::lonmenu::serverform();
                   5868:         my $forbodytag;
                   5869:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5870:                                             $forcereg,$args->{'group'},
                   5871:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5872:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5873:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5874:             $funclist = $forbodytag;
                   5875:         }
                   5876:     } else {
1.903     droeschl 5877: 
                   5878:         #    if ($env{'request.state'} eq 'construct') {
                   5879:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5880:         #    }
                   5881: 
1.1075.2.38  raeburn  5882:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5883:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5884: 
1.1075.2.161.  .1(raebu 5885:21):         unless ($args->{'no_primary_menu'}) {
                   5886:21):             my ($left,$right) = Apache::lonmenu::primary_menu($args->{'links_disabled'});
1.1075.2.2  raeburn  5887: 
1.1075.2.161.  .1(raebu 5888:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   5889:21):                 if ($dc_info) {
                   5890:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5891:21):                 }
                   5892:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   5893:21):                                <em>$realm</em> $dc_info</div>|;
                   5894:21):                 return $bodytag;
1.1075.2.1  raeburn  5895:             }
1.894     droeschl 5896: 
1.1075.2.161.  .1(raebu 5897:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   5898:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   5899:21):             }
1.916     droeschl 5900: 
1.1075.2.161.  .1(raebu 5901:21):             $bodytag .= $right;
1.852     droeschl 5902: 
1.1075.2.161.  .1(raebu 5903:21):             if ($dc_info) {
                   5904:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   5905:21):             }
                   5906:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  5907:         }
1.916     droeschl 5908: 
1.1075.2.61  raeburn  5909:         #if directed to not display the secondary menu, don't.
                   5910:         if ($args->{'no_secondary_menu'}) {
                   5911:             return $bodytag;
                   5912:         }
1.903     droeschl 5913:         #don't show menus for public users
1.954     raeburn  5914:         if (!$public){
1.1075.2.161.  .1(raebu 5915:21):             unless ($args->{'no_inline_menu'}) {
                   5916:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   5917:21):                                                             $args->{'no_primary_menu'},
                   5918:21):                                                             $menucoll,$menuref,
                   5919:21):                                                             $args->{'links_disabled'});
                   5920:21):             }
1.903     droeschl 5921:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5922:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5923:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5924:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .1(raebu 5925:21):                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1075.2.116  raeburn  5926:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5927:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5928:                                                             $args->{'group'},
1.1075.2.161  raeburn  5929:                                                             $args->{'hide_buttons'},
1.1075.2.161.  .1(raebu 5930:21):                                                             $hostname,$ltiscope,$ltiuri);
1.1075.2.15  raeburn  5931:             } else {
1.1075.2.21  raeburn  5932:                 my $forbodytag;
                   5933:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5934:                                                     $forcereg,$args->{'group'},
                   5935:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5936:                                                     $advtoolsref,'',$hostname,
                   5937:                                                     \$forbodytag);
1.1075.2.21  raeburn  5938:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5939:                     $bodytag .= $forbodytag;
                   5940:                 }
1.920     raeburn  5941:             }
1.903     droeschl 5942:         }else{
                   5943:             # this is to seperate menu from content when there's no secondary
                   5944:             # menu. Especially needed for public accessible ressources.
                   5945:             $bodytag .= '<hr style="clear:both" />';
                   5946:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5947:         }
1.903     droeschl 5948: 
1.235     raeburn  5949:         return $bodytag;
1.1075.2.12  raeburn  5950:     }
                   5951: 
                   5952: #
                   5953: # Top frame rendering, Remote is up
                   5954: #
                   5955: 
                   5956:     my $imgsrc = $img;
                   5957:     if ($img =~ /^\/adm/) {
                   5958:         $imgsrc = &lonhttpdurl($img);
                   5959:     }
                   5960:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5961: 
1.1075.2.60  raeburn  5962:     my $help=($no_inline_link?''
                   5963:               :&Apache::loncommon::top_nav_help('Help'));
                   5964: 
1.1075.2.12  raeburn  5965:     # Explicit link to get inline menu
                   5966:     my $menu= ($no_inline_link?''
                   5967:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5968: 
                   5969:     if ($dc_info) {
                   5970:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5971:     }
                   5972: 
1.1075.2.38  raeburn  5973:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5974:     unless ($public) {
                   5975:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5976:                                 undef,'LC_menubuttons_link');
                   5977:     }
                   5978: 
1.1075.2.12  raeburn  5979:     unless ($env{'form.inhibitmenu'}) {
                   5980:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5981:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5982:                        <li>$help</li>
1.1075.2.12  raeburn  5983:                        <li>$menu</li>
                   5984:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5985:     }
1.1075.2.13  raeburn  5986:     if ($env{'request.state'} eq 'construct') {
                   5987:         if (!$public){
                   5988:             if ($env{'request.state'} eq 'construct') {
                   5989:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5990:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5991:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5992:                             &Apache::lonmenu::innerregister($forcereg,
                   5993:                                                             $args->{'bread_crumbs'});
                   5994:             }
                   5995:         }
                   5996:     }
1.1075.2.21  raeburn  5997:     return $bodytag."\n".$funclist;
1.182     matthew  5998: }
                   5999: 
1.917     raeburn  6000: sub dc_courseid_toggle {
                   6001:     my ($dc_info) = @_;
1.980     raeburn  6002:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6003:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6004:            &mt('(More ...)').'</a></span>'.
                   6005:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6006: }
                   6007: 
1.330     albertel 6008: sub make_attr_string {
                   6009:     my ($register,$attr_ref) = @_;
                   6010: 
                   6011:     if ($attr_ref && !ref($attr_ref)) {
                   6012: 	die("addentries Must be a hash ref ".
                   6013: 	    join(':',caller(1))." ".
                   6014: 	    join(':',caller(0))." ");
                   6015:     }
                   6016: 
                   6017:     if ($register) {
1.339     albertel 6018: 	my ($on_load,$on_unload);
                   6019: 	foreach my $key (keys(%{$attr_ref})) {
                   6020: 	    if      (lc($key) eq 'onload') {
                   6021: 		$on_load.=$attr_ref->{$key}.';';
                   6022: 		delete($attr_ref->{$key});
                   6023: 
                   6024: 	    } elsif (lc($key) eq 'onunload') {
                   6025: 		$on_unload.=$attr_ref->{$key}.';';
                   6026: 		delete($attr_ref->{$key});
                   6027: 	    }
                   6028: 	}
1.1075.2.12  raeburn  6029:         if ($env{'environment.remote'} eq 'on') {
                   6030:             $attr_ref->{'onload'}  =
                   6031:                 &Apache::lonmenu::loadevents().  $on_load;
                   6032:             $attr_ref->{'onunload'}=
                   6033:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6034:         } else {  
                   6035: 	    $attr_ref->{'onload'}  = $on_load;
                   6036: 	    $attr_ref->{'onunload'}= $on_unload;
                   6037:         }
1.330     albertel 6038:     }
1.339     albertel 6039: 
1.330     albertel 6040:     my $attr_string;
1.1075.2.56  raeburn  6041:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6042: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6043:     }
                   6044:     return $attr_string;
                   6045: }
                   6046: 
                   6047: 
1.182     matthew  6048: ###############################################
1.251     albertel 6049: ###############################################
                   6050: 
                   6051: =pod
                   6052: 
                   6053: =item * &endbodytag()
                   6054: 
                   6055: Returns a uniform footer for LON-CAPA web pages.
                   6056: 
1.635     raeburn  6057: Inputs: 1 - optional reference to an args hash
                   6058: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6059: a 'Continue' link is not displayed if the page contains an
                   6060: internal redirect in the <head></head> section,
                   6061: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6062: 
                   6063: =cut
                   6064: 
                   6065: sub endbodytag {
1.635     raeburn  6066:     my ($args) = @_;
1.1075.2.6  raeburn  6067:     my $endbodytag;
                   6068:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6069:         $endbodytag='</body>';
                   6070:     }
1.315     albertel 6071:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6072:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6073: 	    $endbodytag=
                   6074: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6075: 	        &mt('Continue').'</a>'.
                   6076: 	        $endbodytag;
                   6077:         }
1.315     albertel 6078:     }
1.251     albertel 6079:     return $endbodytag;
                   6080: }
                   6081: 
1.352     albertel 6082: =pod
                   6083: 
                   6084: =item * &standard_css()
                   6085: 
                   6086: Returns a style sheet
                   6087: 
                   6088: Inputs: (all optional)
                   6089:             domain         -> force to color decorate a page for a specific
                   6090:                                domain
                   6091:             function       -> force usage of a specific rolish color scheme
                   6092:             bgcolor        -> override the default page bgcolor
                   6093: 
                   6094: =cut
                   6095: 
1.343     albertel 6096: sub standard_css {
1.345     albertel 6097:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6098:     $function  = &get_users_function() if (!$function);
                   6099:     my $img    = &designparm($function.'.img',   $domain);
                   6100:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6101:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6102:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6103: #second colour for later usage
1.345     albertel 6104:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6105:     my $pgbg_or_bgcolor =
                   6106: 	         $bgcolor ||
1.352     albertel 6107: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6108:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6109:     my $alink  = &designparm($function.'.alink', $domain);
                   6110:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6111:     my $link   = &designparm($function.'.link',  $domain);
                   6112: 
1.602     albertel 6113:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6114:     my $mono                 = 'monospace';
1.850     bisitz   6115:     my $data_table_head      = $sidebg;
                   6116:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6117:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6118:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6119:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6120:     my $mail_new             = '#FFBB77';
                   6121:     my $mail_new_hover       = '#DD9955';
                   6122:     my $mail_read            = '#BBBB77';
                   6123:     my $mail_read_hover      = '#999944';
                   6124:     my $mail_replied         = '#AAAA88';
                   6125:     my $mail_replied_hover   = '#888855';
                   6126:     my $mail_other           = '#99BBBB';
                   6127:     my $mail_other_hover     = '#669999';
1.391     albertel 6128:     my $table_header         = '#DDDDDD';
1.489     raeburn  6129:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6130:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6131:     my $button_hover         = '#BF2317';
1.392     albertel 6132: 
1.608     albertel 6133:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6134:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6135:                                              : '0 3px 0 4px';
1.448     albertel 6136: 
1.523     albertel 6137: 
1.343     albertel 6138:     return <<END;
1.947     droeschl 6139: 
                   6140: /* needed for iframe to allow 100% height in FF */
                   6141: body, html { 
                   6142:     margin: 0;
                   6143:     padding: 0 0.5%;
                   6144:     height: 99%; /* to avoid scrollbars */
                   6145: }
                   6146: 
1.795     www      6147: body {
1.911     bisitz   6148:   font-family: $sans;
                   6149:   line-height:130%;
                   6150:   font-size:0.83em;
                   6151:   color:$font;
1.795     www      6152: }
                   6153: 
1.959     onken    6154: a:focus,
                   6155: a:focus img {
1.795     www      6156:   color: red;
                   6157: }
1.698     harmsja  6158: 
1.911     bisitz   6159: form, .inline {
                   6160:   display: inline;
1.795     www      6161: }
1.721     harmsja  6162: 
1.795     www      6163: .LC_right {
1.911     bisitz   6164:   text-align:right;
1.795     www      6165: }
                   6166: 
                   6167: .LC_middle {
1.911     bisitz   6168:   vertical-align:middle;
1.795     www      6169: }
1.721     harmsja  6170: 
1.1075.2.38  raeburn  6171: .LC_floatleft {
                   6172:   float: left;
                   6173: }
                   6174: 
                   6175: .LC_floatright {
                   6176:   float: right;
                   6177: }
                   6178: 
1.911     bisitz   6179: .LC_400Box {
                   6180:   width:400px;
                   6181: }
1.721     harmsja  6182: 
1.947     droeschl 6183: .LC_iframecontainer {
                   6184:     width: 98%;
                   6185:     margin: 0;
                   6186:     position: fixed;
                   6187:     top: 8.5em;
                   6188:     bottom: 0;
                   6189: }
                   6190: 
                   6191: .LC_iframecontainer iframe{
                   6192:     border: none;
                   6193:     width: 100%;
                   6194:     height: 100%;
                   6195: }
                   6196: 
1.778     bisitz   6197: .LC_filename {
                   6198:   font-family: $mono;
                   6199:   white-space:pre;
1.921     bisitz   6200:   font-size: 120%;
1.778     bisitz   6201: }
                   6202: 
                   6203: .LC_fileicon {
                   6204:   border: none;
                   6205:   height: 1.3em;
                   6206:   vertical-align: text-bottom;
                   6207:   margin-right: 0.3em;
                   6208:   text-decoration:none;
                   6209: }
                   6210: 
1.1008    www      6211: .LC_setting {
                   6212:   text-decoration:underline;
                   6213: }
                   6214: 
1.350     albertel 6215: .LC_error {
                   6216:   color: red;
                   6217: }
1.795     www      6218: 
1.1075.2.15  raeburn  6219: .LC_warning {
                   6220:   color: darkorange;
                   6221: }
                   6222: 
1.457     albertel 6223: .LC_diff_removed {
1.733     bisitz   6224:   color: red;
1.394     albertel 6225: }
1.532     albertel 6226: 
                   6227: .LC_info,
1.457     albertel 6228: .LC_success,
                   6229: .LC_diff_added {
1.350     albertel 6230:   color: green;
                   6231: }
1.795     www      6232: 
1.802     bisitz   6233: div.LC_confirm_box {
                   6234:   background-color: #FAFAFA;
                   6235:   border: 1px solid $lg_border_color;
                   6236:   margin-right: 0;
                   6237:   padding: 5px;
                   6238: }
                   6239: 
                   6240: div.LC_confirm_box .LC_error img,
                   6241: div.LC_confirm_box .LC_success img {
                   6242:   vertical-align: middle;
                   6243: }
                   6244: 
1.1075.2.108  raeburn  6245: .LC_maxwidth {
                   6246:   max-width: 100%;
                   6247:   height: auto;
                   6248: }
                   6249: 
                   6250: .LC_textsize_mobile {
                   6251:   \@media only screen and (max-device-width: 480px) {
                   6252:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6253:   }
                   6254: }
                   6255: 
1.440     albertel 6256: .LC_icon {
1.771     droeschl 6257:   border: none;
1.790     droeschl 6258:   vertical-align: middle;
1.771     droeschl 6259: }
                   6260: 
1.543     albertel 6261: .LC_docs_spacer {
                   6262:   width: 25px;
                   6263:   height: 1px;
1.771     droeschl 6264:   border: none;
1.543     albertel 6265: }
1.346     albertel 6266: 
1.532     albertel 6267: .LC_internal_info {
1.735     bisitz   6268:   color: #999999;
1.532     albertel 6269: }
                   6270: 
1.794     www      6271: .LC_discussion {
1.1050    www      6272:   background: $data_table_dark;
1.911     bisitz   6273:   border: 1px solid black;
                   6274:   margin: 2px;
1.794     www      6275: }
                   6276: 
                   6277: .LC_disc_action_left {
1.1050    www      6278:   background: $sidebg;
1.911     bisitz   6279:   text-align: left;
1.1050    www      6280:   padding: 4px;
                   6281:   margin: 2px;
1.794     www      6282: }
                   6283: 
                   6284: .LC_disc_action_right {
1.1050    www      6285:   background: $sidebg;
1.911     bisitz   6286:   text-align: right;
1.1050    www      6287:   padding: 4px;
                   6288:   margin: 2px;
1.794     www      6289: }
                   6290: 
                   6291: .LC_disc_new_item {
1.911     bisitz   6292:   background: white;
                   6293:   border: 2px solid red;
1.1050    www      6294:   margin: 4px;
                   6295:   padding: 4px;
1.794     www      6296: }
                   6297: 
                   6298: .LC_disc_old_item {
1.911     bisitz   6299:   background: white;
1.1050    www      6300:   margin: 4px;
                   6301:   padding: 4px;
1.794     www      6302: }
                   6303: 
1.458     albertel 6304: table.LC_pastsubmission {
                   6305:   border: 1px solid black;
                   6306:   margin: 2px;
                   6307: }
                   6308: 
1.924     bisitz   6309: table#LC_menubuttons {
1.345     albertel 6310:   width: 100%;
                   6311:   background: $pgbg;
1.392     albertel 6312:   border: 2px;
1.402     albertel 6313:   border-collapse: separate;
1.803     bisitz   6314:   padding: 0;
1.345     albertel 6315: }
1.392     albertel 6316: 
1.801     tempelho 6317: table#LC_title_bar a {
                   6318:   color: $fontmenu;
                   6319: }
1.836     bisitz   6320: 
1.807     droeschl 6321: table#LC_title_bar {
1.819     tempelho 6322:   clear: both;
1.836     bisitz   6323:   display: none;
1.807     droeschl 6324: }
                   6325: 
1.795     www      6326: table#LC_title_bar,
1.933     droeschl 6327: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6328: table#LC_title_bar.LC_with_remote {
1.359     albertel 6329:   width: 100%;
1.392     albertel 6330:   border-color: $pgbg;
                   6331:   border-style: solid;
                   6332:   border-width: $border;
1.379     albertel 6333:   background: $pgbg;
1.801     tempelho 6334:   color: $fontmenu;
1.392     albertel 6335:   border-collapse: collapse;
1.803     bisitz   6336:   padding: 0;
1.819     tempelho 6337:   margin: 0;
1.359     albertel 6338: }
1.795     www      6339: 
1.933     droeschl 6340: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6341:     margin: 0;
                   6342:     padding: 0;
1.933     droeschl 6343:     position: relative;
                   6344:     list-style: none;
1.913     droeschl 6345: }
1.933     droeschl 6346: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6347:     display: inline;
                   6348: }
1.933     droeschl 6349: 
                   6350: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6351:     padding: 0;
1.933     droeschl 6352:     margin: 0;
                   6353:     float: left;
1.913     droeschl 6354: }
1.933     droeschl 6355: .LC_breadcrumb_tools_tools {
                   6356:     padding: 0;
                   6357:     margin: 0;
1.913     droeschl 6358:     float: right;
                   6359: }
                   6360: 
1.359     albertel 6361: table#LC_title_bar td {
                   6362:   background: $tabbg;
                   6363: }
1.795     www      6364: 
1.911     bisitz   6365: table#LC_menubuttons img {
1.803     bisitz   6366:   border: none;
1.346     albertel 6367: }
1.795     www      6368: 
1.842     droeschl 6369: .LC_breadcrumbs_component {
1.911     bisitz   6370:   float: right;
                   6371:   margin: 0 1em;
1.357     albertel 6372: }
1.842     droeschl 6373: .LC_breadcrumbs_component img {
1.911     bisitz   6374:   vertical-align: middle;
1.777     tempelho 6375: }
1.795     www      6376: 
1.1075.2.108  raeburn  6377: .LC_breadcrumbs_hoverable {
                   6378:   background: $sidebg;
                   6379: }
                   6380: 
1.383     albertel 6381: td.LC_table_cell_checkbox {
                   6382:   text-align: center;
                   6383: }
1.795     www      6384: 
                   6385: .LC_fontsize_small {
1.911     bisitz   6386:   font-size: 70%;
1.705     tempelho 6387: }
                   6388: 
1.844     bisitz   6389: #LC_breadcrumbs {
1.911     bisitz   6390:   clear:both;
                   6391:   background: $sidebg;
                   6392:   border-bottom: 1px solid $lg_border_color;
                   6393:   line-height: 2.5em;
1.933     droeschl 6394:   overflow: hidden;
1.911     bisitz   6395:   margin: 0;
                   6396:   padding: 0;
1.995     raeburn  6397:   text-align: left;
1.819     tempelho 6398: }
1.862     bisitz   6399: 
1.1075.2.16  raeburn  6400: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6401:   clear:both;
                   6402:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6403:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6404:   margin: 0 0 10px 0;
1.966     bisitz   6405:   padding: 3px;
1.995     raeburn  6406:   text-align: left;
1.822     bisitz   6407: }
                   6408: 
1.795     www      6409: .LC_fontsize_medium {
1.911     bisitz   6410:   font-size: 85%;
1.705     tempelho 6411: }
                   6412: 
1.795     www      6413: .LC_fontsize_large {
1.911     bisitz   6414:   font-size: 120%;
1.705     tempelho 6415: }
                   6416: 
1.346     albertel 6417: .LC_menubuttons_inline_text {
                   6418:   color: $font;
1.698     harmsja  6419:   font-size: 90%;
1.701     harmsja  6420:   padding-left:3px;
1.346     albertel 6421: }
                   6422: 
1.934     droeschl 6423: .LC_menubuttons_inline_text img{
                   6424:   vertical-align: middle;
                   6425: }
                   6426: 
1.1051    www      6427: li.LC_menubuttons_inline_text img {
1.951     onken    6428:   cursor:pointer;
1.1002    droeschl 6429:   text-decoration: none;
1.951     onken    6430: }
                   6431: 
1.526     www      6432: .LC_menubuttons_link {
                   6433:   text-decoration: none;
                   6434: }
1.795     www      6435: 
1.522     albertel 6436: .LC_menubuttons_category {
1.521     www      6437:   color: $font;
1.526     www      6438:   background: $pgbg;
1.521     www      6439:   font-size: larger;
                   6440:   font-weight: bold;
                   6441: }
                   6442: 
1.346     albertel 6443: td.LC_menubuttons_text {
1.911     bisitz   6444:   color: $font;
1.346     albertel 6445: }
1.706     harmsja  6446: 
1.346     albertel 6447: .LC_current_location {
                   6448:   background: $tabbg;
                   6449: }
1.795     www      6450: 
1.1075.2.134  raeburn  6451: td.LC_zero_height {
                   6452:   line-height: 0;
                   6453:   cellpadding: 0;
                   6454: }
                   6455: 
1.938     bisitz   6456: table.LC_data_table {
1.347     albertel 6457:   border: 1px solid #000000;
1.402     albertel 6458:   border-collapse: separate;
1.426     albertel 6459:   border-spacing: 1px;
1.610     albertel 6460:   background: $pgbg;
1.347     albertel 6461: }
1.795     www      6462: 
1.422     albertel 6463: .LC_data_table_dense {
                   6464:   font-size: small;
                   6465: }
1.795     www      6466: 
1.507     raeburn  6467: table.LC_nested_outer {
                   6468:   border: 1px solid #000000;
1.589     raeburn  6469:   border-collapse: collapse;
1.803     bisitz   6470:   border-spacing: 0;
1.507     raeburn  6471:   width: 100%;
                   6472: }
1.795     www      6473: 
1.879     raeburn  6474: table.LC_innerpickbox,
1.507     raeburn  6475: table.LC_nested {
1.803     bisitz   6476:   border: none;
1.589     raeburn  6477:   border-collapse: collapse;
1.803     bisitz   6478:   border-spacing: 0;
1.507     raeburn  6479:   width: 100%;
                   6480: }
1.795     www      6481: 
1.911     bisitz   6482: table.LC_data_table tr th,
                   6483: table.LC_calendar tr th,
1.879     raeburn  6484: table.LC_prior_tries tr th,
                   6485: table.LC_innerpickbox tr th {
1.349     albertel 6486:   font-weight: bold;
                   6487:   background-color: $data_table_head;
1.801     tempelho 6488:   color:$fontmenu;
1.701     harmsja  6489:   font-size:90%;
1.347     albertel 6490: }
1.795     www      6491: 
1.879     raeburn  6492: table.LC_innerpickbox tr th,
                   6493: table.LC_innerpickbox tr td {
                   6494:   vertical-align: top;
                   6495: }
                   6496: 
1.711     raeburn  6497: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6498:   background-color: #CCCCCC;
1.711     raeburn  6499:   font-weight: bold;
                   6500:   text-align: left;
                   6501: }
1.795     www      6502: 
1.912     bisitz   6503: table.LC_data_table tr.LC_odd_row > td {
                   6504:   background-color: $data_table_light;
                   6505:   padding: 2px;
                   6506:   vertical-align: top;
                   6507: }
                   6508: 
1.809     bisitz   6509: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6510:   background-color: $data_table_light;
1.912     bisitz   6511:   vertical-align: top;
                   6512: }
                   6513: 
                   6514: table.LC_data_table tr.LC_even_row > td {
                   6515:   background-color: $data_table_dark;
1.425     albertel 6516:   padding: 2px;
1.900     bisitz   6517:   vertical-align: top;
1.347     albertel 6518: }
1.795     www      6519: 
1.809     bisitz   6520: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6521:   background-color: $data_table_dark;
1.900     bisitz   6522:   vertical-align: top;
1.347     albertel 6523: }
1.795     www      6524: 
1.425     albertel 6525: table.LC_data_table tr.LC_data_table_highlight td {
                   6526:   background-color: $data_table_darker;
                   6527: }
1.795     www      6528: 
1.639     raeburn  6529: table.LC_data_table tr td.LC_leftcol_header {
                   6530:   background-color: $data_table_head;
                   6531:   font-weight: bold;
                   6532: }
1.795     www      6533: 
1.451     albertel 6534: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6535: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6536:   font-weight: bold;
                   6537:   font-style: italic;
                   6538:   text-align: center;
                   6539:   padding: 8px;
1.347     albertel 6540: }
1.795     www      6541: 
1.1075.2.30  raeburn  6542: table.LC_data_table tr.LC_empty_row td,
                   6543: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6544:   background-color: $sidebg;
                   6545: }
                   6546: 
                   6547: table.LC_nested tr.LC_empty_row td {
                   6548:   background-color: #FFFFFF;
                   6549: }
                   6550: 
1.890     droeschl 6551: table.LC_caption {
                   6552: }
                   6553: 
1.507     raeburn  6554: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6555:   padding: 4ex
                   6556: }
1.795     www      6557: 
1.507     raeburn  6558: table.LC_nested_outer tr th {
                   6559:   font-weight: bold;
1.801     tempelho 6560:   color:$fontmenu;
1.507     raeburn  6561:   background-color: $data_table_head;
1.701     harmsja  6562:   font-size: small;
1.507     raeburn  6563:   border-bottom: 1px solid #000000;
                   6564: }
1.795     www      6565: 
1.507     raeburn  6566: table.LC_nested_outer tr td.LC_subheader {
                   6567:   background-color: $data_table_head;
                   6568:   font-weight: bold;
                   6569:   font-size: small;
                   6570:   border-bottom: 1px solid #000000;
                   6571:   text-align: right;
1.451     albertel 6572: }
1.795     www      6573: 
1.507     raeburn  6574: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6575:   background-color: #CCCCCC;
1.451     albertel 6576:   font-weight: bold;
                   6577:   font-size: small;
1.507     raeburn  6578:   text-align: center;
                   6579: }
1.795     www      6580: 
1.589     raeburn  6581: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6582: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6583:   text-align: left;
1.451     albertel 6584: }
1.795     www      6585: 
1.507     raeburn  6586: table.LC_nested td {
1.735     bisitz   6587:   background-color: #FFFFFF;
1.451     albertel 6588:   font-size: small;
1.507     raeburn  6589: }
1.795     www      6590: 
1.507     raeburn  6591: table.LC_nested_outer tr th.LC_right_item,
                   6592: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6593: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6594: table.LC_nested tr td.LC_right_item {
1.451     albertel 6595:   text-align: right;
                   6596: }
                   6597: 
1.507     raeburn  6598: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6599:   background-color: #EEEEEE;
1.451     albertel 6600: }
                   6601: 
1.473     raeburn  6602: table.LC_createuser {
                   6603: }
                   6604: 
                   6605: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6606:   font-size: small;
1.473     raeburn  6607: }
                   6608: 
                   6609: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6610:   background-color: #CCCCCC;
1.473     raeburn  6611:   font-weight: bold;
                   6612:   text-align: center;
                   6613: }
                   6614: 
1.349     albertel 6615: table.LC_calendar {
                   6616:   border: 1px solid #000000;
                   6617:   border-collapse: collapse;
1.917     raeburn  6618:   width: 98%;
1.349     albertel 6619: }
1.795     www      6620: 
1.349     albertel 6621: table.LC_calendar_pickdate {
                   6622:   font-size: xx-small;
                   6623: }
1.795     www      6624: 
1.349     albertel 6625: table.LC_calendar tr td {
                   6626:   border: 1px solid #000000;
                   6627:   vertical-align: top;
1.917     raeburn  6628:   width: 14%;
1.349     albertel 6629: }
1.795     www      6630: 
1.349     albertel 6631: table.LC_calendar tr td.LC_calendar_day_empty {
                   6632:   background-color: $data_table_dark;
                   6633: }
1.795     www      6634: 
1.779     bisitz   6635: table.LC_calendar tr td.LC_calendar_day_current {
                   6636:   background-color: $data_table_highlight;
1.777     tempelho 6637: }
1.795     www      6638: 
1.938     bisitz   6639: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6640:   background-color: $mail_new;
                   6641: }
1.795     www      6642: 
1.938     bisitz   6643: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6644:   background-color: $mail_new_hover;
                   6645: }
1.795     www      6646: 
1.938     bisitz   6647: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6648:   background-color: $mail_read;
                   6649: }
1.795     www      6650: 
1.938     bisitz   6651: /*
                   6652: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6653:   background-color: $mail_read_hover;
                   6654: }
1.938     bisitz   6655: */
1.795     www      6656: 
1.938     bisitz   6657: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6658:   background-color: $mail_replied;
                   6659: }
1.795     www      6660: 
1.938     bisitz   6661: /*
                   6662: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6663:   background-color: $mail_replied_hover;
                   6664: }
1.938     bisitz   6665: */
1.795     www      6666: 
1.938     bisitz   6667: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6668:   background-color: $mail_other;
                   6669: }
1.795     www      6670: 
1.938     bisitz   6671: /*
                   6672: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6673:   background-color: $mail_other_hover;
                   6674: }
1.938     bisitz   6675: */
1.494     raeburn  6676: 
1.777     tempelho 6677: table.LC_data_table tr > td.LC_browser_file,
                   6678: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6679:   background: #AAEE77;
1.389     albertel 6680: }
1.795     www      6681: 
1.777     tempelho 6682: table.LC_data_table tr > td.LC_browser_file_locked,
                   6683: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6684:   background: #FFAA99;
1.387     albertel 6685: }
1.795     www      6686: 
1.777     tempelho 6687: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6688:   background: #888888;
1.779     bisitz   6689: }
1.795     www      6690: 
1.777     tempelho 6691: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6692: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6693:   background: #F8F866;
1.777     tempelho 6694: }
1.795     www      6695: 
1.696     bisitz   6696: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6697:   background: #E0E8FF;
1.387     albertel 6698: }
1.696     bisitz   6699: 
1.707     bisitz   6700: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6701:   /* background: #77FF77; */
1.707     bisitz   6702: }
1.795     www      6703: 
1.707     bisitz   6704: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6705:   border-right: 8px solid #FFFF77;
1.707     bisitz   6706: }
1.795     www      6707: 
1.707     bisitz   6708: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6709:   border-right: 8px solid #FFAA77;
1.707     bisitz   6710: }
1.795     www      6711: 
1.707     bisitz   6712: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6713:   border-right: 8px solid #FF7777;
1.707     bisitz   6714: }
1.795     www      6715: 
1.707     bisitz   6716: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6717:   border-right: 8px solid #AAFF77;
1.707     bisitz   6718: }
1.795     www      6719: 
1.707     bisitz   6720: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6721:   border-right: 8px solid #11CC55;
1.707     bisitz   6722: }
                   6723: 
1.388     albertel 6724: span.LC_current_location {
1.701     harmsja  6725:   font-size:larger;
1.388     albertel 6726:   background: $pgbg;
                   6727: }
1.387     albertel 6728: 
1.1029    www      6729: span.LC_current_nav_location {
                   6730:   font-weight:bold;
                   6731:   background: $sidebg;
                   6732: }
                   6733: 
1.395     albertel 6734: span.LC_parm_menu_item {
                   6735:   font-size: larger;
                   6736: }
1.795     www      6737: 
1.395     albertel 6738: span.LC_parm_scope_all {
                   6739:   color: red;
                   6740: }
1.795     www      6741: 
1.395     albertel 6742: span.LC_parm_scope_folder {
                   6743:   color: green;
                   6744: }
1.795     www      6745: 
1.395     albertel 6746: span.LC_parm_scope_resource {
                   6747:   color: orange;
                   6748: }
1.795     www      6749: 
1.395     albertel 6750: span.LC_parm_part {
                   6751:   color: blue;
                   6752: }
1.795     www      6753: 
1.911     bisitz   6754: span.LC_parm_folder,
                   6755: span.LC_parm_symb {
1.395     albertel 6756:   font-size: x-small;
                   6757:   font-family: $mono;
                   6758:   color: #AAAAAA;
                   6759: }
                   6760: 
1.977     bisitz   6761: ul.LC_parm_parmlist li {
                   6762:   display: inline-block;
                   6763:   padding: 0.3em 0.8em;
                   6764:   vertical-align: top;
                   6765:   width: 150px;
                   6766:   border-top:1px solid $lg_border_color;
                   6767: }
                   6768: 
1.795     www      6769: td.LC_parm_overview_level_menu,
                   6770: td.LC_parm_overview_map_menu,
                   6771: td.LC_parm_overview_parm_selectors,
                   6772: td.LC_parm_overview_restrictions  {
1.396     albertel 6773:   border: 1px solid black;
                   6774:   border-collapse: collapse;
                   6775: }
1.795     www      6776: 
1.396     albertel 6777: table.LC_parm_overview_restrictions td {
                   6778:   border-width: 1px 4px 1px 4px;
                   6779:   border-style: solid;
                   6780:   border-color: $pgbg;
                   6781:   text-align: center;
                   6782: }
1.795     www      6783: 
1.396     albertel 6784: table.LC_parm_overview_restrictions th {
                   6785:   background: $tabbg;
                   6786:   border-width: 1px 4px 1px 4px;
                   6787:   border-style: solid;
                   6788:   border-color: $pgbg;
                   6789: }
1.795     www      6790: 
1.398     albertel 6791: table#LC_helpmenu {
1.803     bisitz   6792:   border: none;
1.398     albertel 6793:   height: 55px;
1.803     bisitz   6794:   border-spacing: 0;
1.398     albertel 6795: }
                   6796: 
                   6797: table#LC_helpmenu fieldset legend {
                   6798:   font-size: larger;
                   6799: }
1.795     www      6800: 
1.397     albertel 6801: table#LC_helpmenu_links {
                   6802:   width: 100%;
                   6803:   border: 1px solid black;
                   6804:   background: $pgbg;
1.803     bisitz   6805:   padding: 0;
1.397     albertel 6806:   border-spacing: 1px;
                   6807: }
1.795     www      6808: 
1.397     albertel 6809: table#LC_helpmenu_links tr td {
                   6810:   padding: 1px;
                   6811:   background: $tabbg;
1.399     albertel 6812:   text-align: center;
                   6813:   font-weight: bold;
1.397     albertel 6814: }
1.396     albertel 6815: 
1.795     www      6816: table#LC_helpmenu_links a:link,
                   6817: table#LC_helpmenu_links a:visited,
1.397     albertel 6818: table#LC_helpmenu_links a:active {
                   6819:   text-decoration: none;
                   6820:   color: $font;
                   6821: }
1.795     www      6822: 
1.397     albertel 6823: table#LC_helpmenu_links a:hover {
                   6824:   text-decoration: underline;
                   6825:   color: $vlink;
                   6826: }
1.396     albertel 6827: 
1.417     albertel 6828: .LC_chrt_popup_exists {
                   6829:   border: 1px solid #339933;
                   6830:   margin: -1px;
                   6831: }
1.795     www      6832: 
1.417     albertel 6833: .LC_chrt_popup_up {
                   6834:   border: 1px solid yellow;
                   6835:   margin: -1px;
                   6836: }
1.795     www      6837: 
1.417     albertel 6838: .LC_chrt_popup {
                   6839:   border: 1px solid #8888FF;
                   6840:   background: #CCCCFF;
                   6841: }
1.795     www      6842: 
1.421     albertel 6843: table.LC_pick_box {
                   6844:   border-collapse: separate;
                   6845:   background: white;
                   6846:   border: 1px solid black;
                   6847:   border-spacing: 1px;
                   6848: }
1.795     www      6849: 
1.421     albertel 6850: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6851:   background: $sidebg;
1.421     albertel 6852:   font-weight: bold;
1.900     bisitz   6853:   text-align: left;
1.740     bisitz   6854:   vertical-align: top;
1.421     albertel 6855:   width: 184px;
                   6856:   padding: 8px;
                   6857: }
1.795     www      6858: 
1.579     raeburn  6859: table.LC_pick_box td.LC_pick_box_value {
                   6860:   text-align: left;
                   6861:   padding: 8px;
                   6862: }
1.795     www      6863: 
1.579     raeburn  6864: table.LC_pick_box td.LC_pick_box_select {
                   6865:   text-align: left;
                   6866:   padding: 8px;
                   6867: }
1.795     www      6868: 
1.424     albertel 6869: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6870:   padding: 0;
1.421     albertel 6871:   height: 1px;
                   6872:   background: black;
                   6873: }
1.795     www      6874: 
1.421     albertel 6875: table.LC_pick_box td.LC_pick_box_submit {
                   6876:   text-align: right;
                   6877: }
1.795     www      6878: 
1.579     raeburn  6879: table.LC_pick_box td.LC_evenrow_value {
                   6880:   text-align: left;
                   6881:   padding: 8px;
                   6882:   background-color: $data_table_light;
                   6883: }
1.795     www      6884: 
1.579     raeburn  6885: table.LC_pick_box td.LC_oddrow_value {
                   6886:   text-align: left;
                   6887:   padding: 8px;
                   6888:   background-color: $data_table_light;
                   6889: }
1.795     www      6890: 
1.579     raeburn  6891: span.LC_helpform_receipt_cat {
                   6892:   font-weight: bold;
                   6893: }
1.795     www      6894: 
1.424     albertel 6895: table.LC_group_priv_box {
                   6896:   background: white;
                   6897:   border: 1px solid black;
                   6898:   border-spacing: 1px;
                   6899: }
1.795     www      6900: 
1.424     albertel 6901: table.LC_group_priv_box td.LC_pick_box_title {
                   6902:   background: $tabbg;
                   6903:   font-weight: bold;
                   6904:   text-align: right;
                   6905:   width: 184px;
                   6906: }
1.795     www      6907: 
1.424     albertel 6908: table.LC_group_priv_box td.LC_groups_fixed {
                   6909:   background: $data_table_light;
                   6910:   text-align: center;
                   6911: }
1.795     www      6912: 
1.424     albertel 6913: table.LC_group_priv_box td.LC_groups_optional {
                   6914:   background: $data_table_dark;
                   6915:   text-align: center;
                   6916: }
1.795     www      6917: 
1.424     albertel 6918: table.LC_group_priv_box td.LC_groups_functionality {
                   6919:   background: $data_table_darker;
                   6920:   text-align: center;
                   6921:   font-weight: bold;
                   6922: }
1.795     www      6923: 
1.424     albertel 6924: table.LC_group_priv td {
                   6925:   text-align: left;
1.803     bisitz   6926:   padding: 0;
1.424     albertel 6927: }
                   6928: 
                   6929: .LC_navbuttons {
                   6930:   margin: 2ex 0ex 2ex 0ex;
                   6931: }
1.795     www      6932: 
1.423     albertel 6933: .LC_topic_bar {
                   6934:   font-weight: bold;
                   6935:   background: $tabbg;
1.918     wenzelju 6936:   margin: 1em 0em 1em 2em;
1.805     bisitz   6937:   padding: 3px;
1.918     wenzelju 6938:   font-size: 1.2em;
1.423     albertel 6939: }
1.795     www      6940: 
1.423     albertel 6941: .LC_topic_bar span {
1.918     wenzelju 6942:   left: 0.5em;
                   6943:   position: absolute;
1.423     albertel 6944:   vertical-align: middle;
1.918     wenzelju 6945:   font-size: 1.2em;
1.423     albertel 6946: }
1.795     www      6947: 
1.423     albertel 6948: table.LC_course_group_status {
                   6949:   margin: 20px;
                   6950: }
1.795     www      6951: 
1.423     albertel 6952: table.LC_status_selector td {
                   6953:   vertical-align: top;
                   6954:   text-align: center;
1.424     albertel 6955:   padding: 4px;
                   6956: }
1.795     www      6957: 
1.599     albertel 6958: div.LC_feedback_link {
1.616     albertel 6959:   clear: both;
1.829     kalberla 6960:   background: $sidebg;
1.779     bisitz   6961:   width: 100%;
1.829     kalberla 6962:   padding-bottom: 10px;
                   6963:   border: 1px $tabbg solid;
1.833     kalberla 6964:   height: 22px;
                   6965:   line-height: 22px;
                   6966:   padding-top: 5px;
                   6967: }
                   6968: 
                   6969: div.LC_feedback_link img {
                   6970:   height: 22px;
1.867     kalberla 6971:   vertical-align:middle;
1.829     kalberla 6972: }
                   6973: 
1.911     bisitz   6974: div.LC_feedback_link a {
1.829     kalberla 6975:   text-decoration: none;
1.489     raeburn  6976: }
1.795     www      6977: 
1.867     kalberla 6978: div.LC_comblock {
1.911     bisitz   6979:   display:inline;
1.867     kalberla 6980:   color:$font;
                   6981:   font-size:90%;
                   6982: }
                   6983: 
                   6984: div.LC_feedback_link div.LC_comblock {
                   6985:   padding-left:5px;
                   6986: }
                   6987: 
                   6988: div.LC_feedback_link div.LC_comblock a {
                   6989:   color:$font;
                   6990: }
                   6991: 
1.489     raeburn  6992: span.LC_feedback_link {
1.858     bisitz   6993:   /* background: $feedback_link_bg; */
1.599     albertel 6994:   font-size: larger;
                   6995: }
1.795     www      6996: 
1.599     albertel 6997: span.LC_message_link {
1.858     bisitz   6998:   /* background: $feedback_link_bg; */
1.599     albertel 6999:   font-size: larger;
                   7000:   position: absolute;
                   7001:   right: 1em;
1.489     raeburn  7002: }
1.421     albertel 7003: 
1.515     albertel 7004: table.LC_prior_tries {
1.524     albertel 7005:   border: 1px solid #000000;
                   7006:   border-collapse: separate;
                   7007:   border-spacing: 1px;
1.515     albertel 7008: }
1.523     albertel 7009: 
1.515     albertel 7010: table.LC_prior_tries td {
1.524     albertel 7011:   padding: 2px;
1.515     albertel 7012: }
1.523     albertel 7013: 
                   7014: .LC_answer_correct {
1.795     www      7015:   background: lightgreen;
                   7016:   color: darkgreen;
                   7017:   padding: 6px;
1.523     albertel 7018: }
1.795     www      7019: 
1.523     albertel 7020: .LC_answer_charged_try {
1.797     www      7021:   background: #FFAAAA;
1.795     www      7022:   color: darkred;
                   7023:   padding: 6px;
1.523     albertel 7024: }
1.795     www      7025: 
1.779     bisitz   7026: .LC_answer_not_charged_try,
1.523     albertel 7027: .LC_answer_no_grade,
                   7028: .LC_answer_late {
1.795     www      7029:   background: lightyellow;
1.523     albertel 7030:   color: black;
1.795     www      7031:   padding: 6px;
1.523     albertel 7032: }
1.795     www      7033: 
1.523     albertel 7034: .LC_answer_previous {
1.795     www      7035:   background: lightblue;
                   7036:   color: darkblue;
                   7037:   padding: 6px;
1.523     albertel 7038: }
1.795     www      7039: 
1.779     bisitz   7040: .LC_answer_no_message {
1.777     tempelho 7041:   background: #FFFFFF;
                   7042:   color: black;
1.795     www      7043:   padding: 6px;
1.779     bisitz   7044: }
1.795     www      7045: 
1.1075.2.140  raeburn  7046: .LC_answer_unknown,
                   7047: .LC_answer_warning {
1.779     bisitz   7048:   background: orange;
                   7049:   color: black;
1.795     www      7050:   padding: 6px;
1.777     tempelho 7051: }
1.795     www      7052: 
1.529     albertel 7053: span.LC_prior_numerical,
                   7054: span.LC_prior_string,
                   7055: span.LC_prior_custom,
                   7056: span.LC_prior_reaction,
                   7057: span.LC_prior_math {
1.925     bisitz   7058:   font-family: $mono;
1.523     albertel 7059:   white-space: pre;
                   7060: }
                   7061: 
1.525     albertel 7062: span.LC_prior_string {
1.925     bisitz   7063:   font-family: $mono;
1.525     albertel 7064:   white-space: pre;
                   7065: }
                   7066: 
1.523     albertel 7067: table.LC_prior_option {
                   7068:   width: 100%;
                   7069:   border-collapse: collapse;
                   7070: }
1.795     www      7071: 
1.911     bisitz   7072: table.LC_prior_rank,
1.795     www      7073: table.LC_prior_match {
1.528     albertel 7074:   border-collapse: collapse;
                   7075: }
1.795     www      7076: 
1.528     albertel 7077: table.LC_prior_option tr td,
                   7078: table.LC_prior_rank tr td,
                   7079: table.LC_prior_match tr td {
1.524     albertel 7080:   border: 1px solid #000000;
1.515     albertel 7081: }
                   7082: 
1.855     bisitz   7083: .LC_nobreak {
1.544     albertel 7084:   white-space: nowrap;
1.519     raeburn  7085: }
                   7086: 
1.576     raeburn  7087: span.LC_cusr_emph {
                   7088:   font-style: italic;
                   7089: }
                   7090: 
1.633     raeburn  7091: span.LC_cusr_subheading {
                   7092:   font-weight: normal;
                   7093:   font-size: 85%;
                   7094: }
                   7095: 
1.861     bisitz   7096: div.LC_docs_entry_move {
1.859     bisitz   7097:   border: 1px solid #BBBBBB;
1.545     albertel 7098:   background: #DDDDDD;
1.861     bisitz   7099:   width: 22px;
1.859     bisitz   7100:   padding: 1px;
                   7101:   margin: 0;
1.545     albertel 7102: }
                   7103: 
1.861     bisitz   7104: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7105: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7106:   font-size: x-small;
                   7107: }
1.795     www      7108: 
1.861     bisitz   7109: .LC_docs_entry_parameter {
                   7110:   white-space: nowrap;
                   7111: }
                   7112: 
1.544     albertel 7113: .LC_docs_copy {
1.545     albertel 7114:   color: #000099;
1.544     albertel 7115: }
1.795     www      7116: 
1.544     albertel 7117: .LC_docs_cut {
1.545     albertel 7118:   color: #550044;
1.544     albertel 7119: }
1.795     www      7120: 
1.544     albertel 7121: .LC_docs_rename {
1.545     albertel 7122:   color: #009900;
1.544     albertel 7123: }
1.795     www      7124: 
1.544     albertel 7125: .LC_docs_remove {
1.545     albertel 7126:   color: #990000;
                   7127: }
                   7128: 
1.1075.2.134  raeburn  7129: .LC_domprefs_email,
1.547     albertel 7130: .LC_docs_reinit_warn,
                   7131: .LC_docs_ext_edit {
                   7132:   font-size: x-small;
                   7133: }
                   7134: 
1.545     albertel 7135: table.LC_docs_adddocs td,
                   7136: table.LC_docs_adddocs th {
                   7137:   border: 1px solid #BBBBBB;
                   7138:   padding: 4px;
                   7139:   background: #DDDDDD;
1.543     albertel 7140: }
                   7141: 
1.584     albertel 7142: table.LC_sty_begin {
                   7143:   background: #BBFFBB;
                   7144: }
1.795     www      7145: 
1.584     albertel 7146: table.LC_sty_end {
                   7147:   background: #FFBBBB;
                   7148: }
                   7149: 
1.589     raeburn  7150: table.LC_double_column {
1.803     bisitz   7151:   border-width: 0;
1.589     raeburn  7152:   border-collapse: collapse;
                   7153:   width: 100%;
                   7154:   padding: 2px;
                   7155: }
                   7156: 
                   7157: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7158:   top: 2px;
1.589     raeburn  7159:   left: 2px;
                   7160:   width: 47%;
                   7161:   vertical-align: top;
                   7162: }
                   7163: 
                   7164: table.LC_double_column tr td.LC_right_col {
                   7165:   top: 2px;
1.779     bisitz   7166:   right: 2px;
1.589     raeburn  7167:   width: 47%;
                   7168:   vertical-align: top;
                   7169: }
                   7170: 
1.591     raeburn  7171: div.LC_left_float {
                   7172:   float: left;
                   7173:   padding-right: 5%;
1.597     albertel 7174:   padding-bottom: 4px;
1.591     raeburn  7175: }
                   7176: 
                   7177: div.LC_clear_float_header {
1.597     albertel 7178:   padding-bottom: 2px;
1.591     raeburn  7179: }
                   7180: 
                   7181: div.LC_clear_float_footer {
1.597     albertel 7182:   padding-top: 10px;
1.591     raeburn  7183:   clear: both;
                   7184: }
                   7185: 
1.597     albertel 7186: div.LC_grade_show_user {
1.941     bisitz   7187: /*  border-left: 5px solid $sidebg; */
                   7188:   border-top: 5px solid #000000;
                   7189:   margin: 50px 0 0 0;
1.936     bisitz   7190:   padding: 15px 0 5px 10px;
1.597     albertel 7191: }
1.795     www      7192: 
1.936     bisitz   7193: div.LC_grade_show_user_odd_row {
1.941     bisitz   7194: /*  border-left: 5px solid #000000; */
                   7195: }
                   7196: 
                   7197: div.LC_grade_show_user div.LC_Box {
                   7198:   margin-right: 50px;
1.597     albertel 7199: }
                   7200: 
                   7201: div.LC_grade_submissions,
                   7202: div.LC_grade_message_center,
1.936     bisitz   7203: div.LC_grade_info_links {
1.597     albertel 7204:   margin: 5px;
                   7205:   width: 99%;
                   7206:   background: #FFFFFF;
                   7207: }
1.795     www      7208: 
1.597     albertel 7209: div.LC_grade_submissions_header,
1.936     bisitz   7210: div.LC_grade_message_center_header {
1.705     tempelho 7211:   font-weight: bold;
                   7212:   font-size: large;
1.597     albertel 7213: }
1.795     www      7214: 
1.597     albertel 7215: div.LC_grade_submissions_body,
1.936     bisitz   7216: div.LC_grade_message_center_body {
1.597     albertel 7217:   border: 1px solid black;
                   7218:   width: 99%;
                   7219:   background: #FFFFFF;
                   7220: }
1.795     www      7221: 
1.613     albertel 7222: table.LC_scantron_action {
                   7223:   width: 100%;
                   7224: }
1.795     www      7225: 
1.613     albertel 7226: table.LC_scantron_action tr th {
1.698     harmsja  7227:   font-weight:bold;
                   7228:   font-style:normal;
1.613     albertel 7229: }
1.795     www      7230: 
1.779     bisitz   7231: .LC_edit_problem_header,
1.614     albertel 7232: div.LC_edit_problem_footer {
1.705     tempelho 7233:   font-weight: normal;
                   7234:   font-size:  medium;
1.602     albertel 7235:   margin: 2px;
1.1060    bisitz   7236:   background-color: $sidebg;
1.600     albertel 7237: }
1.795     www      7238: 
1.600     albertel 7239: div.LC_edit_problem_header,
1.602     albertel 7240: div.LC_edit_problem_header div,
1.614     albertel 7241: div.LC_edit_problem_footer,
                   7242: div.LC_edit_problem_footer div,
1.602     albertel 7243: div.LC_edit_problem_editxml_header,
                   7244: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7245:   z-index: 100;
1.600     albertel 7246: }
1.795     www      7247: 
1.600     albertel 7248: div.LC_edit_problem_header_title {
1.705     tempelho 7249:   font-weight: bold;
                   7250:   font-size: larger;
1.602     albertel 7251:   background: $tabbg;
                   7252:   padding: 3px;
1.1060    bisitz   7253:   margin: 0 0 5px 0;
1.602     albertel 7254: }
1.795     www      7255: 
1.602     albertel 7256: table.LC_edit_problem_header_title {
                   7257:   width: 100%;
1.600     albertel 7258:   background: $tabbg;
1.602     albertel 7259: }
                   7260: 
1.1075.2.112  raeburn  7261: div.LC_edit_actionbar {
                   7262:     background-color: $sidebg;
                   7263:     margin: 0;
                   7264:     padding: 0;
                   7265:     line-height: 200%;
1.602     albertel 7266: }
1.795     www      7267: 
1.1075.2.112  raeburn  7268: div.LC_edit_actionbar div{
                   7269:     padding: 0;
                   7270:     margin: 0;
                   7271:     display: inline-block;
1.600     albertel 7272: }
1.795     www      7273: 
1.1075.2.34  raeburn  7274: .LC_edit_opt {
                   7275:   padding-left: 1em;
                   7276:   white-space: nowrap;
                   7277: }
                   7278: 
1.1075.2.57  raeburn  7279: .LC_edit_problem_latexhelper{
                   7280:     text-align: right;
                   7281: }
                   7282: 
                   7283: #LC_edit_problem_colorful div{
                   7284:     margin-left: 40px;
                   7285: }
                   7286: 
1.1075.2.112  raeburn  7287: #LC_edit_problem_codemirror div{
                   7288:     margin-left: 0px;
                   7289: }
                   7290: 
1.911     bisitz   7291: img.stift {
1.803     bisitz   7292:   border-width: 0;
                   7293:   vertical-align: middle;
1.677     riegler  7294: }
1.680     riegler  7295: 
1.923     bisitz   7296: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7297:   vertical-align: top;
1.777     tempelho 7298: }
1.795     www      7299: 
1.716     raeburn  7300: div.LC_createcourse {
1.911     bisitz   7301:   margin: 10px 10px 10px 10px;
1.716     raeburn  7302: }
                   7303: 
1.917     raeburn  7304: .LC_dccid {
1.1075.2.38  raeburn  7305:   float: right;
1.917     raeburn  7306:   margin: 0.2em 0 0 0;
                   7307:   padding: 0;
                   7308:   font-size: 90%;
                   7309:   display:none;
                   7310: }
                   7311: 
1.897     wenzelju 7312: ol.LC_primary_menu a:hover,
1.721     harmsja  7313: ol#LC_MenuBreadcrumbs a:hover,
                   7314: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7315: ul#LC_secondary_menu a:hover,
1.721     harmsja  7316: .LC_FormSectionClearButton input:hover
1.795     www      7317: ul.LC_TabContent   li:hover a {
1.952     onken    7318:   color:$button_hover;
1.911     bisitz   7319:   text-decoration:none;
1.693     droeschl 7320: }
                   7321: 
1.779     bisitz   7322: h1 {
1.911     bisitz   7323:   padding: 0;
                   7324:   line-height:130%;
1.693     droeschl 7325: }
1.698     harmsja  7326: 
1.911     bisitz   7327: h2,
                   7328: h3,
                   7329: h4,
                   7330: h5,
                   7331: h6 {
                   7332:   margin: 5px 0 5px 0;
                   7333:   padding: 0;
                   7334:   line-height:130%;
1.693     droeschl 7335: }
1.795     www      7336: 
                   7337: .LC_hcell {
1.911     bisitz   7338:   padding:3px 15px 3px 15px;
                   7339:   margin: 0;
                   7340:   background-color:$tabbg;
                   7341:   color:$fontmenu;
                   7342:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7343: }
1.795     www      7344: 
1.840     bisitz   7345: .LC_Box > .LC_hcell {
1.911     bisitz   7346:   margin: 0 -10px 10px -10px;
1.835     bisitz   7347: }
                   7348: 
1.721     harmsja  7349: .LC_noBorder {
1.911     bisitz   7350:   border: 0;
1.698     harmsja  7351: }
1.693     droeschl 7352: 
1.721     harmsja  7353: .LC_FormSectionClearButton input {
1.911     bisitz   7354:   background-color:transparent;
                   7355:   border: none;
                   7356:   cursor:pointer;
                   7357:   text-decoration:underline;
1.693     droeschl 7358: }
1.763     bisitz   7359: 
                   7360: .LC_help_open_topic {
1.911     bisitz   7361:   color: #FFFFFF;
                   7362:   background-color: #EEEEFF;
                   7363:   margin: 1px;
                   7364:   padding: 4px;
                   7365:   border: 1px solid #000033;
                   7366:   white-space: nowrap;
                   7367:   /* vertical-align: middle; */
1.759     neumanie 7368: }
1.693     droeschl 7369: 
1.911     bisitz   7370: dl,
                   7371: ul,
                   7372: div,
                   7373: fieldset {
                   7374:   margin: 10px 10px 10px 0;
                   7375:   /* overflow: hidden; */
1.693     droeschl 7376: }
1.795     www      7377: 
1.1075.2.90  raeburn  7378: article.geogebraweb div {
                   7379:     margin: 0;
                   7380: }
                   7381: 
1.838     bisitz   7382: fieldset > legend {
1.911     bisitz   7383:   font-weight: bold;
                   7384:   padding: 0 5px 0 5px;
1.838     bisitz   7385: }
                   7386: 
1.813     bisitz   7387: #LC_nav_bar {
1.911     bisitz   7388:   float: left;
1.995     raeburn  7389:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7390:   margin: 0 0 2px 0;
1.807     droeschl 7391: }
                   7392: 
1.916     droeschl 7393: #LC_realm {
                   7394:   margin: 0.2em 0 0 0;
                   7395:   padding: 0;
                   7396:   font-weight: bold;
                   7397:   text-align: center;
1.995     raeburn  7398:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7399: }
                   7400: 
1.911     bisitz   7401: #LC_nav_bar em {
                   7402:   font-weight: bold;
                   7403:   font-style: normal;
1.807     droeschl 7404: }
                   7405: 
1.897     wenzelju 7406: ol.LC_primary_menu {
1.934     droeschl 7407:   margin: 0;
1.1075.2.2  raeburn  7408:   padding: 0;
1.807     droeschl 7409: }
                   7410: 
1.852     droeschl 7411: ol#LC_PathBreadcrumbs {
1.911     bisitz   7412:   margin: 0;
1.693     droeschl 7413: }
                   7414: 
1.897     wenzelju 7415: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7416:   color: RGB(80, 80, 80);
                   7417:   vertical-align: middle;
                   7418:   text-align: left;
                   7419:   list-style: none;
1.1075.2.112  raeburn  7420:   position: relative;
1.1075.2.2  raeburn  7421:   float: left;
1.1075.2.112  raeburn  7422:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7423:   line-height: 1.5em;
1.1075.2.2  raeburn  7424: }
                   7425: 
1.1075.2.113  raeburn  7426: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7427: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7428:   display: block;
                   7429:   margin: 0;
                   7430:   padding: 0 5px 0 10px;
                   7431:   text-decoration: none;
                   7432: }
                   7433: 
1.1075.2.112  raeburn  7434: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7435:   display: inline-block;
                   7436:   width: 95%;
                   7437:   text-align: left;
                   7438: }
                   7439: 
                   7440: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7441:   display: inline-block;
                   7442:   width: 5%;
                   7443:   float: right;
                   7444:   text-align: right;
                   7445:   font-size: 70%;
                   7446: }
                   7447: 
                   7448: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7449:   display: none;
1.1075.2.112  raeburn  7450:   width: 15em;
1.1075.2.2  raeburn  7451:   background-color: $data_table_light;
1.1075.2.112  raeburn  7452:   position: absolute;
                   7453:   top: 100%;
                   7454: }
                   7455: 
                   7456: ol.LC_primary_menu ul ul {
                   7457:   left: 100%;
                   7458:   top: 0;
1.1075.2.2  raeburn  7459: }
                   7460: 
1.1075.2.112  raeburn  7461: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7462:   display: block;
                   7463:   position: absolute;
                   7464:   margin: 0;
                   7465:   padding: 0;
1.1075.2.5  raeburn  7466:   z-index: 2;
1.1075.2.2  raeburn  7467: }
                   7468: 
                   7469: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7470: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7471:   font-size: 90%;
1.911     bisitz   7472:   vertical-align: top;
1.1075.2.2  raeburn  7473:   float: none;
1.1075.2.5  raeburn  7474:   border-left: 1px solid black;
                   7475:   border-right: 1px solid black;
1.1075.2.112  raeburn  7476: /* A dark bottom border to visualize different menu options;
                   7477: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7478:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7479: }
                   7480: 
1.1075.2.112  raeburn  7481: ol.LC_primary_menu li li p:hover {
                   7482:   color:$button_hover;
                   7483:   text-decoration:none;
                   7484:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7485: }
                   7486: 
                   7487: ol.LC_primary_menu li li a:hover {
                   7488:    color:$button_hover;
                   7489:    background-color:$data_table_dark;
1.693     droeschl 7490: }
                   7491: 
1.1075.2.112  raeburn  7492: /* Font-size equal to the size of the predecessors*/
                   7493: ol.LC_primary_menu li:hover li li {
                   7494:   font-size: 100%;
                   7495: }
                   7496: 
1.897     wenzelju 7497: ol.LC_primary_menu li img {
1.911     bisitz   7498:   vertical-align: bottom;
1.934     droeschl 7499:   height: 1.1em;
1.1075.2.3  raeburn  7500:   margin: 0.2em 0 0 0;
1.693     droeschl 7501: }
                   7502: 
1.897     wenzelju 7503: ol.LC_primary_menu a {
1.911     bisitz   7504:   color: RGB(80, 80, 80);
                   7505:   text-decoration: none;
1.693     droeschl 7506: }
1.795     www      7507: 
1.949     droeschl 7508: ol.LC_primary_menu a.LC_new_message {
                   7509:   font-weight:bold;
                   7510:   color: darkred;
                   7511: }
                   7512: 
1.975     raeburn  7513: ol.LC_docs_parameters {
                   7514:   margin-left: 0;
                   7515:   padding: 0;
                   7516:   list-style: none;
                   7517: }
                   7518: 
                   7519: ol.LC_docs_parameters li {
                   7520:   margin: 0;
                   7521:   padding-right: 20px;
                   7522:   display: inline;
                   7523: }
                   7524: 
1.976     raeburn  7525: ol.LC_docs_parameters li:before {
                   7526:   content: "\\002022 \\0020";
                   7527: }
                   7528: 
                   7529: li.LC_docs_parameters_title {
                   7530:   font-weight: bold;
                   7531: }
                   7532: 
                   7533: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7534:   content: "";
                   7535: }
                   7536: 
1.897     wenzelju 7537: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7538:   clear: right;
1.911     bisitz   7539:   color: $fontmenu;
                   7540:   background: $tabbg;
                   7541:   list-style: none;
                   7542:   padding: 0;
                   7543:   margin: 0;
                   7544:   width: 100%;
1.995     raeburn  7545:   text-align: left;
1.1075.2.4  raeburn  7546:   float: left;
1.808     droeschl 7547: }
                   7548: 
1.897     wenzelju 7549: ul#LC_secondary_menu li {
1.911     bisitz   7550:   font-weight: bold;
                   7551:   line-height: 1.8em;
                   7552:   border-right: 1px solid black;
1.1075.2.4  raeburn  7553:   float: left;
                   7554: }
                   7555: 
                   7556: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7557:   background-color: $data_table_light;
                   7558: }
                   7559: 
                   7560: ul#LC_secondary_menu li a {
                   7561:   padding: 0 0.8em;
                   7562: }
                   7563: 
                   7564: ul#LC_secondary_menu li ul {
                   7565:   display: none;
                   7566: }
                   7567: 
                   7568: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7569:   display: block;
                   7570:   position: absolute;
                   7571:   margin: 0;
                   7572:   padding: 0;
                   7573:   list-style:none;
                   7574:   float: none;
                   7575:   background-color: $data_table_light;
1.1075.2.5  raeburn  7576:   z-index: 2;
1.1075.2.10  raeburn  7577:   margin-left: -1px;
1.1075.2.4  raeburn  7578: }
                   7579: 
                   7580: ul#LC_secondary_menu li ul li {
                   7581:   font-size: 90%;
                   7582:   vertical-align: top;
                   7583:   border-left: 1px solid black;
                   7584:   border-right: 1px solid black;
1.1075.2.33  raeburn  7585:   background-color: $data_table_light;
1.1075.2.4  raeburn  7586:   list-style:none;
                   7587:   float: none;
                   7588: }
                   7589: 
                   7590: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7591:   background-color: $data_table_dark;
1.807     droeschl 7592: }
                   7593: 
1.847     tempelho 7594: ul.LC_TabContent {
1.911     bisitz   7595:   display:block;
                   7596:   background: $sidebg;
                   7597:   border-bottom: solid 1px $lg_border_color;
                   7598:   list-style:none;
1.1020    raeburn  7599:   margin: -1px -10px 0 -10px;
1.911     bisitz   7600:   padding: 0;
1.693     droeschl 7601: }
                   7602: 
1.795     www      7603: ul.LC_TabContent li,
                   7604: ul.LC_TabContentBigger li {
1.911     bisitz   7605:   float:left;
1.741     harmsja  7606: }
1.795     www      7607: 
1.897     wenzelju 7608: ul#LC_secondary_menu li a {
1.911     bisitz   7609:   color: $fontmenu;
                   7610:   text-decoration: none;
1.693     droeschl 7611: }
1.795     www      7612: 
1.721     harmsja  7613: ul.LC_TabContent {
1.952     onken    7614:   min-height:20px;
1.721     harmsja  7615: }
1.795     www      7616: 
                   7617: ul.LC_TabContent li {
1.911     bisitz   7618:   vertical-align:middle;
1.959     onken    7619:   padding: 0 16px 0 10px;
1.911     bisitz   7620:   background-color:$tabbg;
                   7621:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7622:   border-left: solid 1px $font;
1.721     harmsja  7623: }
1.795     www      7624: 
1.847     tempelho 7625: ul.LC_TabContent .right {
1.911     bisitz   7626:   float:right;
1.847     tempelho 7627: }
                   7628: 
1.911     bisitz   7629: ul.LC_TabContent li a,
                   7630: ul.LC_TabContent li {
                   7631:   color:rgb(47,47,47);
                   7632:   text-decoration:none;
                   7633:   font-size:95%;
                   7634:   font-weight:bold;
1.952     onken    7635:   min-height:20px;
                   7636: }
                   7637: 
1.959     onken    7638: ul.LC_TabContent li a:hover,
                   7639: ul.LC_TabContent li a:focus {
1.952     onken    7640:   color: $button_hover;
1.959     onken    7641:   background:none;
                   7642:   outline:none;
1.952     onken    7643: }
                   7644: 
                   7645: ul.LC_TabContent li:hover {
                   7646:   color: $button_hover;
                   7647:   cursor:pointer;
1.721     harmsja  7648: }
1.795     www      7649: 
1.911     bisitz   7650: ul.LC_TabContent li.active {
1.952     onken    7651:   color: $font;
1.911     bisitz   7652:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7653:   border-bottom:solid 1px #FFFFFF;
                   7654:   cursor: default;
1.744     ehlerst  7655: }
1.795     www      7656: 
1.959     onken    7657: ul.LC_TabContent li.active a {
                   7658:   color:$font;
                   7659:   background:#FFFFFF;
                   7660:   outline: none;
                   7661: }
1.1047    raeburn  7662: 
                   7663: ul.LC_TabContent li.goback {
                   7664:   float: left;
                   7665:   border-left: none;
                   7666: }
                   7667: 
1.870     tempelho 7668: #maincoursedoc {
1.911     bisitz   7669:   clear:both;
1.870     tempelho 7670: }
                   7671: 
                   7672: ul.LC_TabContentBigger {
1.911     bisitz   7673:   display:block;
                   7674:   list-style:none;
                   7675:   padding: 0;
1.870     tempelho 7676: }
                   7677: 
1.795     www      7678: ul.LC_TabContentBigger li {
1.911     bisitz   7679:   vertical-align:bottom;
                   7680:   height: 30px;
                   7681:   font-size:110%;
                   7682:   font-weight:bold;
                   7683:   color: #737373;
1.841     tempelho 7684: }
                   7685: 
1.957     onken    7686: ul.LC_TabContentBigger li.active {
                   7687:   position: relative;
                   7688:   top: 1px;
                   7689: }
                   7690: 
1.870     tempelho 7691: ul.LC_TabContentBigger li a {
1.911     bisitz   7692:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7693:   height: 30px;
                   7694:   line-height: 30px;
                   7695:   text-align: center;
                   7696:   display: block;
                   7697:   text-decoration: none;
1.958     onken    7698:   outline: none;  
1.741     harmsja  7699: }
1.795     www      7700: 
1.870     tempelho 7701: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7702:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7703:   color:$font;
1.744     ehlerst  7704: }
1.795     www      7705: 
1.870     tempelho 7706: ul.LC_TabContentBigger li b {
1.911     bisitz   7707:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7708:   display: block;
                   7709:   float: left;
                   7710:   padding: 0 30px;
1.957     onken    7711:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7712: }
                   7713: 
1.956     onken    7714: ul.LC_TabContentBigger li:hover b {
                   7715:   color:$button_hover;
                   7716: }
                   7717: 
1.870     tempelho 7718: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7719:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7720:   color:$font;
1.957     onken    7721:   border: 0;
1.741     harmsja  7722: }
1.693     droeschl 7723: 
1.870     tempelho 7724: 
1.862     bisitz   7725: ul.LC_CourseBreadcrumbs {
                   7726:   background: $sidebg;
1.1020    raeburn  7727:   height: 2em;
1.862     bisitz   7728:   padding-left: 10px;
1.1020    raeburn  7729:   margin: 0;
1.862     bisitz   7730:   list-style-position: inside;
                   7731: }
                   7732: 
1.911     bisitz   7733: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7734: ol#LC_PathBreadcrumbs {
1.911     bisitz   7735:   padding-left: 10px;
                   7736:   margin: 0;
1.933     droeschl 7737:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7738: }
                   7739: 
1.911     bisitz   7740: ol#LC_MenuBreadcrumbs li,
                   7741: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7742: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7743:   display: inline;
1.933     droeschl 7744:   white-space: normal;  
1.693     droeschl 7745: }
                   7746: 
1.823     bisitz   7747: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7748: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7749:   text-decoration: none;
                   7750:   font-size:90%;
1.693     droeschl 7751: }
1.795     www      7752: 
1.969     droeschl 7753: ol#LC_MenuBreadcrumbs h1 {
                   7754:   display: inline;
                   7755:   font-size: 90%;
                   7756:   line-height: 2.5em;
                   7757:   margin: 0;
                   7758:   padding: 0;
                   7759: }
                   7760: 
1.795     www      7761: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7762:   text-decoration:none;
                   7763:   font-size:100%;
                   7764:   font-weight:bold;
1.693     droeschl 7765: }
1.795     www      7766: 
1.840     bisitz   7767: .LC_Box {
1.911     bisitz   7768:   border: solid 1px $lg_border_color;
                   7769:   padding: 0 10px 10px 10px;
1.746     neumanie 7770: }
1.795     www      7771: 
1.1020    raeburn  7772: .LC_DocsBox {
                   7773:   border: solid 1px $lg_border_color;
                   7774:   padding: 0 0 10px 10px;
                   7775: }
                   7776: 
1.795     www      7777: .LC_AboutMe_Image {
1.911     bisitz   7778:   float:left;
                   7779:   margin-right:10px;
1.747     neumanie 7780: }
1.795     www      7781: 
                   7782: .LC_Clear_AboutMe_Image {
1.911     bisitz   7783:   clear:left;
1.747     neumanie 7784: }
1.795     www      7785: 
1.721     harmsja  7786: dl.LC_ListStyleClean dt {
1.911     bisitz   7787:   padding-right: 5px;
                   7788:   display: table-header-group;
1.693     droeschl 7789: }
                   7790: 
1.721     harmsja  7791: dl.LC_ListStyleClean dd {
1.911     bisitz   7792:   display: table-row;
1.693     droeschl 7793: }
                   7794: 
1.721     harmsja  7795: .LC_ListStyleClean,
                   7796: .LC_ListStyleSimple,
                   7797: .LC_ListStyleNormal,
1.795     www      7798: .LC_ListStyleSpecial {
1.911     bisitz   7799:   /* display:block; */
                   7800:   list-style-position: inside;
                   7801:   list-style-type: none;
                   7802:   overflow: hidden;
                   7803:   padding: 0;
1.693     droeschl 7804: }
                   7805: 
1.721     harmsja  7806: .LC_ListStyleSimple li,
                   7807: .LC_ListStyleSimple dd,
                   7808: .LC_ListStyleNormal li,
                   7809: .LC_ListStyleNormal dd,
                   7810: .LC_ListStyleSpecial li,
1.795     www      7811: .LC_ListStyleSpecial dd {
1.911     bisitz   7812:   margin: 0;
                   7813:   padding: 5px 5px 5px 10px;
                   7814:   clear: both;
1.693     droeschl 7815: }
                   7816: 
1.721     harmsja  7817: .LC_ListStyleClean li,
                   7818: .LC_ListStyleClean dd {
1.911     bisitz   7819:   padding-top: 0;
                   7820:   padding-bottom: 0;
1.693     droeschl 7821: }
                   7822: 
1.721     harmsja  7823: .LC_ListStyleSimple dd,
1.795     www      7824: .LC_ListStyleSimple li {
1.911     bisitz   7825:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7826: }
                   7827: 
1.721     harmsja  7828: .LC_ListStyleSpecial li,
                   7829: .LC_ListStyleSpecial dd {
1.911     bisitz   7830:   list-style-type: none;
                   7831:   background-color: RGB(220, 220, 220);
                   7832:   margin-bottom: 4px;
1.693     droeschl 7833: }
                   7834: 
1.721     harmsja  7835: table.LC_SimpleTable {
1.911     bisitz   7836:   margin:5px;
                   7837:   border:solid 1px $lg_border_color;
1.795     www      7838: }
1.693     droeschl 7839: 
1.721     harmsja  7840: table.LC_SimpleTable tr {
1.911     bisitz   7841:   padding: 0;
                   7842:   border:solid 1px $lg_border_color;
1.693     droeschl 7843: }
1.795     www      7844: 
                   7845: table.LC_SimpleTable thead {
1.911     bisitz   7846:   background:rgb(220,220,220);
1.693     droeschl 7847: }
                   7848: 
1.721     harmsja  7849: div.LC_columnSection {
1.911     bisitz   7850:   display: block;
                   7851:   clear: both;
                   7852:   overflow: hidden;
                   7853:   margin: 0;
1.693     droeschl 7854: }
                   7855: 
1.721     harmsja  7856: div.LC_columnSection>* {
1.911     bisitz   7857:   float: left;
                   7858:   margin: 10px 20px 10px 0;
                   7859:   overflow:hidden;
1.693     droeschl 7860: }
1.721     harmsja  7861: 
1.795     www      7862: table em {
1.911     bisitz   7863:   font-weight: bold;
                   7864:   font-style: normal;
1.748     schulted 7865: }
1.795     www      7866: 
1.779     bisitz   7867: table.LC_tableBrowseRes,
1.795     www      7868: table.LC_tableOfContent {
1.911     bisitz   7869:   border:none;
                   7870:   border-spacing: 1px;
                   7871:   padding: 3px;
                   7872:   background-color: #FFFFFF;
                   7873:   font-size: 90%;
1.753     droeschl 7874: }
1.789     droeschl 7875: 
1.911     bisitz   7876: table.LC_tableOfContent {
                   7877:   border-collapse: collapse;
1.789     droeschl 7878: }
                   7879: 
1.771     droeschl 7880: table.LC_tableBrowseRes a,
1.768     schulted 7881: table.LC_tableOfContent a {
1.911     bisitz   7882:   background-color: transparent;
                   7883:   text-decoration: none;
1.753     droeschl 7884: }
                   7885: 
1.795     www      7886: table.LC_tableOfContent img {
1.911     bisitz   7887:   border: none;
                   7888:   height: 1.3em;
                   7889:   vertical-align: text-bottom;
                   7890:   margin-right: 0.3em;
1.753     droeschl 7891: }
1.757     schulted 7892: 
1.795     www      7893: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7894:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7895: }
                   7896: 
1.795     www      7897: a#LC_content_toolbar_everything {
1.911     bisitz   7898:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7899: }
                   7900: 
1.795     www      7901: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7902:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7903: }
                   7904: 
1.795     www      7905: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7906:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7907: }
                   7908: 
1.795     www      7909: a#LC_content_toolbar_changefolder {
1.911     bisitz   7910:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7911: }
                   7912: 
1.795     www      7913: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7914:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7915: }
                   7916: 
1.1043    raeburn  7917: a#LC_content_toolbar_edittoplevel {
                   7918:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7919: }
                   7920: 
1.795     www      7921: ul#LC_toolbar li a:hover {
1.911     bisitz   7922:   background-position: bottom center;
1.757     schulted 7923: }
                   7924: 
1.795     www      7925: ul#LC_toolbar {
1.911     bisitz   7926:   padding: 0;
                   7927:   margin: 2px;
                   7928:   list-style:none;
                   7929:   position:relative;
                   7930:   background-color:white;
1.1075.2.9  raeburn  7931:   overflow: auto;
1.757     schulted 7932: }
                   7933: 
1.795     www      7934: ul#LC_toolbar li {
1.911     bisitz   7935:   border:1px solid white;
                   7936:   padding: 0;
                   7937:   margin: 0;
                   7938:   float: left;
                   7939:   display:inline;
                   7940:   vertical-align:middle;
1.1075.2.9  raeburn  7941:   white-space: nowrap;
1.911     bisitz   7942: }
1.757     schulted 7943: 
1.783     amueller 7944: 
1.795     www      7945: a.LC_toolbarItem {
1.911     bisitz   7946:   display:block;
                   7947:   padding: 0;
                   7948:   margin: 0;
                   7949:   height: 32px;
                   7950:   width: 32px;
                   7951:   color:white;
                   7952:   border: none;
                   7953:   background-repeat:no-repeat;
                   7954:   background-color:transparent;
1.757     schulted 7955: }
                   7956: 
1.915     droeschl 7957: ul.LC_funclist {
                   7958:     margin: 0;
                   7959:     padding: 0.5em 1em 0.5em 0;
                   7960: }
                   7961: 
1.933     droeschl 7962: ul.LC_funclist > li:first-child {
                   7963:     font-weight:bold; 
                   7964:     margin-left:0.8em;
                   7965: }
                   7966: 
1.915     droeschl 7967: ul.LC_funclist + ul.LC_funclist {
                   7968:     /* 
                   7969:        left border as a seperator if we have more than
                   7970:        one list 
                   7971:     */
                   7972:     border-left: 1px solid $sidebg;
                   7973:     /* 
                   7974:        this hides the left border behind the border of the 
                   7975:        outer box if element is wrapped to the next 'line' 
                   7976:     */
                   7977:     margin-left: -1px;
                   7978: }
                   7979: 
1.843     bisitz   7980: ul.LC_funclist li {
1.915     droeschl 7981:   display: inline;
1.782     bisitz   7982:   white-space: nowrap;
1.915     droeschl 7983:   margin: 0 0 0 25px;
                   7984:   line-height: 150%;
1.782     bisitz   7985: }
                   7986: 
1.974     wenzelju 7987: .LC_hidden {
                   7988:   display: none;
                   7989: }
                   7990: 
1.1030    www      7991: .LCmodal-overlay {
                   7992: 		position:fixed;
                   7993: 		top:0;
                   7994: 		right:0;
                   7995: 		bottom:0;
                   7996: 		left:0;
                   7997: 		height:100%;
                   7998: 		width:100%;
                   7999: 		margin:0;
                   8000: 		padding:0;
                   8001: 		background:#999;
                   8002: 		opacity:.75;
                   8003: 		filter: alpha(opacity=75);
                   8004: 		-moz-opacity: 0.75;
                   8005: 		z-index:101;
                   8006: }
                   8007: 
                   8008: * html .LCmodal-overlay {   
                   8009: 		position: absolute;
                   8010: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8011: }
                   8012: 
                   8013: .LCmodal-window {
                   8014: 		position:fixed;
                   8015: 		top:50%;
                   8016: 		left:50%;
                   8017: 		margin:0;
                   8018: 		padding:0;
                   8019: 		z-index:102;
                   8020: 	}
                   8021: 
                   8022: * html .LCmodal-window {
                   8023: 		position:absolute;
                   8024: }
                   8025: 
                   8026: .LCclose-window {
                   8027: 		position:absolute;
                   8028: 		width:32px;
                   8029: 		height:32px;
                   8030: 		right:8px;
                   8031: 		top:8px;
                   8032: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8033: 		text-indent:-99999px;
                   8034: 		overflow:hidden;
                   8035: 		cursor:pointer;
                   8036: }
                   8037: 
1.1075.2.158  raeburn  8038: .LCisDisabled {
                   8039:   cursor: not-allowed;
                   8040:   opacity: 0.5;
                   8041: }
                   8042: 
                   8043: a[aria-disabled="true"] {
                   8044:   color: currentColor;
                   8045:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8046:   pointer-events: none;
                   8047:   text-decoration: none;
                   8048: }
                   8049: 
1.1075.2.141  raeburn  8050: pre.LC_wordwrap {
                   8051:   white-space: pre-wrap;
                   8052:   white-space: -moz-pre-wrap;
                   8053:   white-space: -pre-wrap;
                   8054:   white-space: -o-pre-wrap;
                   8055:   word-wrap: break-word;
                   8056: }
                   8057: 
1.1075.2.17  raeburn  8058: /*
                   8059:   styles used by TTH when "Default set of options to pass to tth/m
                   8060:   when converting TeX" in course settings has been set
                   8061: 
                   8062:   option passed: -t
                   8063: 
                   8064: */
                   8065: 
                   8066: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8067: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8068: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8069: td div.norm {line-height:normal;}
                   8070: 
                   8071: /*
                   8072:   option passed -y3
                   8073: */
                   8074: 
                   8075: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8076: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8077: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8078: 
1.1075.2.121  raeburn  8079: #LC_minitab_header {
                   8080:   float:left;
                   8081:   width:100%;
                   8082:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8083:   font-size:93%;
                   8084:   line-height:normal;
                   8085:   margin: 0.5em 0 0.5em 0;
                   8086: }
                   8087: #LC_minitab_header ul {
                   8088:   margin:0;
                   8089:   padding:10px 10px 0;
                   8090:   list-style:none;
                   8091: }
                   8092: #LC_minitab_header li {
                   8093:   float:left;
                   8094:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8095:   margin:0;
                   8096:   padding:0 0 0 9px;
                   8097: }
                   8098: #LC_minitab_header a {
                   8099:   display:block;
                   8100:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8101:   padding:5px 15px 4px 6px;
                   8102: }
                   8103: #LC_minitab_header #LC_current_minitab {
                   8104:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8105: }
                   8106: #LC_minitab_header #LC_current_minitab a {
                   8107:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8108:   padding-bottom:5px;
                   8109: }
                   8110: 
                   8111: 
1.343     albertel 8112: END
                   8113: }
                   8114: 
1.306     albertel 8115: =pod
                   8116: 
                   8117: =item * &headtag()
                   8118: 
                   8119: Returns a uniform footer for LON-CAPA web pages.
                   8120: 
1.307     albertel 8121: Inputs: $title - optional title for the head
                   8122:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8123:         $args - optional arguments
1.319     albertel 8124:             force_register - if is true call registerurl so the remote is 
                   8125:                              informed
1.415     albertel 8126:             redirect       -> array ref of
                   8127:                                    1- seconds before redirect occurs
                   8128:                                    2- url to redirect to
                   8129:                                    3- whether the side effect should occur
1.315     albertel 8130:                            (side effect of setting 
                   8131:                                $env{'internal.head.redirect'} to the url 
                   8132:                                redirected too)
1.352     albertel 8133:             domain         -> force to color decorate a page for a specific
                   8134:                                domain
                   8135:             function       -> force usage of a specific rolish color scheme
                   8136:             bgcolor        -> override the default page bgcolor
1.460     albertel 8137:             no_auto_mt_title
                   8138:                            -> prevent &mt()ing the title arg
1.464     albertel 8139: 
1.306     albertel 8140: =cut
                   8141: 
                   8142: sub headtag {
1.313     albertel 8143:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8144:     
1.363     albertel 8145:     my $function = $args->{'function'} || &get_users_function();
                   8146:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8147:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8148:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8149:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8150: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8151: 		   #time(),
1.418     albertel 8152: 		   $env{'environment.color.timestamp'},
1.363     albertel 8153: 		   $function,$domain,$bgcolor);
                   8154: 
1.369     www      8155:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8156: 
1.308     albertel 8157:     my $result =
                   8158: 	'<head>'.
1.1075.2.56  raeburn  8159: 	&font_settings($args);
1.319     albertel 8160: 
1.1075.2.72  raeburn  8161:     my $inhibitprint;
                   8162:     if ($args->{'print_suppress'}) {
                   8163:         $inhibitprint = &print_suppression();
                   8164:     }
1.1064    raeburn  8165: 
1.461     albertel 8166:     if (!$args->{'frameset'}) {
                   8167: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8168:     }
1.1075.2.12  raeburn  8169:     if ($args->{'force_register'}) {
                   8170:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8171:     }
1.436     albertel 8172:     if (!$args->{'no_nav_bar'} 
                   8173: 	&& !$args->{'only_body'}
                   8174: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8175: 	$result .= &help_menu_js($httphost);
1.1032    www      8176:         $result.=&modal_window();
1.1038    www      8177:         $result.=&togglebox_script();
1.1034    www      8178:         $result.=&wishlist_window();
1.1041    www      8179:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8180:     } else {
                   8181:         if ($args->{'add_modal'}) {
                   8182:            $result.=&modal_window();
                   8183:         }
                   8184:         if ($args->{'add_wishlist'}) {
                   8185:            $result.=&wishlist_window();
                   8186:         }
1.1038    www      8187:         if ($args->{'add_togglebox'}) {
                   8188:            $result.=&togglebox_script();
                   8189:         }
1.1041    www      8190:         if ($args->{'add_progressbar'}) {
                   8191:            $result.=&LCprogressbarUpdate_script();
                   8192:         }
1.436     albertel 8193:     }
1.314     albertel 8194:     if (ref($args->{'redirect'})) {
1.414     albertel 8195: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8196: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8197: 	if (!$inhibit_continue) {
                   8198: 	    $env{'internal.head.redirect'} = $url;
                   8199: 	}
1.313     albertel 8200: 	$result.=<<ADDMETA
                   8201: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8202: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8203: ADDMETA
1.1075.2.89  raeburn  8204:     } else {
                   8205:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8206:             my $requrl = $env{'request.uri'};
                   8207:             if ($requrl eq '') {
                   8208:                 $requrl = $ENV{'REQUEST_URI'};
                   8209:                 $requrl =~ s/\?.+$//;
                   8210:             }
                   8211:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8212:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8213:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8214:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8215:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8216:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8217:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8218:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8219:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8220:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8221:                             $offload = 1;
1.1075.2.151  raeburn  8222:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8223:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8224:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8225:                                     $offloadoth = 1;
                   8226:                                     $dom_in_use = $env{'user.domain'};
                   8227:                                 }
                   8228:                             }
1.1075.2.145  raeburn  8229:                         }
                   8230:                     }
                   8231:                     unless ($offload) {
                   8232:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8233:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8234:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8235:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8236:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8237:                                         $offload = 1;
1.1075.2.151  raeburn  8238:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8239:                                         $dom_in_use = $env{'user.domain'};
                   8240:                                     }
1.1075.2.89  raeburn  8241:                                 }
1.1075.2.145  raeburn  8242:                             }
                   8243:                         }
                   8244:                     }
                   8245:                     if ($offload) {
1.1075.2.158  raeburn  8246:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8247:                         if (($newserver eq '') && ($offloadoth)) {
                   8248:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 8249:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  8250:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8251:                             }
                   8252:                         }
1.1075.2.145  raeburn  8253:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8254:                             my $numsec = 5;
                   8255:                             my $timeout = $numsec * 1000;
                   8256:                             my ($newurl,$locknum,%locks,$msg);
                   8257:                             if ($env{'request.role.adv'}) {
                   8258:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8259:                             }
                   8260:                             my $disable_submit = 0;
                   8261:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8262:                                 $disable_submit = 1;
                   8263:                             }
                   8264:                             if ($locknum) {
                   8265:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8266:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8267:                                        join(", ",sort(values(%locks)))."\n";
                   8268:                                 if (&show_course()) {
                   8269:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8270:                                 } else {
1.1075.2.145  raeburn  8271:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8272:                                 }
                   8273:                             } else {
                   8274:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8275:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8276:                                 }
                   8277:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8278:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8279:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8280:                                     $newurl .= '&role='.$env{'request.role'};
                   8281:                                 }
                   8282:                                 if ($env{'request.symb'}) {
                   8283:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8284:                                     if ($shownsymb =~ m{^/enc/}) {
                   8285:                                         my $reqdmajor = 2;
                   8286:                                         my $reqdminor = 11;
                   8287:                                         my $reqdsubminor = 3;
                   8288:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8289:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8290:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8291:                                         if (($major eq '' && $minor eq '') ||
                   8292:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8293:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8294:                                              ($reqdsubminor > $subminor))))) {
                   8295:                                             undef($shownsymb);
                   8296:                                         }
1.1075.2.89  raeburn  8297:                                     }
1.1075.2.145  raeburn  8298:                                     if ($shownsymb) {
                   8299:                                         &js_escape(\$shownsymb);
                   8300:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8301:                                     }
1.1075.2.145  raeburn  8302:                                 } else {
                   8303:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8304:                                     &js_escape(\$shownurl);
                   8305:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8306:                                 }
1.1075.2.145  raeburn  8307:                             }
                   8308:                             &js_escape(\$msg);
                   8309:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8310: <meta http-equiv="pragma" content="no-cache" />
                   8311: <script type="text/javascript">
1.1075.2.92  raeburn  8312: // <![CDATA[
1.1075.2.89  raeburn  8313: function LC_Offload_Now() {
                   8314:     var dest = "$newurl";
                   8315:     if (dest != '') {
                   8316:         window.location.href="$newurl";
                   8317:     }
                   8318: }
1.1075.2.92  raeburn  8319: \$(document).ready(function () {
                   8320:     window.alert('$msg');
                   8321:     if ($disable_submit) {
1.1075.2.89  raeburn  8322:         \$(".LC_hwk_submit").prop("disabled", true);
                   8323:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8324:     }
                   8325:     setTimeout('LC_Offload_Now()', $timeout);
                   8326: });
                   8327: // ]]>
1.1075.2.89  raeburn  8328: </script>
                   8329: OFFLOAD
                   8330:                         }
                   8331:                     }
                   8332:                 }
                   8333:             }
                   8334:         }
1.313     albertel 8335:     }
1.306     albertel 8336:     if (!defined($title)) {
                   8337: 	$title = 'The LearningOnline Network with CAPA';
                   8338:     }
1.460     albertel 8339:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8340:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8341: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8342:     if (!$args->{'frameset'}) {
                   8343:         $result .= ' /';
                   8344:     }
                   8345:     $result .= '>'
1.1064    raeburn  8346:         .$inhibitprint
1.414     albertel 8347: 	.$head_extra;
1.1075.2.108  raeburn  8348:     my $clientmobile;
                   8349:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8350:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8351:     } else {
                   8352:         $clientmobile = $env{'browser.mobile'};
                   8353:     }
                   8354:     if ($clientmobile) {
1.1075.2.42  raeburn  8355:         $result .= '
                   8356: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8357: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8358:     }
1.1075.2.126  raeburn  8359:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8360:     return $result.'</head>';
1.306     albertel 8361: }
                   8362: 
                   8363: =pod
                   8364: 
1.340     albertel 8365: =item * &font_settings()
                   8366: 
                   8367: Returns neccessary <meta> to set the proper encoding
                   8368: 
1.1075.2.56  raeburn  8369: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8370: 
                   8371: =cut
                   8372: 
                   8373: sub font_settings {
1.1075.2.56  raeburn  8374:     my ($args) = @_;
1.340     albertel 8375:     my $headerstring='';
1.1075.2.56  raeburn  8376:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8377:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8378: 	$headerstring.=
1.1075.2.61  raeburn  8379: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8380:         if (!$args->{'frameset'}) {
                   8381:             $headerstring.= ' /';
                   8382:         }
                   8383:         $headerstring .= '>'."\n";
1.340     albertel 8384:     }
                   8385:     return $headerstring;
                   8386: }
                   8387: 
1.341     albertel 8388: =pod
                   8389: 
1.1064    raeburn  8390: =item * &print_suppression()
                   8391: 
                   8392: In course context returns css which causes the body to be blank when media="print",
                   8393: if printout generation is unavailable for the current resource.
                   8394: 
                   8395: This could be because:
                   8396: 
                   8397: (a) printstartdate is in the future
                   8398: 
                   8399: (b) printenddate is in the past
                   8400: 
                   8401: (c) there is an active exam block with "printout"
                   8402: functionality blocked
                   8403: 
                   8404: Users with pav, pfo or evb privileges are exempt.
                   8405: 
                   8406: Inputs: none
                   8407: 
                   8408: =cut
                   8409: 
                   8410: 
                   8411: sub print_suppression {
                   8412:     my $noprint;
                   8413:     if ($env{'request.course.id'}) {
                   8414:         my $scope = $env{'request.course.id'};
                   8415:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8416:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8417:             return;
                   8418:         }
                   8419:         if ($env{'request.course.sec'} ne '') {
                   8420:             $scope .= "/$env{'request.course.sec'}";
                   8421:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8422:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8423:                 return;
1.1064    raeburn  8424:             }
                   8425:         }
                   8426:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8427:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  8428:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   8429:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8430:         if ($blocked) {
                   8431:             my $checkrole = "cm./$cdom/$cnum";
                   8432:             if ($env{'request.course.sec'} ne '') {
                   8433:                 $checkrole .= "/$env{'request.course.sec'}";
                   8434:             }
                   8435:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8436:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8437:                 $noprint = 1;
                   8438:             }
                   8439:         }
                   8440:         unless ($noprint) {
                   8441:             my $symb = &Apache::lonnet::symbread();
                   8442:             if ($symb ne '') {
                   8443:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8444:                 if (ref($navmap)) {
                   8445:                     my $res = $navmap->getBySymb($symb);
                   8446:                     if (ref($res)) {
                   8447:                         if (!$res->resprintable()) {
                   8448:                             $noprint = 1;
                   8449:                         }
                   8450:                     }
                   8451:                 }
                   8452:             }
                   8453:         }
                   8454:         if ($noprint) {
                   8455:             return <<"ENDSTYLE";
                   8456: <style type="text/css" media="print">
                   8457:     body { display:none }
                   8458: </style>
                   8459: ENDSTYLE
                   8460:         }
                   8461:     }
                   8462:     return;
                   8463: }
                   8464: 
                   8465: =pod
                   8466: 
1.341     albertel 8467: =item * &xml_begin()
                   8468: 
                   8469: Returns the needed doctype and <html>
                   8470: 
                   8471: Inputs: none
                   8472: 
                   8473: =cut
                   8474: 
                   8475: sub xml_begin {
1.1075.2.61  raeburn  8476:     my ($is_frameset) = @_;
1.341     albertel 8477:     my $output='';
                   8478: 
                   8479:     if ($env{'browser.mathml'}) {
                   8480: 	$output='<?xml version="1.0"?>'
                   8481:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8482: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8483:             
                   8484: #	    .'<!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">] >'
                   8485: 	    .'<!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">'
                   8486:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8487: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8488:     } elsif ($is_frameset) {
                   8489:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8490:                 '<html>'."\n";
1.341     albertel 8491:     } else {
1.1075.2.61  raeburn  8492: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8493:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8494:     }
                   8495:     return $output;
                   8496: }
1.340     albertel 8497: 
                   8498: =pod
                   8499: 
1.306     albertel 8500: =item * &start_page()
                   8501: 
                   8502: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8503: 
1.648     raeburn  8504: Inputs:
                   8505: 
                   8506: =over 4
                   8507: 
                   8508: $title - optional title for the page
                   8509: 
                   8510: $head_extra - optional extra HTML to incude inside the <head>
                   8511: 
                   8512: $args - additional optional args supported are:
                   8513: 
                   8514: =over 8
                   8515: 
                   8516:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8517:                                     arg on
1.814     bisitz   8518:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8519:              add_entries    -> additional attributes to add to the  <body>
                   8520:              domain         -> force to color decorate a page for a 
1.317     albertel 8521:                                     specific domain
1.648     raeburn  8522:              function       -> force usage of a specific rolish color
1.317     albertel 8523:                                     scheme
1.648     raeburn  8524:              redirect       -> see &headtag()
                   8525:              bgcolor        -> override the default page bg color
                   8526:              js_ready       -> return a string ready for being used in 
1.317     albertel 8527:                                     a javascript writeln
1.648     raeburn  8528:              html_encode    -> return a string ready for being used in 
1.320     albertel 8529:                                     a html attribute
1.648     raeburn  8530:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8531:                                     $forcereg arg
1.648     raeburn  8532:              frameset       -> if true will start with a <frameset>
1.330     albertel 8533:                                     rather than <body>
1.648     raeburn  8534:              skip_phases    -> hash ref of 
1.338     albertel 8535:                                     head -> skip the <html><head> generation
                   8536:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8537:              no_inline_link -> if true and in remote mode, don't show the
                   8538:                                     'Switch To Inline Menu' link
1.648     raeburn  8539:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8540:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8541:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8542:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8543:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8544:              group          -> includes the current group, if page is for a
                   8545:                                specific group
1.1075.2.133  raeburn  8546:              use_absolute   -> for request for external resource or syllabus, this
                   8547:                                will contain https://<hostname> if server uses
                   8548:                                https (as per hosts.tab), but request is for http
                   8549:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  8550:              links_disabled -> Links in primary and secondary menus are disabled
                   8551:                                (Can enable them once page has loaded - see lonroles.pm
                   8552:                                for an example).
1.361     albertel 8553: 
1.648     raeburn  8554: =back
1.460     albertel 8555: 
1.648     raeburn  8556: =back
1.562     albertel 8557: 
1.306     albertel 8558: =cut
                   8559: 
                   8560: sub start_page {
1.309     albertel 8561:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8562:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8563: 
1.315     albertel 8564:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 8565:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8566: 
1.338     albertel 8567:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8568:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8569:     }
1.1075.2.161.  .1(raebu 8570:21): 
                   8571:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   8572:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8573:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8574:21):                 $args->{'no_primary_menu'} = 1;
                   8575:21):             }
                   8576:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8577:21):                 $args->{'no_inline_menu'} = 1;
                   8578:21):             }
                   8579:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8580:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8581:21):             }
                   8582:21):         } else {
                   8583:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8584:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8585:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8586:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8587:21):                     $args->{'no_primary_menu'} = 1;
                   8588:21):                 }
                   8589:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8590:21):                     $args->{'no_inline_menu'} = 1;
                   8591:21):                 }
                   8592:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8593:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8594:21):                 }
                   8595:21):             }
                   8596:21):         }
                   8597:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8598:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8599:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8600:21):     } elsif ($env{'request.course.id'}) {
                   8601:21):         my $expiretime=600;
                   8602:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   8603:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   8604:21):         }
                   8605:21):         my ($deeplinkmenu,$menuref);
                   8606:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   8607:21):         if ($menucoll) {
                   8608:21):             if (ref($menuref) eq 'HASH') {
                   8609:21):                 %menu = %{$menuref};
                   8610:21):             }
                   8611:21):             if ($menu{'top'} eq 'n') {
                   8612:21):                 $args->{'no_primary_menu'} = 1;
                   8613:21):             }
                   8614:21):             if ($menu{'inline'} eq 'n') {
                   8615:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   8616:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8617:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8618:21):                     my $crstype = &course_type();
                   8619:21):                     my $now = time;
                   8620:21):                     my $ccrole;
                   8621:21):                     if ($crstype eq 'Community') {
                   8622:21):                         $ccrole = 'co';
                   8623:21):                     } else {
                   8624:21):                         $ccrole = 'cc';
                   8625:21):                     }
                   8626:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   8627:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   8628:21):                         if ((($start) && ($start<0)) ||
                   8629:21):                             (($end) && ($end<$now))  ||
                   8630:21):                             (($start) && ($now<$start))) {
                   8631:21):                             $args->{'no_inline_menu'} = 1;
                   8632:21):                         }
                   8633:21):                     } else {
                   8634:21):                         $args->{'no_inline_menu'} = 1;
                   8635:21):                     }
                   8636:21):                 }
                   8637:21):             }
                   8638:21):         }
                   8639:21):     }
1.338     albertel 8640:     
                   8641:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8642: 	if ($args->{'frameset'}) {
                   8643: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8644: 						$args->{'add_entries'});
                   8645: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8646:         } else {
                   8647:             $result .=
                   8648:                 &bodytag($title, 
                   8649:                          $args->{'function'},       $args->{'add_entries'},
                   8650:                          $args->{'only_body'},      $args->{'domain'},
                   8651:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8652:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 8653:21):                          $args,                     \@advtools,
                   8654:21):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   8655:         }
1.330     albertel 8656:     }
1.338     albertel 8657: 
1.315     albertel 8658:     if ($args->{'js_ready'}) {
1.713     kaisler  8659: 		$result = &js_ready($result);
1.315     albertel 8660:     }
1.320     albertel 8661:     if ($args->{'html_encode'}) {
1.713     kaisler  8662: 		$result = &html_encode($result);
                   8663:     }
                   8664: 
1.813     bisitz   8665:     # Preparation for new and consistent functionlist at top of screen
                   8666:     # if ($args->{'functionlist'}) {
                   8667:     #            $result .= &build_functionlist();
                   8668:     #}
                   8669: 
1.964     droeschl 8670:     # Don't add anything more if only_body wanted or in const space
                   8671:     return $result if    $args->{'only_body'} 
                   8672:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8673: 
                   8674:     #Breadcrumbs
1.758     kaisler  8675:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8676: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8677: 		#if any br links exists, add them to the breadcrumbs
                   8678: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8679: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8680: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8681: 			}
                   8682: 		}
1.1075.2.19  raeburn  8683:                 # if @advtools array contains items add then to the breadcrumbs
                   8684:                 if (@advtools > 0) {
                   8685:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8686:                 }
1.1075.2.123  raeburn  8687:                 my $menulink;
                   8688:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 8689:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8690:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  8691:                     $menulink = 0;
                   8692:                 } else {
                   8693:                     undef($menulink);
                   8694:                 }
1.758     kaisler  8695: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8696: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8697: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 8698:21): 		} else {
1.1075.2.123  raeburn  8699: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8700: 		}
1.1075.2.24  raeburn  8701:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8702:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8703:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8704:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8705:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8706:     }
1.315     albertel 8707:     return $result;
1.306     albertel 8708: }
                   8709: 
                   8710: sub end_page {
1.315     albertel 8711:     my ($args) = @_;
                   8712:     $env{'internal.end_page'}++;
1.330     albertel 8713:     my $result;
1.335     albertel 8714:     if ($args->{'discussion'}) {
                   8715: 	my ($target,$parser);
                   8716: 	if (ref($args->{'discussion'})) {
                   8717: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8718: 				$args->{'discussion'}{'parser'});
                   8719: 	}
                   8720: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8721:     }
1.330     albertel 8722:     if ($args->{'frameset'}) {
                   8723: 	$result .= '</frameset>';
                   8724:     } else {
1.635     raeburn  8725: 	$result .= &endbodytag($args);
1.330     albertel 8726:     }
1.1075.2.6  raeburn  8727:     unless ($args->{'notbody'}) {
                   8728:         $result .= "\n</html>";
                   8729:     }
1.330     albertel 8730: 
1.315     albertel 8731:     if ($args->{'js_ready'}) {
1.317     albertel 8732: 	$result = &js_ready($result);
1.315     albertel 8733:     }
1.335     albertel 8734: 
1.320     albertel 8735:     if ($args->{'html_encode'}) {
                   8736: 	$result = &html_encode($result);
                   8737:     }
1.335     albertel 8738: 
1.315     albertel 8739:     return $result;
                   8740: }
                   8741: 
1.1075.2.161.  .1(raebu 8742:21): sub menucoll_in_effect {
                   8743:21):     my ($menucoll,$deeplinkmenu,%menu);
                   8744:21):     if ($env{'request.course.id'}) {
                   8745:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   8746:21):         if ($env{'request.deeplink.login'}) {
                   8747:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   8748:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8749:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8750:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   8751:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   8752:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   8753:21):                     if (ref($navmap)) {
                   8754:21):                         $deeplink = $navmap->get_mapparam(undef,
                   8755:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   8756:21):                                                           '0.deeplink');
                   8757:21):                     } else {
                   8758:21):                         $check_login_symb = 1;
                   8759:21):                     }
                   8760:21):                 } else {
                   8761:21):                     my $symb=&Apache::lonnet::symbread();
                   8762:21):                     if ($symb) {
                   8763:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   8764:21):                     } else {
                   8765:21):                         $check_login_symb = 1;
                   8766:21):                     }
                   8767:21):                 }
                   8768:21):             } else {
                   8769:21):                 $check_login_symb = 1;
                   8770:21):             }
                   8771:21):             if ($check_login_symb) {
                   8772:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   8773:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   8774:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   8775:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   8776:21):                     if (ref($navmap)) {
                   8777:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   8778:21):                     }
                   8779:21):                 } else {
                   8780:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   8781:21):                 }
                   8782:21):             }
                   8783:21):             if ($deeplink ne '') {
                   8784:21):                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
                   8785:21):                 if ($display =~ /^\d+$/) {
                   8786:21):                     $deeplinkmenu = 1;
                   8787:21):                     $menucoll = $display;
                   8788:21):                 }
                   8789:21):             }
                   8790:21):         }
                   8791:21):         if ($menucoll) {
                   8792:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   8793:21):         }
                   8794:21):     }
                   8795:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   8796:21): }
                   8797:21): 
                   8798:21): sub deeplink_login_symb {
                   8799:21):     my ($cnum,$cdom) = @_;
                   8800:21):     my $login_symb;
                   8801:21):     if ($env{'request.deeplink.login'}) {
                   8802:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   8803:21):     }
                   8804:21):     return $login_symb;
                   8805:21): }
                   8806:21): 
                   8807:21): sub symb_from_tinyurl {
                   8808:21):     my ($url,$cnum,$cdom) = @_;
                   8809:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8810:21):         my $key = $1;
                   8811:21):         my ($tinyurl,$login);
                   8812:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8813:21):         if (defined($cached)) {
                   8814:21):             $tinyurl = $result;
                   8815:21):         } else {
                   8816:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8817:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8818:21):             if ($currtiny{$key} ne '') {
                   8819:21):                 $tinyurl = $currtiny{$key};
                   8820:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8821:21):             }
                   8822:21):         }
                   8823:21):         if ($tinyurl ne '') {
                   8824:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   8825:21):             if (wantarray) {
                   8826:21):                 return ($cnumreq,$symb);
                   8827:21):             } elsif ($cnumreq eq $cnum) {
                   8828:21):                 return $symb;
                   8829:21):             }
                   8830:21):         }
                   8831:21):     }
                   8832:21):     if (wantarray) {
                   8833:21):         return ();
                   8834:21):     } else {
                   8835:21):         return;
                   8836:21):     }
                   8837:21): }
                   8838:21): 
1.1034    www      8839: sub wishlist_window {
                   8840:     return(<<'ENDWISHLIST');
1.1046    raeburn  8841: <script type="text/javascript">
1.1034    www      8842: // <![CDATA[
                   8843: // <!-- BEGIN LON-CAPA Internal
                   8844: function set_wishlistlink(title, path) {
                   8845:     if (!title) {
                   8846:         title = document.title;
                   8847:         title = title.replace(/^LON-CAPA /,'');
                   8848:     }
1.1075.2.65  raeburn  8849:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8850:     title = title.replace("'","\\\'");
1.1034    www      8851:     if (!path) {
                   8852:         path = location.pathname;
                   8853:     }
1.1075.2.65  raeburn  8854:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8855:     path = path.replace("'","\\\'");
1.1034    www      8856:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8857:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8858: }
                   8859: // END LON-CAPA Internal -->
                   8860: // ]]>
                   8861: </script>
                   8862: ENDWISHLIST
                   8863: }
                   8864: 
1.1030    www      8865: sub modal_window {
                   8866:     return(<<'ENDMODAL');
1.1046    raeburn  8867: <script type="text/javascript">
1.1030    www      8868: // <![CDATA[
                   8869: // <!-- BEGIN LON-CAPA Internal
                   8870: var modalWindow = {
                   8871: 	parent:"body",
                   8872: 	windowId:null,
                   8873: 	content:null,
                   8874: 	width:null,
                   8875: 	height:null,
                   8876: 	close:function()
                   8877: 	{
                   8878: 	        $(".LCmodal-window").remove();
                   8879: 	        $(".LCmodal-overlay").remove();
                   8880: 	},
                   8881: 	open:function()
                   8882: 	{
                   8883: 		var modal = "";
                   8884: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8885: 		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;\">";
                   8886: 		modal += this.content;
                   8887: 		modal += "</div>";	
                   8888: 
                   8889: 		$(this.parent).append(modal);
                   8890: 
                   8891: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8892: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8893: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8894: 	}
                   8895: };
1.1075.2.42  raeburn  8896: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8897: 	{
1.1075.2.119  raeburn  8898:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8899: 		modalWindow.windowId = "myModal";
                   8900: 		modalWindow.width = width;
                   8901: 		modalWindow.height = height;
1.1075.2.80  raeburn  8902: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8903: 		modalWindow.open();
1.1075.2.87  raeburn  8904: 	};
1.1030    www      8905: // END LON-CAPA Internal -->
                   8906: // ]]>
                   8907: </script>
                   8908: ENDMODAL
                   8909: }
                   8910: 
                   8911: sub modal_link {
1.1075.2.42  raeburn  8912:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8913:     unless ($width) { $width=480; }
                   8914:     unless ($height) { $height=400; }
1.1031    www      8915:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8916:     unless ($transparency) { $transparency='true'; }
                   8917: 
1.1074    raeburn  8918:     my $target_attr;
                   8919:     if (defined($target)) {
                   8920:         $target_attr = 'target="'.$target.'"';
                   8921:     }
                   8922:     return <<"ENDLINK";
1.1075.2.143  raeburn  8923: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8924: ENDLINK
1.1030    www      8925: }
                   8926: 
1.1032    www      8927: sub modal_adhoc_script {
1.1075.2.155  raeburn  8928:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   8929:     my $mathjax;
                   8930:     if ($possmathjax) {
                   8931:         $mathjax = <<'ENDJAX';
                   8932:                if (typeof MathJax == 'object') {
                   8933:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   8934:                }
                   8935: ENDJAX
                   8936:     }
1.1032    www      8937:     return (<<ENDADHOC);
1.1046    raeburn  8938: <script type="text/javascript">
1.1032    www      8939: // <![CDATA[
                   8940:         var $funcname = function()
                   8941:         {
                   8942:                 modalWindow.windowId = "myModal";
                   8943:                 modalWindow.width = $width;
                   8944:                 modalWindow.height = $height;
                   8945:                 modalWindow.content = '$content';
                   8946:                 modalWindow.open();
1.1075.2.155  raeburn  8947:                 $mathjax
1.1032    www      8948:         };  
                   8949: // ]]>
                   8950: </script>
                   8951: ENDADHOC
                   8952: }
                   8953: 
1.1041    www      8954: sub modal_adhoc_inner {
1.1075.2.155  raeburn  8955:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      8956:     my $innerwidth=$width-20;
                   8957:     $content=&js_ready(
1.1042    www      8958:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8959:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8960:                  $content.
1.1041    www      8961:                  &end_scrollbox().
1.1075.2.42  raeburn  8962:                  &end_page()
1.1041    www      8963:              );
1.1075.2.155  raeburn  8964:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      8965: }
                   8966: 
                   8967: sub modal_adhoc_window {
1.1075.2.155  raeburn  8968:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   8969:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      8970:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8971: }
                   8972: 
                   8973: sub modal_adhoc_launch {
                   8974:     my ($funcname,$width,$height,$content)=@_;
                   8975:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8976: <script type="text/javascript">
                   8977: // <![CDATA[
                   8978: $funcname();
                   8979: // ]]>
                   8980: </script>
                   8981: ENDLAUNCH
                   8982: }
                   8983: 
                   8984: sub modal_adhoc_close {
                   8985:     return (<<ENDCLOSE);
                   8986: <script type="text/javascript">
                   8987: // <![CDATA[
                   8988: modalWindow.close();
                   8989: // ]]>
                   8990: </script>
                   8991: ENDCLOSE
                   8992: }
                   8993: 
1.1038    www      8994: sub togglebox_script {
                   8995:    return(<<ENDTOGGLE);
                   8996: <script type="text/javascript"> 
                   8997: // <![CDATA[
                   8998: function LCtoggleDisplay(id,hidetext,showtext) {
                   8999:    link = document.getElementById(id + "link").childNodes[0];
                   9000:    with (document.getElementById(id).style) {
                   9001:       if (display == "none" ) {
                   9002:           display = "inline";
                   9003:           link.nodeValue = hidetext;
                   9004:         } else {
                   9005:           display = "none";
                   9006:           link.nodeValue = showtext;
                   9007:        }
                   9008:    }
                   9009: }
                   9010: // ]]>
                   9011: </script>
                   9012: ENDTOGGLE
                   9013: }
                   9014: 
1.1039    www      9015: sub start_togglebox {
                   9016:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9017:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9018:     unless ($showtext) { $showtext=&mt('show'); }
                   9019:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9020:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9021:     return &start_data_table().
                   9022:            &start_data_table_header_row().
                   9023:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9024:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9025:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9026:            &end_data_table_header_row().
                   9027:            '<tr id="'.$id.'" style="display:none""><td>';
                   9028: }
                   9029: 
                   9030: sub end_togglebox {
                   9031:     return '</td></tr>'.&end_data_table();
                   9032: }
                   9033: 
1.1041    www      9034: sub LCprogressbar_script {
1.1075.2.130  raeburn  9035:    my ($id,$number_to_do)=@_;
                   9036:    if ($number_to_do) {
                   9037:        return(<<ENDPROGRESS);
1.1041    www      9038: <script type="text/javascript">
                   9039: // <![CDATA[
1.1045    www      9040: \$('#progressbar$id').progressbar({
1.1041    www      9041:   value: 0,
                   9042:   change: function(event, ui) {
                   9043:     var newVal = \$(this).progressbar('option', 'value');
                   9044:     \$('.pblabel', this).text(LCprogressTxt);
                   9045:   }
                   9046: });
                   9047: // ]]>
                   9048: </script>
                   9049: ENDPROGRESS
1.1075.2.130  raeburn  9050:    } else {
                   9051:        return(<<ENDPROGRESS);
                   9052: <script type="text/javascript">
                   9053: // <![CDATA[
                   9054: \$('#progressbar$id').progressbar({
                   9055:   value: false,
                   9056:   create: function(event, ui) {
                   9057:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9058:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9059:   }
                   9060: });
                   9061: // ]]>
                   9062: </script>
                   9063: ENDPROGRESS
                   9064:    }
1.1041    www      9065: }
                   9066: 
                   9067: sub LCprogressbarUpdate_script {
                   9068:    return(<<ENDPROGRESSUPDATE);
                   9069: <style type="text/css">
                   9070: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9071: .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      9072: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9073: </style>
                   9074: <script type="text/javascript">
                   9075: // <![CDATA[
1.1045    www      9076: var LCprogressTxt='---';
                   9077: 
1.1075.2.130  raeburn  9078: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9079:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9080:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9081:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9082:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9083:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9084:    } else {
                   9085:        \$('#progressbar'+id).progressbar('value',percent);
                   9086:    }
1.1041    www      9087: }
                   9088: // ]]>
                   9089: </script>
                   9090: ENDPROGRESSUPDATE
                   9091: }
                   9092: 
1.1042    www      9093: my $LClastpercent;
1.1045    www      9094: my $LCidcnt;
                   9095: my $LCcurrentid;
1.1042    www      9096: 
1.1041    www      9097: sub LCprogressbar {
1.1075.2.130  raeburn  9098:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9099:     $LClastpercent=0;
1.1045    www      9100:     $LCidcnt++;
                   9101:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9102:     my ($starting,$content);
                   9103:     if ($number_to_do) {
                   9104:         $starting=&mt('Starting');
                   9105:         $content=(<<ENDPROGBAR);
                   9106: $preamble
1.1045    www      9107:   <div id="progressbar$LCcurrentid">
1.1041    www      9108:     <span class="pblabel">$starting</span>
                   9109:   </div>
                   9110: ENDPROGBAR
1.1075.2.130  raeburn  9111:     } else {
                   9112:         $starting=&mt('Loading...');
                   9113:         $LClastpercent='false';
                   9114:         $content=(<<ENDPROGBAR);
                   9115: $preamble
                   9116:   <div id="progressbar$LCcurrentid">
                   9117:       <div class="progress-label">$starting</div>
                   9118:   </div>
                   9119: ENDPROGBAR
                   9120:     }
                   9121:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9122: }
                   9123: 
                   9124: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9125:     my ($r,$val,$text,$number_to_do)=@_;
                   9126:     if ($number_to_do) {
                   9127:         unless ($val) { 
                   9128:             if ($LClastpercent) {
                   9129:                 $val=$LClastpercent;
                   9130:             } else {
                   9131:                 $val=0;
                   9132:             }
                   9133:         }
                   9134:         if ($val<0) { $val=0; }
                   9135:         if ($val>100) { $val=0; }
                   9136:         $LClastpercent=$val;
                   9137:         unless ($text) { $text=$val.'%'; }
                   9138:     } else {
                   9139:         $val = 'false';
1.1042    www      9140:     }
1.1041    www      9141:     $text=&js_ready($text);
1.1044    www      9142:     &r_print($r,<<ENDUPDATE);
1.1041    www      9143: <script type="text/javascript">
                   9144: // <![CDATA[
1.1075.2.130  raeburn  9145: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9146: // ]]>
                   9147: </script>
                   9148: ENDUPDATE
1.1035    www      9149: }
                   9150: 
1.1042    www      9151: sub LCprogressbarClose {
                   9152:     my ($r)=@_;
                   9153:     $LClastpercent=0;
1.1044    www      9154:     &r_print($r,<<ENDCLOSE);
1.1042    www      9155: <script type="text/javascript">
                   9156: // <![CDATA[
1.1045    www      9157: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9158: // ]]>
                   9159: </script>
                   9160: ENDCLOSE
1.1044    www      9161: }
                   9162: 
                   9163: sub r_print {
                   9164:     my ($r,$to_print)=@_;
                   9165:     if ($r) {
                   9166:       $r->print($to_print);
                   9167:       $r->rflush();
                   9168:     } else {
                   9169:       print($to_print);
                   9170:     }
1.1042    www      9171: }
                   9172: 
1.320     albertel 9173: sub html_encode {
                   9174:     my ($result) = @_;
                   9175: 
1.322     albertel 9176:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9177:     
                   9178:     return $result;
                   9179: }
1.1044    www      9180: 
1.317     albertel 9181: sub js_ready {
                   9182:     my ($result) = @_;
                   9183: 
1.323     albertel 9184:     $result =~ s/[\n\r]/ /xmsg;
                   9185:     $result =~ s/\\/\\\\/xmsg;
                   9186:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9187:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9188:     
                   9189:     return $result;
                   9190: }
                   9191: 
1.315     albertel 9192: sub validate_page {
                   9193:     if (  exists($env{'internal.start_page'})
1.316     albertel 9194: 	  &&     $env{'internal.start_page'} > 1) {
                   9195: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9196: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9197: 				 $ENV{'request.filename'});
1.315     albertel 9198:     }
                   9199:     if (  exists($env{'internal.end_page'})
1.316     albertel 9200: 	  &&     $env{'internal.end_page'} > 1) {
                   9201: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9202: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9203: 				 $env{'request.filename'});
1.315     albertel 9204:     }
                   9205:     if (     exists($env{'internal.start_page'})
                   9206: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9207: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9208: 				 $env{'request.filename'});
1.315     albertel 9209:     }
                   9210:     if (   ! exists($env{'internal.start_page'})
                   9211: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9212: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9213: 				 $env{'request.filename'});
1.315     albertel 9214:     }
1.306     albertel 9215: }
1.315     albertel 9216: 
1.996     www      9217: 
                   9218: sub start_scrollbox {
1.1075.2.56  raeburn  9219:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9220:     unless ($outerwidth) { $outerwidth='520px'; }
                   9221:     unless ($width) { $width='500px'; }
                   9222:     unless ($height) { $height='200px'; }
1.1075    raeburn  9223:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9224:     if ($id ne '') {
1.1075.2.42  raeburn  9225:         $table_id = ' id="table_'.$id.'"';
                   9226:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9227:     }
1.1075    raeburn  9228:     if ($bgcolor ne '') {
                   9229:         $tdcol = "background-color: $bgcolor;";
                   9230:     }
1.1075.2.42  raeburn  9231:     my $nicescroll_js;
                   9232:     if ($env{'browser.mobile'}) {
                   9233:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9234:     }
1.1075    raeburn  9235:     return <<"END";
1.1075.2.42  raeburn  9236: $nicescroll_js
                   9237: 
                   9238: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  9239: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  9240: END
1.996     www      9241: }
                   9242: 
                   9243: sub end_scrollbox {
1.1036    www      9244:     return '</div></td></tr></table>';
1.996     www      9245: }
                   9246: 
1.1075.2.42  raeburn  9247: sub nicescroll_javascript {
                   9248:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9249:     my %options;
                   9250:     if (ref($cursor) eq 'HASH') {
                   9251:         %options = %{$cursor};
                   9252:     }
                   9253:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9254:         $options{'railalign'} = 'left';
                   9255:     }
                   9256:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9257:         my $function  = &get_users_function();
                   9258:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   9259:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9260:             $options{'cursorcolor'} = '#00F';
                   9261:         }
                   9262:     }
                   9263:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9264:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   9265:             $options{'cursoropacity'}='1.0';
                   9266:         }
                   9267:     } else {
                   9268:         $options{'cursoropacity'}='1.0';
                   9269:     }
                   9270:     if ($options{'cursorfixedheight'} eq 'none') {
                   9271:         delete($options{'cursorfixedheight'});
                   9272:     } else {
                   9273:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9274:     }
                   9275:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9276:         delete($options{'railoffset'});
                   9277:     }
                   9278:     my @niceoptions;
                   9279:     while (my($key,$value) = each(%options)) {
                   9280:         if ($value =~ /^\{.+\}$/) {
                   9281:             push(@niceoptions,$key.':'.$value);
                   9282:         } else {
                   9283:             push(@niceoptions,$key.':"'.$value.'"');
                   9284:         }
                   9285:     }
                   9286:     my $nicescroll_js = '
                   9287: $(document).ready(
                   9288:       function() {
                   9289:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9290:       }
                   9291: );
                   9292: ';
                   9293:     if ($framecheck) {
                   9294:         $nicescroll_js .= '
                   9295: function expand_div(caller) {
                   9296:     if (top === self) {
                   9297:         document.getElementById("'.$id.'").style.width = "auto";
                   9298:         document.getElementById("'.$id.'").style.height = "auto";
                   9299:     } else {
                   9300:         try {
                   9301:             if (parent.frames) {
                   9302:                 if (parent.frames.length > 1) {
                   9303:                     var framesrc = parent.frames[1].location.href;
                   9304:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9305:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9306:                         document.getElementById("'.$id.'").style.width = "auto";
                   9307:                         document.getElementById("'.$id.'").style.height = "auto";
                   9308:                     }
                   9309:                 }
                   9310:             }
                   9311:         } catch (e) {
                   9312:             return;
                   9313:         }
                   9314:     }
                   9315:     return;
                   9316: }
                   9317: ';
                   9318:     }
                   9319:     if ($needjsready) {
                   9320:         $nicescroll_js = '
                   9321: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9322:     } else {
                   9323:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9324:     }
                   9325:     return $nicescroll_js;
                   9326: }
                   9327: 
1.318     albertel 9328: sub simple_error_page {
1.1075.2.49  raeburn  9329:     my ($r,$title,$msg,$args) = @_;
                   9330:     if (ref($args) eq 'HASH') {
                   9331:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9332:     } else {
                   9333:         $msg = &mt($msg);
                   9334:     }
                   9335: 
1.318     albertel 9336:     my $page =
                   9337: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  9338: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9339: 	&Apache::loncommon::end_page();
                   9340:     if (ref($r)) {
                   9341: 	$r->print($page);
1.327     albertel 9342: 	return;
1.318     albertel 9343:     }
                   9344:     return $page;
                   9345: }
1.347     albertel 9346: 
                   9347: {
1.610     albertel 9348:     my @row_count;
1.961     onken    9349: 
                   9350:     sub start_data_table_count {
                   9351:         unshift(@row_count, 0);
                   9352:         return;
                   9353:     }
                   9354: 
                   9355:     sub end_data_table_count {
                   9356:         shift(@row_count);
                   9357:         return;
                   9358:     }
                   9359: 
1.347     albertel 9360:     sub start_data_table {
1.1018    raeburn  9361: 	my ($add_class,$id) = @_;
1.422     albertel 9362: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9363:         my $table_id;
                   9364:         if (defined($id)) {
                   9365:             $table_id = ' id="'.$id.'"';
                   9366:         }
1.961     onken    9367: 	&start_data_table_count();
1.1018    raeburn  9368: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9369:     }
                   9370: 
                   9371:     sub end_data_table {
1.961     onken    9372: 	&end_data_table_count();
1.389     albertel 9373: 	return '</table>'."\n";;
1.347     albertel 9374:     }
                   9375: 
                   9376:     sub start_data_table_row {
1.974     wenzelju 9377: 	my ($add_class, $id) = @_;
1.610     albertel 9378: 	$row_count[0]++;
                   9379: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9380: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9381:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9382:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9383:     }
1.471     banghart 9384:     
                   9385:     sub continue_data_table_row {
1.974     wenzelju 9386: 	my ($add_class, $id) = @_;
1.610     albertel 9387: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9388: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9389:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9390:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9391:     }
1.347     albertel 9392: 
                   9393:     sub end_data_table_row {
1.389     albertel 9394: 	return '</tr>'."\n";;
1.347     albertel 9395:     }
1.367     www      9396: 
1.421     albertel 9397:     sub start_data_table_empty_row {
1.707     bisitz   9398: #	$row_count[0]++;
1.421     albertel 9399: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9400:     }
                   9401: 
                   9402:     sub end_data_table_empty_row {
                   9403: 	return '</tr>'."\n";;
                   9404:     }
                   9405: 
1.367     www      9406:     sub start_data_table_header_row {
1.389     albertel 9407: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9408:     }
                   9409: 
                   9410:     sub end_data_table_header_row {
1.389     albertel 9411: 	return '</tr>'."\n";;
1.367     www      9412:     }
1.890     droeschl 9413: 
                   9414:     sub data_table_caption {
                   9415:         my $caption = shift;
                   9416:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9417:     }
1.347     albertel 9418: }
                   9419: 
1.548     albertel 9420: =pod
                   9421: 
                   9422: =item * &inhibit_menu_check($arg)
                   9423: 
                   9424: Checks for a inhibitmenu state and generates output to preserve it
                   9425: 
                   9426: Inputs:         $arg - can be any of
                   9427:                      - undef - in which case the return value is a string 
                   9428:                                to add  into arguments list of a uri
                   9429:                      - 'input' - in which case the return value is a HTML
                   9430:                                  <form> <input> field of type hidden to
                   9431:                                  preserve the value
                   9432:                      - a url - in which case the return value is the url with
                   9433:                                the neccesary cgi args added to preserve the
                   9434:                                inhibitmenu state
                   9435:                      - a ref to a url - no return value, but the string is
                   9436:                                         updated to include the neccessary cgi
                   9437:                                         args to preserve the inhibitmenu state
                   9438: 
                   9439: =cut
                   9440: 
                   9441: sub inhibit_menu_check {
                   9442:     my ($arg) = @_;
                   9443:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9444:     if ($arg eq 'input') {
                   9445: 	if ($env{'form.inhibitmenu'}) {
                   9446: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9447: 	} else {
                   9448: 	    return
                   9449: 	}
                   9450:     }
                   9451:     if ($env{'form.inhibitmenu'}) {
                   9452: 	if (ref($arg)) {
                   9453: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9454: 	} elsif ($arg eq '') {
                   9455: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9456: 	} else {
                   9457: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9458: 	}
                   9459:     }
                   9460:     if (!ref($arg)) {
                   9461: 	return $arg;
                   9462:     }
                   9463: }
                   9464: 
1.251     albertel 9465: ###############################################
1.182     matthew  9466: 
                   9467: =pod
                   9468: 
1.549     albertel 9469: =back
                   9470: 
                   9471: =head1 User Information Routines
                   9472: 
                   9473: =over 4
                   9474: 
1.405     albertel 9475: =item * &get_users_function()
1.182     matthew  9476: 
                   9477: Used by &bodytag to determine the current users primary role.
                   9478: Returns either 'student','coordinator','admin', or 'author'.
                   9479: 
                   9480: =cut
                   9481: 
                   9482: ###############################################
                   9483: sub get_users_function {
1.815     tempelho 9484:     my $function = 'norole';
1.818     tempelho 9485:     if ($env{'request.role'}=~/^(st)/) {
                   9486:         $function='student';
                   9487:     }
1.907     raeburn  9488:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9489:         $function='coordinator';
                   9490:     }
1.258     albertel 9491:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9492:         $function='admin';
                   9493:     }
1.826     bisitz   9494:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9495:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9496:         $function='author';
                   9497:     }
                   9498:     return $function;
1.54      www      9499: }
1.99      www      9500: 
                   9501: ###############################################
                   9502: 
1.233     raeburn  9503: =pod
                   9504: 
1.821     raeburn  9505: =item * &show_course()
                   9506: 
                   9507: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9508: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9509: 
                   9510: Inputs:
                   9511: None
                   9512: 
                   9513: Outputs:
                   9514: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9515: 
                   9516: =cut
                   9517: 
                   9518: ###############################################
                   9519: sub show_course {
                   9520:     my $course = !$env{'user.adv'};
                   9521:     if (!$env{'user.adv'}) {
                   9522:         foreach my $env (keys(%env)) {
                   9523:             next if ($env !~ m/^user\.priv\./);
                   9524:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9525:                 $course = 0;
                   9526:                 last;
                   9527:             }
                   9528:         }
                   9529:     }
                   9530:     return $course;
                   9531: }
                   9532: 
                   9533: ###############################################
                   9534: 
                   9535: =pod
                   9536: 
1.542     raeburn  9537: =item * &check_user_status()
1.274     raeburn  9538: 
                   9539: Determines current status of supplied role for a
                   9540: specific user. Roles can be active, previous or future.
                   9541: 
                   9542: Inputs: 
                   9543: user's domain, user's username, course's domain,
1.375     raeburn  9544: course's number, optional section ID.
1.274     raeburn  9545: 
                   9546: Outputs:
                   9547: role status: active, previous or future. 
                   9548: 
                   9549: =cut
                   9550: 
                   9551: sub check_user_status {
1.412     raeburn  9552:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9553:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9554:     my @uroles = keys(%userinfo);
1.274     raeburn  9555:     my $srchstr;
                   9556:     my $active_chk = 'none';
1.412     raeburn  9557:     my $now = time;
1.274     raeburn  9558:     if (@uroles > 0) {
1.908     raeburn  9559:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9560:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9561:         } else {
1.412     raeburn  9562:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9563:         }
                   9564:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9565:             my $role_end = 0;
                   9566:             my $role_start = 0;
                   9567:             $active_chk = 'active';
1.412     raeburn  9568:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9569:                 $role_end = $1;
                   9570:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9571:                     $role_start = $1;
1.274     raeburn  9572:                 }
                   9573:             }
                   9574:             if ($role_start > 0) {
1.412     raeburn  9575:                 if ($now < $role_start) {
1.274     raeburn  9576:                     $active_chk = 'future';
                   9577:                 }
                   9578:             }
                   9579:             if ($role_end > 0) {
1.412     raeburn  9580:                 if ($now > $role_end) {
1.274     raeburn  9581:                     $active_chk = 'previous';
                   9582:                 }
                   9583:             }
                   9584:         }
                   9585:     }
                   9586:     return $active_chk;
                   9587: }
                   9588: 
                   9589: ###############################################
                   9590: 
                   9591: =pod
                   9592: 
1.405     albertel 9593: =item * &get_sections()
1.233     raeburn  9594: 
                   9595: Determines all the sections for a course including
                   9596: sections with students and sections containing other roles.
1.419     raeburn  9597: Incoming parameters: 
                   9598: 
                   9599: 1. domain
                   9600: 2. course number 
                   9601: 3. reference to array containing roles for which sections should 
                   9602: be gathered (optional).
                   9603: 4. reference to array containing status types for which sections 
                   9604: should be gathered (optional).
                   9605: 
                   9606: If the third argument is undefined, sections are gathered for any role. 
                   9607: If the fourth argument is undefined, sections are gathered for any status.
                   9608: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9609:  
1.374     raeburn  9610: Returns section hash (keys are section IDs, values are
                   9611: number of users in each section), subject to the
1.419     raeburn  9612: optional roles filter, optional status filter 
1.233     raeburn  9613: 
                   9614: =cut
                   9615: 
                   9616: ###############################################
                   9617: sub get_sections {
1.419     raeburn  9618:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9619:     if (!defined($cdom) || !defined($cnum)) {
                   9620:         my $cid =  $env{'request.course.id'};
                   9621: 
                   9622: 	return if (!defined($cid));
                   9623: 
                   9624:         $cdom = $env{'course.'.$cid.'.domain'};
                   9625:         $cnum = $env{'course.'.$cid.'.num'};
                   9626:     }
                   9627: 
                   9628:     my %sectioncount;
1.419     raeburn  9629:     my $now = time;
1.240     albertel 9630: 
1.1075.2.33  raeburn  9631:     my $check_students = 1;
                   9632:     my $only_students = 0;
                   9633:     if (ref($possible_roles) eq 'ARRAY') {
                   9634:         if (grep(/^st$/,@{$possible_roles})) {
                   9635:             if (@{$possible_roles} == 1) {
                   9636:                 $only_students = 1;
                   9637:             }
                   9638:         } else {
                   9639:             $check_students = 0;
                   9640:         }
                   9641:     }
                   9642: 
                   9643:     if ($check_students) {
1.276     albertel 9644: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9645: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9646: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9647:         my $start_index = &Apache::loncoursedata::CL_START();
                   9648:         my $end_index = &Apache::loncoursedata::CL_END();
                   9649:         my $status;
1.366     albertel 9650: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9651: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9652: 				                     $data->[$status_index],
                   9653:                                                      $data->[$start_index],
                   9654:                                                      $data->[$end_index]);
                   9655:             if ($stu_status eq 'Active') {
                   9656:                 $status = 'active';
                   9657:             } elsif ($end < $now) {
                   9658:                 $status = 'previous';
                   9659:             } elsif ($start > $now) {
                   9660:                 $status = 'future';
                   9661:             } 
                   9662: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9663:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9664:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9665: 		    $sectioncount{$section}++;
                   9666:                 }
1.240     albertel 9667: 	    }
                   9668: 	}
                   9669:     }
1.1075.2.33  raeburn  9670:     if ($only_students) {
                   9671:         return %sectioncount;
                   9672:     }
1.240     albertel 9673:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9674:     foreach my $user (sort(keys(%courseroles))) {
                   9675: 	if ($user !~ /^(\w{2})/) { next; }
                   9676: 	my ($role) = ($user =~ /^(\w{2})/);
                   9677: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9678: 	my ($section,$status);
1.240     albertel 9679: 	if ($role eq 'cr' &&
                   9680: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9681: 	    $section=$1;
                   9682: 	}
                   9683: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9684: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9685:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9686:         if ($end == -1 && $start == -1) {
                   9687:             next; #deleted role
                   9688:         }
                   9689:         if (!defined($possible_status)) { 
                   9690:             $sectioncount{$section}++;
                   9691:         } else {
                   9692:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9693:                 $status = 'active';
                   9694:             } elsif ($end < $now) {
                   9695:                 $status = 'future';
                   9696:             } elsif ($start > $now) {
                   9697:                 $status = 'previous';
                   9698:             }
                   9699:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9700:                 $sectioncount{$section}++;
                   9701:             }
                   9702:         }
1.233     raeburn  9703:     }
1.366     albertel 9704:     return %sectioncount;
1.233     raeburn  9705: }
                   9706: 
1.274     raeburn  9707: ###############################################
1.294     raeburn  9708: 
                   9709: =pod
1.405     albertel 9710: 
                   9711: =item * &get_course_users()
                   9712: 
1.275     raeburn  9713: Retrieves usernames:domains for users in the specified course
                   9714: with specific role(s), and access status. 
                   9715: 
                   9716: Incoming parameters:
1.277     albertel 9717: 1. course domain
                   9718: 2. course number
                   9719: 3. access status: users must have - either active, 
1.275     raeburn  9720: previous, future, or all.
1.277     albertel 9721: 4. reference to array of permissible roles
1.288     raeburn  9722: 5. reference to array of section restrictions (optional)
                   9723: 6. reference to results object (hash of hashes).
                   9724: 7. reference to optional userdata hash
1.609     raeburn  9725: 8. reference to optional statushash
1.630     raeburn  9726: 9. flag if privileged users (except those set to unhide in
                   9727:    course settings) should be excluded    
1.609     raeburn  9728: Keys of top level results hash are roles.
1.275     raeburn  9729: Keys of inner hashes are username:domain, with 
                   9730: values set to access type.
1.288     raeburn  9731: Optional userdata hash returns an array with arguments in the 
                   9732: same order as loncoursedata::get_classlist() for student data.
                   9733: 
1.609     raeburn  9734: Optional statushash returns
                   9735: 
1.288     raeburn  9736: Entries for end, start, section and status are blank because
                   9737: of the possibility of multiple values for non-student roles.
                   9738: 
1.275     raeburn  9739: =cut
1.405     albertel 9740: 
1.275     raeburn  9741: ###############################################
1.405     albertel 9742: 
1.275     raeburn  9743: sub get_course_users {
1.630     raeburn  9744:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9745:     my %idx = ();
1.419     raeburn  9746:     my %seclists;
1.288     raeburn  9747: 
                   9748:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9749:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9750:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9751:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9752:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9753:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9754:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9755:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9756: 
1.290     albertel 9757:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9758:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9759:         my $now = time;
1.277     albertel 9760:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9761:             my $match = 0;
1.412     raeburn  9762:             my $secmatch = 0;
1.419     raeburn  9763:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9764:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9765:             if ($section eq '') {
                   9766:                 $section = 'none';
                   9767:             }
1.291     albertel 9768:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9769:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9770:                     $secmatch = 1;
                   9771:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9772:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9773:                         $secmatch = 1;
                   9774:                     }
                   9775:                 } else {  
1.419     raeburn  9776: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9777: 		        $secmatch = 1;
                   9778:                     }
1.290     albertel 9779: 		}
1.412     raeburn  9780:                 if (!$secmatch) {
                   9781:                     next;
                   9782:                 }
1.419     raeburn  9783:             }
1.275     raeburn  9784:             if (defined($$types{'active'})) {
1.288     raeburn  9785:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9786:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9787:                     $match = 1;
1.275     raeburn  9788:                 }
                   9789:             }
                   9790:             if (defined($$types{'previous'})) {
1.609     raeburn  9791:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9792:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9793:                     $match = 1;
1.275     raeburn  9794:                 }
                   9795:             }
                   9796:             if (defined($$types{'future'})) {
1.609     raeburn  9797:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9798:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9799:                     $match = 1;
1.275     raeburn  9800:                 }
                   9801:             }
1.609     raeburn  9802:             if ($match) {
                   9803:                 push(@{$seclists{$student}},$section);
                   9804:                 if (ref($userdata) eq 'HASH') {
                   9805:                     $$userdata{$student} = $$classlist{$student};
                   9806:                 }
                   9807:                 if (ref($statushash) eq 'HASH') {
                   9808:                     $statushash->{$student}{'st'}{$section} = $status;
                   9809:                 }
1.288     raeburn  9810:             }
1.275     raeburn  9811:         }
                   9812:     }
1.412     raeburn  9813:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9814:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9815:         my $now = time;
1.609     raeburn  9816:         my %displaystatus = ( previous => 'Expired',
                   9817:                               active   => 'Active',
                   9818:                               future   => 'Future',
                   9819:                             );
1.1075.2.36  raeburn  9820:         my (%nothide,@possdoms);
1.630     raeburn  9821:         if ($hidepriv) {
                   9822:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9823:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9824:                 if ($user !~ /:/) {
                   9825:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9826:                 } else {
                   9827:                     $nothide{$user} = 1;
                   9828:                 }
                   9829:             }
1.1075.2.36  raeburn  9830:             my @possdoms = ($cdom);
                   9831:             if ($coursehash{'checkforpriv'}) {
                   9832:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9833:             }
1.630     raeburn  9834:         }
1.439     raeburn  9835:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9836:             my $match = 0;
1.412     raeburn  9837:             my $secmatch = 0;
1.439     raeburn  9838:             my $status;
1.412     raeburn  9839:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9840:             $user =~ s/:$//;
1.439     raeburn  9841:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9842:             if ($end == -1 || $start == -1) {
                   9843:                 next;
                   9844:             }
                   9845:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9846:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9847:                 my ($uname,$udom) = split(/:/,$user);
                   9848:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9849:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9850:                         $secmatch = 1;
                   9851:                     } elsif ($usec eq '') {
1.420     albertel 9852:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9853:                             $secmatch = 1;
                   9854:                         }
                   9855:                     } else {
                   9856:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9857:                             $secmatch = 1;
                   9858:                         }
                   9859:                     }
                   9860:                     if (!$secmatch) {
                   9861:                         next;
                   9862:                     }
1.288     raeburn  9863:                 }
1.419     raeburn  9864:                 if ($usec eq '') {
                   9865:                     $usec = 'none';
                   9866:                 }
1.275     raeburn  9867:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9868:                     if ($hidepriv) {
1.1075.2.36  raeburn  9869:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9870:                             (!$nothide{$uname.':'.$udom})) {
                   9871:                             next;
                   9872:                         }
                   9873:                     }
1.503     raeburn  9874:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9875:                         $status = 'previous';
                   9876:                     } elsif ($start > $now) {
                   9877:                         $status = 'future';
                   9878:                     } else {
                   9879:                         $status = 'active';
                   9880:                     }
1.277     albertel 9881:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9882:                         if ($status eq $type) {
1.420     albertel 9883:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9884:                                 push(@{$$users{$role}{$user}},$type);
                   9885:                             }
1.288     raeburn  9886:                             $match = 1;
                   9887:                         }
                   9888:                     }
1.419     raeburn  9889:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9890:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9891: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9892:                         }
1.420     albertel 9893:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9894:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9895:                         }
1.609     raeburn  9896:                         if (ref($statushash) eq 'HASH') {
                   9897:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9898:                         }
1.275     raeburn  9899:                     }
                   9900:                 }
                   9901:             }
                   9902:         }
1.290     albertel 9903:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9904:             if ((defined($cdom)) && (defined($cnum))) {
                   9905:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9906:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9907:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9908:                     next if ($owner eq '');
                   9909:                     my ($ownername,$ownerdom);
                   9910:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9911:                         $ownername = $1;
                   9912:                         $ownerdom = $2;
                   9913:                     } else {
                   9914:                         $ownername = $owner;
                   9915:                         $ownerdom = $cdom;
                   9916:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9917:                     }
                   9918:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9919:                     if (defined($userdata) && 
1.609     raeburn  9920: 			!exists($$userdata{$owner})) {
                   9921: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9922:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9923:                             push(@{$seclists{$owner}},'none');
                   9924:                         }
                   9925:                         if (ref($statushash) eq 'HASH') {
                   9926:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9927:                         }
1.290     albertel 9928: 		    }
1.279     raeburn  9929:                 }
                   9930:             }
                   9931:         }
1.419     raeburn  9932:         foreach my $user (keys(%seclists)) {
                   9933:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9934:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9935:         }
1.275     raeburn  9936:     }
                   9937:     return;
                   9938: }
                   9939: 
1.288     raeburn  9940: sub get_user_info {
                   9941:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9942:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9943: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9944:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9945:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9946:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9947:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9948:     return;
                   9949: }
1.275     raeburn  9950: 
1.472     raeburn  9951: ###############################################
                   9952: 
                   9953: =pod
                   9954: 
                   9955: =item * &get_user_quota()
                   9956: 
1.1075.2.41  raeburn  9957: Retrieves quota assigned for storage of user files.
                   9958: Default is to report quota for portfolio files.
1.472     raeburn  9959: 
                   9960: Incoming parameters:
                   9961: 1. user's username
                   9962: 2. user's domain
1.1075.2.41  raeburn  9963: 3. quota name - portfolio, author, or course
                   9964:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9965: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9966:    course
1.472     raeburn  9967: 
                   9968: Returns:
1.1075.2.58  raeburn  9969: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9970: 2. (Optional) Type of setting: custom or default
                   9971:    (individually assigned or default for user's 
                   9972:    institutional status).
                   9973: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9974:    or student - types as defined in localenroll::inst_usertypes 
                   9975:    for user's domain, which determines default quota for user.
                   9976: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9977: 
                   9978: If a value has been stored in the user's environment, 
1.536     raeburn  9979: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9980: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9981: 
                   9982: =cut
                   9983: 
                   9984: ###############################################
                   9985: 
                   9986: 
                   9987: sub get_user_quota {
1.1075.2.42  raeburn  9988:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9989:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9990:     if (!defined($udom)) {
                   9991:         $udom = $env{'user.domain'};
                   9992:     }
                   9993:     if (!defined($uname)) {
                   9994:         $uname = $env{'user.name'};
                   9995:     }
                   9996:     if (($udom eq '' || $uname eq '') ||
                   9997:         ($udom eq 'public') && ($uname eq 'public')) {
                   9998:         $quota = 0;
1.536     raeburn  9999:         $quotatype = 'default';
                   10000:         $defquota = 0; 
1.472     raeburn  10001:     } else {
1.536     raeburn  10002:         my $inststatus;
1.1075.2.41  raeburn  10003:         if ($quotaname eq 'course') {
                   10004:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10005:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10006:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10007:             } else {
                   10008:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10009:                 $quota = $cenv{'internal.uploadquota'};
                   10010:             }
1.536     raeburn  10011:         } else {
1.1075.2.41  raeburn  10012:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10013:                 if ($quotaname eq 'author') {
                   10014:                     $quota = $env{'environment.authorquota'};
                   10015:                 } else {
                   10016:                     $quota = $env{'environment.portfolioquota'};
                   10017:                 }
                   10018:                 $inststatus = $env{'environment.inststatus'};
                   10019:             } else {
                   10020:                 my %userenv = 
                   10021:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10022:                                          'authorquota','inststatus'],$udom,$uname);
                   10023:                 my ($tmp) = keys(%userenv);
                   10024:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10025:                     if ($quotaname eq 'author') {
                   10026:                         $quota = $userenv{'authorquota'};
                   10027:                     } else {
                   10028:                         $quota = $userenv{'portfolioquota'};
                   10029:                     }
                   10030:                     $inststatus = $userenv{'inststatus'};
                   10031:                 } else {
                   10032:                     undef(%userenv);
                   10033:                 }
                   10034:             }
                   10035:         }
                   10036:         if ($quota eq '' || wantarray) {
                   10037:             if ($quotaname eq 'course') {
                   10038:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10039:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10040:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10041:                     $defquota = $domdefs{$crstype.'quota'};
                   10042:                 }
                   10043:                 if ($defquota eq '') {
                   10044:                     $defquota = 500;
                   10045:                 }
1.1075.2.41  raeburn  10046:             } else {
                   10047:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10048:             }
                   10049:             if ($quota eq '') {
                   10050:                 $quota = $defquota;
                   10051:                 $quotatype = 'default';
                   10052:             } else {
                   10053:                 $quotatype = 'custom';
                   10054:             }
1.472     raeburn  10055:         }
                   10056:     }
1.536     raeburn  10057:     if (wantarray) {
                   10058:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10059:     } else {
                   10060:         return $quota;
                   10061:     }
1.472     raeburn  10062: }
                   10063: 
                   10064: ###############################################
                   10065: 
                   10066: =pod
                   10067: 
                   10068: =item * &default_quota()
                   10069: 
1.536     raeburn  10070: Retrieves default quota assigned for storage of user portfolio files,
                   10071: given an (optional) user's institutional status.
1.472     raeburn  10072: 
                   10073: Incoming parameters:
1.1075.2.42  raeburn  10074: 
1.472     raeburn  10075: 1. domain
1.536     raeburn  10076: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10077:    status types (e.g., faculty, staff, student etc.)
                   10078:    which apply to the user for whom the default is being retrieved.
                   10079:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10080:    default quota will be returned.
                   10081: 3.  quota name - portfolio, author, or course
                   10082:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10083: 
                   10084: Returns:
1.1075.2.42  raeburn  10085: 
1.1075.2.58  raeburn  10086: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10087: 2. (Optional) institutional type which determined the value of the
                   10088:    default quota.
1.472     raeburn  10089: 
                   10090: If a value has been stored in the domain's configuration db,
                   10091: it will return that, otherwise it returns 20 (for backwards 
                   10092: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10093: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10094: 
1.536     raeburn  10095: If the user's status includes multiple types (e.g., staff and student),
                   10096: the largest default quota which applies to the user determines the
                   10097: default quota returned.
                   10098: 
1.472     raeburn  10099: =cut
                   10100: 
                   10101: ###############################################
                   10102: 
                   10103: 
                   10104: sub default_quota {
1.1075.2.41  raeburn  10105:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10106:     my ($defquota,$settingstatus);
                   10107:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10108:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10109:     my $key = 'defaultquota';
                   10110:     if ($quotaname eq 'author') {
                   10111:         $key = 'authorquota';
                   10112:     }
1.622     raeburn  10113:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10114:         if ($inststatus ne '') {
1.765     raeburn  10115:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10116:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10117:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10118:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10119:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10120:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10121:                             $settingstatus = $item;
1.1075.2.41  raeburn  10122:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10123:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10124:                             $settingstatus = $item;
                   10125:                         }
                   10126:                     }
1.1075.2.41  raeburn  10127:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10128:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10129:                         if ($defquota eq '') {
                   10130:                             $defquota = $quotahash{'quotas'}{$item};
                   10131:                             $settingstatus = $item;
                   10132:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10133:                             $defquota = $quotahash{'quotas'}{$item};
                   10134:                             $settingstatus = $item;
                   10135:                         }
1.536     raeburn  10136:                     }
                   10137:                 }
                   10138:             }
                   10139:         }
                   10140:         if ($defquota eq '') {
1.1075.2.41  raeburn  10141:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10142:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10143:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10144:                 $defquota = $quotahash{'quotas'}{'default'};
                   10145:             }
1.536     raeburn  10146:             $settingstatus = 'default';
1.1075.2.42  raeburn  10147:             if ($defquota eq '') {
                   10148:                 if ($quotaname eq 'author') {
                   10149:                     $defquota = 500;
                   10150:                 }
                   10151:             }
1.536     raeburn  10152:         }
                   10153:     } else {
                   10154:         $settingstatus = 'default';
1.1075.2.41  raeburn  10155:         if ($quotaname eq 'author') {
                   10156:             $defquota = 500;
                   10157:         } else {
                   10158:             $defquota = 20;
                   10159:         }
1.536     raeburn  10160:     }
                   10161:     if (wantarray) {
                   10162:         return ($defquota,$settingstatus);
1.472     raeburn  10163:     } else {
1.536     raeburn  10164:         return $defquota;
1.472     raeburn  10165:     }
                   10166: }
                   10167: 
1.1075.2.41  raeburn  10168: ###############################################
                   10169: 
                   10170: =pod
                   10171: 
1.1075.2.42  raeburn  10172: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  10173: 
                   10174: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  10175: of existing file within authoring space will cause quota for the authoring
                   10176: space to be exceeded.
                   10177: 
                   10178: Same, if upload of a file directly to a course/community via Course Editor
                   10179: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  10180: 
1.1075.2.61  raeburn  10181: Inputs: 7 
1.1075.2.42  raeburn  10182: 1. username or coursenum
1.1075.2.41  raeburn  10183: 2. domain
1.1075.2.42  raeburn  10184: 3. context ('author' or 'course')
1.1075.2.41  raeburn  10185: 4. filename of file for which action is being requested
                   10186: 5. filesize (kB) of file
                   10187: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  10188: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  10189: 
                   10190: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   10191:          otherwise return null.
                   10192: 
1.1075.2.42  raeburn  10193: =back
                   10194: 
1.1075.2.41  raeburn  10195: =cut
                   10196: 
1.1075.2.42  raeburn  10197: sub excess_filesize_warning {
1.1075.2.59  raeburn  10198:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  10199:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  10200:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  10201:     if ($context eq 'author') {
                   10202:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10203:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10204:     } else {
                   10205:         foreach my $subdir ('docs','supplemental') {
                   10206:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10207:         }
                   10208:     }
1.1075.2.41  raeburn  10209:     $disk_quota = int($disk_quota * 1000);
                   10210:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  10211:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  10212:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  10213:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10214:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  10215:                             $disk_quota,$current_disk_usage).
                   10216:                '</p>';
                   10217:     }
                   10218:     return;
                   10219: }
                   10220: 
                   10221: ###############################################
                   10222: 
                   10223: 
1.384     raeburn  10224: sub get_secgrprole_info {
                   10225:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10226:     my %sections_count = &get_sections($cdom,$cnum);
                   10227:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10228:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10229:     my @groups = sort(keys(%curr_groups));
                   10230:     my $allroles = [];
                   10231:     my $rolehash;
                   10232:     my $accesshash = {
                   10233:                      active => 'Currently has access',
                   10234:                      future => 'Will have future access',
                   10235:                      previous => 'Previously had access',
                   10236:                   };
                   10237:     if ($needroles) {
                   10238:         $rolehash = {'all' => 'all'};
1.385     albertel 10239:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10240: 	if (&Apache::lonnet::error(%user_roles)) {
                   10241: 	    undef(%user_roles);
                   10242: 	}
                   10243:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10244:             my ($role)=split(/\:/,$item,2);
                   10245:             if ($role eq 'cr') { next; }
                   10246:             if ($role =~ /^cr/) {
                   10247:                 $$rolehash{$role} = (split('/',$role))[3];
                   10248:             } else {
                   10249:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10250:             }
                   10251:         }
                   10252:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10253:             push(@{$allroles},$key);
                   10254:         }
                   10255:         push (@{$allroles},'st');
                   10256:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10257:     }
                   10258:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10259: }
                   10260: 
1.555     raeburn  10261: sub user_picker {
1.1075.2.127  raeburn  10262:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10263:     my $currdom = $dom;
1.1075.2.114  raeburn  10264:     my @alldoms = &Apache::lonnet::all_domains();
                   10265:     if (@alldoms == 1) {
                   10266:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10267:                                                ['directorysrch'],$alldoms[0]);
                   10268:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10269:         my $showdom = $domdesc;
                   10270:         if ($showdom eq '') {
                   10271:             $showdom = $dom;
                   10272:         }
                   10273:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10274:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10275:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10276:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10277:             }
                   10278:         }
                   10279:     }
1.555     raeburn  10280:     my %curr_selected = (
                   10281:                         srchin => 'dom',
1.580     raeburn  10282:                         srchby => 'lastname',
1.555     raeburn  10283:                       );
                   10284:     my $srchterm;
1.625     raeburn  10285:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10286:         if ($srch->{'srchby'} ne '') {
                   10287:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10288:         }
                   10289:         if ($srch->{'srchin'} ne '') {
                   10290:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10291:         }
                   10292:         if ($srch->{'srchtype'} ne '') {
                   10293:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10294:         }
                   10295:         if ($srch->{'srchdomain'} ne '') {
                   10296:             $currdom = $srch->{'srchdomain'};
                   10297:         }
                   10298:         $srchterm = $srch->{'srchterm'};
                   10299:     }
1.1075.2.98  raeburn  10300:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10301:                     'usr'       => 'Search criteria',
1.563     raeburn  10302:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10303:                     'uname'     => 'username',
                   10304:                     'lastname'  => 'last name',
1.555     raeburn  10305:                     'lastfirst' => 'last name, first name',
1.558     albertel 10306:                     'crs'       => 'in this course',
1.576     raeburn  10307:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10308:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10309:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10310:                     'exact'     => 'is',
                   10311:                     'contains'  => 'contains',
1.569     raeburn  10312:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  10313:                                        );
                   10314:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10315:                     'youm'      => "You must include some text to search for.",
                   10316:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10317:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10318:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10319:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10320:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10321:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10322:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10323:                                        );
1.1075.2.98  raeburn  10324:     &html_escape(\%html_lt);
                   10325:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  10326:     my $domform;
1.1075.2.126  raeburn  10327:     my $allow_blank = 1;
1.1075.2.115  raeburn  10328:     if ($fixeddom) {
1.1075.2.126  raeburn  10329:         $allow_blank = 0;
                   10330:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  10331:     } else {
1.1075.2.126  raeburn  10332:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  10333:     }
1.563     raeburn  10334:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10335: 
                   10336:     my @srchins = ('crs','dom','alc','instd');
                   10337: 
                   10338:     foreach my $option (@srchins) {
                   10339:         # FIXME 'alc' option unavailable until 
                   10340:         #       loncreateuser::print_user_query_page()
                   10341:         #       has been completed.
                   10342:         next if ($option eq 'alc');
1.880     raeburn  10343:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10344:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  10345:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10346:         if ($curr_selected{'srchin'} eq $option) {
                   10347:             $srchinsel .= ' 
1.1075.2.98  raeburn  10348:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10349:         } else {
                   10350:             $srchinsel .= '
1.1075.2.98  raeburn  10351:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10352:         }
1.555     raeburn  10353:     }
1.563     raeburn  10354:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10355: 
                   10356:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10357:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10358:         if ($curr_selected{'srchby'} eq $option) {
                   10359:             $srchbysel .= '
1.1075.2.98  raeburn  10360:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10361:         } else {
                   10362:             $srchbysel .= '
1.1075.2.98  raeburn  10363:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10364:          }
                   10365:     }
                   10366:     $srchbysel .= "\n  </select>\n";
                   10367: 
                   10368:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10369:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10370:         if ($curr_selected{'srchtype'} eq $option) {
                   10371:             $srchtypesel .= '
1.1075.2.98  raeburn  10372:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10373:         } else {
                   10374:             $srchtypesel .= '
1.1075.2.98  raeburn  10375:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10376:         }
                   10377:     }
                   10378:     $srchtypesel .= "\n  </select>\n";
                   10379: 
1.558     albertel 10380:     my ($newuserscript,$new_user_create);
1.994     raeburn  10381:     my $context_dom = $env{'request.role.domain'};
                   10382:     if ($context eq 'requestcrs') {
                   10383:         if ($env{'form.coursedom'} ne '') { 
                   10384:             $context_dom = $env{'form.coursedom'};
                   10385:         }
                   10386:     }
1.556     raeburn  10387:     if ($forcenewuser) {
1.576     raeburn  10388:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10389:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10390:                 if ($cancreate) {
                   10391:                     $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>';
                   10392:                 } else {
1.799     bisitz   10393:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10394:                     my %usertypetext = (
                   10395:                         official   => 'institutional',
                   10396:                         unofficial => 'non-institutional',
                   10397:                     );
1.799     bisitz   10398:                     $new_user_create = '<p class="LC_warning">'
                   10399:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10400:                                       .' '
                   10401:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10402:                                           ,'<a href="'.$helplink.'">','</a>')
                   10403:                                       .'</p><br />';
1.627     raeburn  10404:                 }
1.576     raeburn  10405:             }
                   10406:         }
                   10407: 
1.556     raeburn  10408:         $newuserscript = <<"ENDSCRIPT";
                   10409: 
1.570     raeburn  10410: function setSearch(createnew,callingForm) {
1.556     raeburn  10411:     if (createnew == 1) {
1.570     raeburn  10412:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10413:             if (callingForm.srchby.options[i].value == 'uname') {
                   10414:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10415:             }
                   10416:         }
1.570     raeburn  10417:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10418:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10419: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10420:             }
                   10421:         }
1.570     raeburn  10422:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10423:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10424:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10425:             }
                   10426:         }
1.570     raeburn  10427:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10428:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10429:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10430:             }
                   10431:         }
                   10432:     }
                   10433: }
                   10434: ENDSCRIPT
1.558     albertel 10435: 
1.556     raeburn  10436:     }
                   10437: 
1.555     raeburn  10438:     my $output = <<"END_BLOCK";
1.556     raeburn  10439: <script type="text/javascript">
1.824     bisitz   10440: // <![CDATA[
1.570     raeburn  10441: function validateEntry(callingForm) {
1.558     albertel 10442: 
1.556     raeburn  10443:     var checkok = 1;
1.558     albertel 10444:     var srchin;
1.570     raeburn  10445:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10446: 	if ( callingForm.srchin[i].checked ) {
                   10447: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10448: 	}
                   10449:     }
                   10450: 
1.570     raeburn  10451:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10452:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10453:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10454:     var srchterm =  callingForm.srchterm.value;
                   10455:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10456:     var msg = "";
                   10457: 
                   10458:     if (srchterm == "") {
                   10459:         checkok = 0;
1.1075.2.98  raeburn  10460:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10461:     }
                   10462: 
1.569     raeburn  10463:     if (srchtype== 'begins') {
                   10464:         if (srchterm.length < 2) {
                   10465:             checkok = 0;
1.1075.2.98  raeburn  10466:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10467:         }
                   10468:     }
                   10469: 
1.556     raeburn  10470:     if (srchtype== 'contains') {
                   10471:         if (srchterm.length < 3) {
                   10472:             checkok = 0;
1.1075.2.98  raeburn  10473:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10474:         }
                   10475:     }
                   10476:     if (srchin == 'instd') {
                   10477:         if (srchdomain == '') {
                   10478:             checkok = 0;
1.1075.2.98  raeburn  10479:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10480:         }
                   10481:     }
                   10482:     if (srchin == 'dom') {
                   10483:         if (srchdomain == '') {
                   10484:             checkok = 0;
1.1075.2.98  raeburn  10485:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10486:         }
                   10487:     }
                   10488:     if (srchby == 'lastfirst') {
                   10489:         if (srchterm.indexOf(",") == -1) {
                   10490:             checkok = 0;
1.1075.2.98  raeburn  10491:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10492:         }
                   10493:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10494:             checkok = 0;
1.1075.2.98  raeburn  10495:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10496:         }
                   10497:     }
                   10498:     if (checkok == 0) {
1.1075.2.98  raeburn  10499:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10500:         return;
                   10501:     }
                   10502:     if (checkok == 1) {
1.570     raeburn  10503:         callingForm.submit();
1.556     raeburn  10504:     }
                   10505: }
                   10506: 
                   10507: $newuserscript
                   10508: 
1.824     bisitz   10509: // ]]>
1.556     raeburn  10510: </script>
1.558     albertel 10511: 
                   10512: $new_user_create
                   10513: 
1.555     raeburn  10514: END_BLOCK
1.558     albertel 10515: 
1.876     raeburn  10516:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10517:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10518:                $domform.
                   10519:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10520:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10521:                $srchbysel.
                   10522:                $srchtypesel. 
                   10523:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10524:                $srchinsel.
                   10525:                &Apache::lonhtmlcommon::row_closure(1). 
                   10526:                &Apache::lonhtmlcommon::end_pick_box().
                   10527:                '<br />';
1.1075.2.114  raeburn  10528:     return ($output,1);
1.555     raeburn  10529: }
                   10530: 
1.612     raeburn  10531: sub user_rule_check {
1.615     raeburn  10532:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10533:     my ($response,%inst_response);
1.612     raeburn  10534:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10535:         if (keys(%{$usershash}) > 1) {
                   10536:             my (%by_username,%by_id,%userdoms);
                   10537:             my $checkid;
1.612     raeburn  10538:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10539:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10540:                     $checkid = 1;
                   10541:                 }
                   10542:             }
                   10543:             foreach my $user (keys(%{$usershash})) {
                   10544:                 my ($uname,$udom) = split(/:/,$user);
                   10545:                 if ($checkid) {
                   10546:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10547:                         if ($usershash->{$user}->{'id'} ne '') {
                   10548:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10549:                             $userdoms{$udom} = 1;
                   10550:                             if (ref($inst_results) eq 'HASH') {
                   10551:                                 $inst_results->{$uname.':'.$udom} = {};
                   10552:                             }
                   10553:                         }
                   10554:                     }
                   10555:                 } else {
                   10556:                     $by_username{$udom}{$uname} = 1;
                   10557:                     $userdoms{$udom} = 1;
                   10558:                     if (ref($inst_results) eq 'HASH') {
                   10559:                         $inst_results->{$uname.':'.$udom} = {};
                   10560:                     }
                   10561:                 }
                   10562:             }
                   10563:             foreach my $udom (keys(%userdoms)) {
                   10564:                 if (!$got_rules->{$udom}) {
                   10565:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10566:                                                              ['usercreation'],$udom);
                   10567:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10568:                         foreach my $item ('username','id') {
                   10569:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10570:                                 $$curr_rules{$udom}{$item} =
                   10571:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10572:                             }
                   10573:                         }
                   10574:                     }
                   10575:                     $got_rules->{$udom} = 1;
                   10576:                 }
                   10577:             }
                   10578:             if ($checkid) {
                   10579:                 foreach my $udom (keys(%by_id)) {
                   10580:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10581:                     if ($outcome eq 'ok') {
                   10582:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10583:                             my $uname = $by_id{$udom}{$id};
                   10584:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10585:                         }
                   10586:                         if (ref($results) eq 'HASH') {
                   10587:                             foreach my $uname (keys(%{$results})) {
                   10588:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10589:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10590:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10591:                                 }
                   10592:                             }
                   10593:                         }
                   10594:                     }
1.612     raeburn  10595:                 }
1.615     raeburn  10596:             } else {
1.1075.2.99  raeburn  10597:                 foreach my $udom (keys(%by_username)) {
                   10598:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10599:                     if ($outcome eq 'ok') {
                   10600:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10601:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10602:                         }
                   10603:                         if (ref($results) eq 'HASH') {
                   10604:                             foreach my $uname (keys(%{$results})) {
                   10605:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10606:                             }
                   10607:                         }
                   10608:                     }
                   10609:                 }
1.612     raeburn  10610:             }
1.1075.2.99  raeburn  10611:         } elsif (keys(%{$usershash}) == 1) {
                   10612:             my $user = (keys(%{$usershash}))[0];
                   10613:             my ($uname,$udom) = split(/:/,$user);
                   10614:             if (($udom ne '') && ($uname ne '')) {
                   10615:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10616:                     if (ref($checks) eq 'HASH') {
                   10617:                         if (defined($checks->{'username'})) {
                   10618:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10619:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10620:                         } elsif (defined($checks->{'id'})) {
                   10621:                             if ($usershash->{$user}->{'id'} ne '') {
                   10622:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10623:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10624:                                                                   $usershash->{$user}->{'id'});
                   10625:                             } else {
                   10626:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10627:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10628:                             }
                   10629:                         }
                   10630:                     } else {
                   10631:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10632:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10633:                        return;
                   10634:                     }
                   10635:                     if (!$got_rules->{$udom}) {
                   10636:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10637:                                                                  ['usercreation'],$udom);
                   10638:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10639:                             foreach my $item ('username','id') {
                   10640:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10641:                                    $$curr_rules{$udom}{$item} =
                   10642:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10643:                                 }
                   10644:                             }
1.585     raeburn  10645:                         }
1.1075.2.99  raeburn  10646:                         $got_rules->{$udom} = 1;
1.585     raeburn  10647:                     }
                   10648:                 }
1.1075.2.99  raeburn  10649:             } else {
                   10650:                 return;
                   10651:             }
                   10652:         } else {
                   10653:             return;
                   10654:         }
                   10655:         foreach my $user (keys(%{$usershash})) {
                   10656:             my ($uname,$udom) = split(/:/,$user);
                   10657:             next if (($udom eq '') || ($uname eq ''));
                   10658:             my $id;
                   10659:             if (ref($inst_results) eq 'HASH') {
                   10660:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10661:                     $id = $inst_results->{$user}->{'id'};
                   10662:                 }
                   10663:             }
                   10664:             if ($id eq '') {
                   10665:                 if (ref($usershash->{$user})) {
                   10666:                     $id = $usershash->{$user}->{'id'};
                   10667:                 }
1.585     raeburn  10668:             }
1.612     raeburn  10669:             foreach my $item (keys(%{$checks})) {
                   10670:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10671:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10672:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10673:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10674:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10675:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10676:                                 if ($rule_check{$rule}) {
                   10677:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10678:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10679:                                         if (ref($inst_results) eq 'HASH') {
                   10680:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10681:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10682:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10683:                                                 } elsif ($item eq 'id') {
                   10684:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10685:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10686:                                                     }
1.615     raeburn  10687:                                                 }
1.612     raeburn  10688:                                             }
                   10689:                                         }
1.615     raeburn  10690:                                     }
                   10691:                                     last;
1.585     raeburn  10692:                                 }
                   10693:                             }
                   10694:                         }
                   10695:                     }
                   10696:                 }
                   10697:             }
                   10698:         }
                   10699:     }
1.612     raeburn  10700:     return;
                   10701: }
                   10702: 
                   10703: sub user_rule_formats {
                   10704:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10705:     my %text = ( 
                   10706:                  'username' => 'Usernames',
                   10707:                  'id'       => 'IDs',
                   10708:                );
                   10709:     my $output;
                   10710:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10711:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10712:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10713:             $output = '<br />'.
                   10714:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10715:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10716:                       ' <ul>';
1.612     raeburn  10717:             foreach my $rule (@{$ruleorder}) {
                   10718:                 if (ref($curr_rules) eq 'ARRAY') {
                   10719:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10720:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10721:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10722:                                         $rules->{$rule}{'desc'}.'</li>';
                   10723:                         }
                   10724:                     }
                   10725:                 }
                   10726:             }
                   10727:             $output .= '</ul>';
                   10728:         }
                   10729:     }
                   10730:     return $output;
                   10731: }
                   10732: 
                   10733: sub instrule_disallow_msg {
1.615     raeburn  10734:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10735:     my $response;
                   10736:     my %text = (
                   10737:                   item   => 'username',
                   10738:                   items  => 'usernames',
                   10739:                   match  => 'matches',
                   10740:                   do     => 'does',
                   10741:                   action => 'a username',
                   10742:                   one    => 'one',
                   10743:                );
                   10744:     if ($count > 1) {
                   10745:         $text{'item'} = 'usernames';
                   10746:         $text{'match'} ='match';
                   10747:         $text{'do'} = 'do';
                   10748:         $text{'action'} = 'usernames',
                   10749:         $text{'one'} = 'ones';
                   10750:     }
                   10751:     if ($checkitem eq 'id') {
                   10752:         $text{'items'} = 'IDs';
                   10753:         $text{'item'} = 'ID';
                   10754:         $text{'action'} = 'an ID';
1.615     raeburn  10755:         if ($count > 1) {
                   10756:             $text{'item'} = 'IDs';
                   10757:             $text{'action'} = 'IDs';
                   10758:         }
1.612     raeburn  10759:     }
1.674     bisitz   10760:     $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  10761:     if ($mode eq 'upload') {
                   10762:         if ($checkitem eq 'username') {
                   10763:             $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'}.");
                   10764:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10765:             $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  10766:         }
1.669     raeburn  10767:     } elsif ($mode eq 'selfcreate') {
                   10768:         if ($checkitem eq 'id') {
                   10769:             $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.");
                   10770:         }
1.615     raeburn  10771:     } else {
                   10772:         if ($checkitem eq 'username') {
                   10773:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10774:         } elsif ($checkitem eq 'id') {
                   10775:             $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.");
                   10776:         }
1.612     raeburn  10777:     }
                   10778:     return $response;
1.585     raeburn  10779: }
                   10780: 
1.624     raeburn  10781: sub personal_data_fieldtitles {
                   10782:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10783:                         id => 'Student/Employee ID',
                   10784:                         permanentemail => 'E-mail address',
                   10785:                         lastname => 'Last Name',
                   10786:                         firstname => 'First Name',
                   10787:                         middlename => 'Middle Name',
                   10788:                         generation => 'Generation',
                   10789:                         gen => 'Generation',
1.765     raeburn  10790:                         inststatus => 'Affiliation',
1.624     raeburn  10791:                    );
                   10792:     return %fieldtitles;
                   10793: }
                   10794: 
1.642     raeburn  10795: sub sorted_inst_types {
                   10796:     my ($dom) = @_;
1.1075.2.70  raeburn  10797:     my ($usertypes,$order);
                   10798:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10799:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10800:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10801:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10802:     } else {
                   10803:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10804:     }
1.642     raeburn  10805:     my $othertitle = &mt('All users');
                   10806:     if ($env{'request.course.id'}) {
1.668     raeburn  10807:         $othertitle  = &mt('Any users');
1.642     raeburn  10808:     }
                   10809:     my @types;
                   10810:     if (ref($order) eq 'ARRAY') {
                   10811:         @types = @{$order};
                   10812:     }
                   10813:     if (@types == 0) {
                   10814:         if (ref($usertypes) eq 'HASH') {
                   10815:             @types = sort(keys(%{$usertypes}));
                   10816:         }
                   10817:     }
                   10818:     if (keys(%{$usertypes}) > 0) {
                   10819:         $othertitle = &mt('Other users');
                   10820:     }
                   10821:     return ($othertitle,$usertypes,\@types);
                   10822: }
                   10823: 
1.645     raeburn  10824: sub get_institutional_codes {
1.1075.2.157  raeburn  10825:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  10826: # Get complete list of course sections to update
                   10827:     my @currsections = ();
                   10828:     my @currxlists = ();
1.1075.2.157  raeburn  10829:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  10830:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  10831:     my $crskey = $crs.':'.$coursecode;
                   10832:     @{$unclutteredsec{$crskey}} = ();
                   10833:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  10834: 
                   10835:     if ($$settings{'internal.sectionnums'} ne '') {
                   10836:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10837:     }
                   10838: 
                   10839:     if ($$settings{'internal.crosslistings'} ne '') {
                   10840:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10841:     }
                   10842: 
                   10843:     if (@currxlists > 0) {
1.1075.2.157  raeburn  10844:         foreach my $xl (@currxlists) {
                   10845:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  10846:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10847:                     push(@{$allcourses},$1);
1.645     raeburn  10848:                     $$LC_code{$1} = $2;
                   10849:                 }
                   10850:             }
                   10851:         }
                   10852:     }
1.1075.2.157  raeburn  10853: 
1.645     raeburn  10854:     if (@currsections > 0) {
1.1075.2.157  raeburn  10855:         foreach my $sec (@currsections) {
                   10856:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   10857:                 my $instsec = $1;
1.645     raeburn  10858:                 my $lc_sec = $2;
1.1075.2.157  raeburn  10859:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   10860:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   10861:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   10862:                 }
                   10863:             }
                   10864:         }
                   10865:     }
                   10866: 
                   10867:     if (@{$unclutteredsec{$crskey}} > 0) {
                   10868:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   10869:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   10870:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   10871:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   10872:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  10873:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  10874:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  10875:                 }
                   10876:             }
                   10877:         }
                   10878:     }
                   10879:     return;
                   10880: }
                   10881: 
1.971     raeburn  10882: sub get_standard_codeitems {
                   10883:     return ('Year','Semester','Department','Number','Section');
                   10884: }
                   10885: 
1.112     bowersj2 10886: =pod
                   10887: 
1.780     raeburn  10888: =head1 Slot Helpers
                   10889: 
                   10890: =over 4
                   10891: 
                   10892: =item * sorted_slots()
                   10893: 
1.1040    raeburn  10894: Sorts an array of slot names in order of an optional sort key,
                   10895: default sort is by slot start time (earliest first). 
1.780     raeburn  10896: 
                   10897: Inputs:
                   10898: 
                   10899: =over 4
                   10900: 
                   10901: slotsarr  - Reference to array of unsorted slot names.
                   10902: 
                   10903: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10904: 
1.1040    raeburn  10905: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10906: 
1.549     albertel 10907: =back
                   10908: 
1.780     raeburn  10909: Returns:
                   10910: 
                   10911: =over 4
                   10912: 
1.1040    raeburn  10913: sorted   - An array of slot names sorted by a specified sort key 
                   10914:            (default sort key is start time of the slot).
1.780     raeburn  10915: 
                   10916: =back
                   10917: 
                   10918: =cut
                   10919: 
                   10920: 
                   10921: sub sorted_slots {
1.1040    raeburn  10922:     my ($slotsarr,$slots,$sortkey) = @_;
                   10923:     if ($sortkey eq '') {
                   10924:         $sortkey = 'starttime';
                   10925:     }
1.780     raeburn  10926:     my @sorted;
                   10927:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10928:         @sorted =
                   10929:             sort {
                   10930:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10931:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10932:                      }
                   10933:                      if (ref($slots->{$a})) { return -1;}
                   10934:                      if (ref($slots->{$b})) { return 1;}
                   10935:                      return 0;
                   10936:                  } @{$slotsarr};
                   10937:     }
                   10938:     return @sorted;
                   10939: }
                   10940: 
1.1040    raeburn  10941: =pod
                   10942: 
                   10943: =item * get_future_slots()
                   10944: 
                   10945: Inputs:
                   10946: 
                   10947: =over 4
                   10948: 
                   10949: cnum - course number
                   10950: 
                   10951: cdom - course domain
                   10952: 
                   10953: now - current UNIX time
                   10954: 
                   10955: symb - optional symb
                   10956: 
                   10957: =back
                   10958: 
                   10959: Returns:
                   10960: 
                   10961: =over 4
                   10962: 
                   10963: sorted_reservable - ref to array of student_schedulable slots currently 
                   10964:                     reservable, ordered by end date of reservation period.
                   10965: 
                   10966: reservable_now - ref to hash of student_schedulable slots currently
                   10967:                  reservable.
                   10968: 
                   10969:     Keys in inner hash are:
                   10970:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10971:     (b) endreserve: end date of reservation period.
                   10972:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10973:         selected.
1.1040    raeburn  10974: 
                   10975: sorted_future - ref to array of student_schedulable slots reservable in
                   10976:                 the future, ordered by start date of reservation period.
                   10977: 
                   10978: future_reservable - ref to hash of student_schedulable slots reservable
                   10979:                     in the future.
                   10980: 
                   10981:     Keys in inner hash are:
                   10982:     (a) symb: either blank or symb to which slot use is restricted.
                   10983:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10984:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10985:         selected.
1.1040    raeburn  10986: 
                   10987: =back
                   10988: 
                   10989: =cut
                   10990: 
                   10991: sub get_future_slots {
                   10992:     my ($cnum,$cdom,$now,$symb) = @_;
                   10993:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10994:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10995:     foreach my $slot (keys(%slots)) {
                   10996:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10997:         if ($symb) {
                   10998:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10999:                      ($slots{$slot}->{'symb'} ne $symb));
                   11000:         }
                   11001:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11002:             ($slots{$slot}->{'endtime'} > $now)) {
                   11003:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11004:                 my $userallowed = 0;
                   11005:                 if ($slots{$slot}->{'allowedsections'}) {
                   11006:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11007:                     if (!defined($env{'request.role.sec'})
                   11008:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11009:                         $userallowed=1;
                   11010:                     } else {
                   11011:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11012:                             $userallowed=1;
                   11013:                         }
                   11014:                     }
                   11015:                     unless ($userallowed) {
                   11016:                         if (defined($env{'request.course.groups'})) {
                   11017:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11018:                             foreach my $group (@groups) {
                   11019:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11020:                                     $userallowed=1;
                   11021:                                     last;
                   11022:                                 }
                   11023:                             }
                   11024:                         }
                   11025:                     }
                   11026:                 }
                   11027:                 if ($slots{$slot}->{'allowedusers'}) {
                   11028:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11029:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11030:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11031:                         $userallowed = 1;
                   11032:                     }
                   11033:                 }
                   11034:                 next unless($userallowed);
                   11035:             }
                   11036:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11037:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11038:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11039:             my $uniqueperiod;
                   11040:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11041:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11042:             }
1.1040    raeburn  11043:             if (($startreserve < $now) &&
                   11044:                 (!$endreserve || $endreserve > $now)) {
                   11045:                 my $lastres = $endreserve;
                   11046:                 if (!$lastres) {
                   11047:                     $lastres = $slots{$slot}->{'starttime'};
                   11048:                 }
                   11049:                 $reservable_now{$slot} = {
                   11050:                                            symb       => $symb,
1.1075.2.104  raeburn  11051:                                            endreserve => $lastres,
                   11052:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11053:                                          };
                   11054:             } elsif (($startreserve > $now) &&
                   11055:                      (!$endreserve || $endreserve > $startreserve)) {
                   11056:                 $future_reservable{$slot} = {
                   11057:                                               symb         => $symb,
1.1075.2.104  raeburn  11058:                                               startreserve => $startreserve,
                   11059:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11060:                                             };
                   11061:             }
                   11062:         }
                   11063:     }
                   11064:     my @unsorted_reservable = keys(%reservable_now);
                   11065:     if (@unsorted_reservable > 0) {
                   11066:         @sorted_reservable = 
                   11067:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11068:     }
                   11069:     my @unsorted_future = keys(%future_reservable);
                   11070:     if (@unsorted_future > 0) {
                   11071:         @sorted_future =
                   11072:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11073:     }
                   11074:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11075: }
1.780     raeburn  11076: 
                   11077: =pod
                   11078: 
1.1057    foxr     11079: =back
                   11080: 
1.549     albertel 11081: =head1 HTTP Helpers
                   11082: 
                   11083: =over 4
                   11084: 
1.648     raeburn  11085: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11086: 
1.258     albertel 11087: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11088: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11089: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11090: 
                   11091: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11092: $possible_names is an ref to an array of form element names.  As an example:
                   11093: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11094: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11095: 
                   11096: =cut
1.1       albertel 11097: 
1.6       albertel 11098: sub get_unprocessed_cgi {
1.25      albertel 11099:   my ($query,$possible_names)= @_;
1.26      matthew  11100:   # $Apache::lonxml::debug=1;
1.356     albertel 11101:   foreach my $pair (split(/&/,$query)) {
                   11102:     my ($name, $value) = split(/=/,$pair);
1.369     www      11103:     $name = &unescape($name);
1.25      albertel 11104:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11105:       $value =~ tr/+/ /;
                   11106:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11107:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11108:     }
1.16      harris41 11109:   }
1.6       albertel 11110: }
                   11111: 
1.112     bowersj2 11112: =pod
                   11113: 
1.648     raeburn  11114: =item * &cacheheader() 
1.112     bowersj2 11115: 
                   11116: returns cache-controlling header code
                   11117: 
                   11118: =cut
                   11119: 
1.7       albertel 11120: sub cacheheader {
1.258     albertel 11121:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11122:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11123:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11124:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11125:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11126:     return $output;
1.7       albertel 11127: }
                   11128: 
1.112     bowersj2 11129: =pod
                   11130: 
1.648     raeburn  11131: =item * &no_cache($r) 
1.112     bowersj2 11132: 
                   11133: specifies header code to not have cache
                   11134: 
                   11135: =cut
                   11136: 
1.9       albertel 11137: sub no_cache {
1.216     albertel 11138:     my ($r) = @_;
                   11139:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11140: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11141:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11142:     $r->no_cache(1);
                   11143:     $r->header_out("Expires" => $date);
                   11144:     $r->header_out("Pragma" => "no-cache");
1.123     www      11145: }
                   11146: 
                   11147: sub content_type {
1.181     albertel 11148:     my ($r,$type,$charset) = @_;
1.299     foxr     11149:     if ($r) {
                   11150: 	#  Note that printout.pl calls this with undef for $r.
                   11151: 	&no_cache($r);
                   11152:     }
1.258     albertel 11153:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11154:     unless ($charset) {
                   11155: 	$charset=&Apache::lonlocal::current_encoding;
                   11156:     }
                   11157:     if ($charset) { $type.='; charset='.$charset; }
                   11158:     if ($r) {
                   11159: 	$r->content_type($type);
                   11160:     } else {
                   11161: 	print("Content-type: $type\n\n");
                   11162:     }
1.9       albertel 11163: }
1.25      albertel 11164: 
1.112     bowersj2 11165: =pod
                   11166: 
1.648     raeburn  11167: =item * &add_to_env($name,$value) 
1.112     bowersj2 11168: 
1.258     albertel 11169: adds $name to the %env hash with value
1.112     bowersj2 11170: $value, if $name already exists, the entry is converted to an array
                   11171: reference and $value is added to the array.
                   11172: 
                   11173: =cut
                   11174: 
1.25      albertel 11175: sub add_to_env {
                   11176:   my ($name,$value)=@_;
1.258     albertel 11177:   if (defined($env{$name})) {
                   11178:     if (ref($env{$name})) {
1.25      albertel 11179:       #already have multiple values
1.258     albertel 11180:       push(@{ $env{$name} },$value);
1.25      albertel 11181:     } else {
                   11182:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11183:       my $first=$env{$name};
                   11184:       undef($env{$name});
                   11185:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11186:     }
                   11187:   } else {
1.258     albertel 11188:     $env{$name}=$value;
1.25      albertel 11189:   }
1.31      albertel 11190: }
1.149     albertel 11191: 
                   11192: =pod
                   11193: 
1.648     raeburn  11194: =item * &get_env_multiple($name) 
1.149     albertel 11195: 
1.258     albertel 11196: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11197: values may be defined and end up as an array ref.
                   11198: 
                   11199: returns an array of values
                   11200: 
                   11201: =cut
                   11202: 
                   11203: sub get_env_multiple {
                   11204:     my ($name) = @_;
                   11205:     my @values;
1.258     albertel 11206:     if (defined($env{$name})) {
1.149     albertel 11207:         # exists is it an array
1.258     albertel 11208:         if (ref($env{$name})) {
                   11209:             @values=@{ $env{$name} };
1.149     albertel 11210:         } else {
1.258     albertel 11211:             $values[0]=$env{$name};
1.149     albertel 11212:         }
                   11213:     }
                   11214:     return(@values);
                   11215: }
                   11216: 
1.660     raeburn  11217: sub ask_for_embedded_content {
                   11218:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11219:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  11220:         %currsubfile,%unused,$rem);
1.1071    raeburn  11221:     my $counter = 0;
                   11222:     my $numnew = 0;
1.987     raeburn  11223:     my $numremref = 0;
                   11224:     my $numinvalid = 0;
                   11225:     my $numpathchg = 0;
                   11226:     my $numexisting = 0;
1.1071    raeburn  11227:     my $numunused = 0;
                   11228:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  11229:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11230:     my $heading = &mt('Upload embedded files');
                   11231:     my $buttontext = &mt('Upload');
                   11232: 
1.1075.2.11  raeburn  11233:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  11234:         if ($actionurl eq '/adm/dependencies') {
                   11235:             $navmap = Apache::lonnavmaps::navmap->new();
                   11236:         }
                   11237:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11238:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  11239:     }
1.1075.2.35  raeburn  11240:     if (($actionurl eq '/adm/portfolio') ||
                   11241:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11242:         my $current_path='/';
                   11243:         if ($env{'form.currentpath'}) {
                   11244:             $current_path = $env{'form.currentpath'};
                   11245:         }
                   11246:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  11247:             $udom = $cdom;
                   11248:             $uname = $cnum;
1.984     raeburn  11249:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11250:         } else {
                   11251:             $udom = $env{'user.domain'};
                   11252:             $uname = $env{'user.name'};
                   11253:             $url = '/userfiles/portfolio';
                   11254:         }
1.987     raeburn  11255:         $toplevel = $url.'/';
1.984     raeburn  11256:         $url .= $current_path;
                   11257:         $getpropath = 1;
1.987     raeburn  11258:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11259:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11260:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11261:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11262:         $toplevel = $url;
1.984     raeburn  11263:         if ($rest ne '') {
1.987     raeburn  11264:             $url .= $rest;
                   11265:         }
                   11266:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11267:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11268:             $url = $args->{'docs_url'};
                   11269:             $toplevel = $url;
1.1075.2.11  raeburn  11270:             if ($args->{'context'} eq 'paste') {
                   11271:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11272:                 ($path) =
                   11273:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11274:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11275:                 $fileloc =~ s{^/}{};
                   11276:             }
1.1071    raeburn  11277:         }
                   11278:     } elsif ($actionurl eq '/adm/dependencies') {
                   11279:         if ($env{'request.course.id'} ne '') {
                   11280:             if (ref($args) eq 'HASH') {
                   11281:                 $url = $args->{'docs_url'};
                   11282:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  11283:                 $toplevel = $url;
                   11284:                 unless ($toplevel =~ m{^/}) {
                   11285:                     $toplevel = "/$url";
                   11286:                 }
1.1075.2.11  raeburn  11287:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  11288:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11289:                     $path = $1;
                   11290:                 } else {
                   11291:                     ($path) =
                   11292:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11293:                 }
1.1075.2.79  raeburn  11294:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11295:                     $fileloc = $toplevel;
                   11296:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11297:                     my ($udom,$uname,$fname) =
                   11298:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11299:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11300:                 } else {
                   11301:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11302:                 }
1.1071    raeburn  11303:                 $fileloc =~ s{^/}{};
                   11304:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11305:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11306:             }
1.987     raeburn  11307:         }
1.1075.2.35  raeburn  11308:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11309:         $udom = $cdom;
                   11310:         $uname = $cnum;
                   11311:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11312:         $toplevel = $url;
                   11313:         $path = $url;
                   11314:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11315:         $fileloc =~ s{^/}{};
                   11316:     }
                   11317:     foreach my $file (keys(%{$allfiles})) {
                   11318:         my $embed_file;
                   11319:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11320:             $embed_file = $1;
                   11321:         } else {
                   11322:             $embed_file = $file;
                   11323:         }
1.1075.2.55  raeburn  11324:         my ($absolutepath,$cleaned_file);
                   11325:         if ($embed_file =~ m{^\w+://}) {
                   11326:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  11327:             $newfiles{$cleaned_file} = 1;
                   11328:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11329:         } else {
1.1075.2.55  raeburn  11330:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11331:             if ($embed_file =~ m{^/}) {
                   11332:                 $absolutepath = $embed_file;
                   11333:             }
1.1075.2.47  raeburn  11334:             if ($cleaned_file =~ m{/}) {
                   11335:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11336:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11337:                 my $item = $fname;
                   11338:                 if ($path ne '') {
                   11339:                     $item = $path.'/'.$fname;
                   11340:                     $subdependencies{$path}{$fname} = 1;
                   11341:                 } else {
                   11342:                     $dependencies{$item} = 1;
                   11343:                 }
                   11344:                 if ($absolutepath) {
                   11345:                     $mapping{$item} = $absolutepath;
                   11346:                 } else {
                   11347:                     $mapping{$item} = $embed_file;
                   11348:                 }
                   11349:             } else {
                   11350:                 $dependencies{$embed_file} = 1;
                   11351:                 if ($absolutepath) {
1.1075.2.47  raeburn  11352:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11353:                 } else {
1.1075.2.47  raeburn  11354:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11355:                 }
                   11356:             }
1.984     raeburn  11357:         }
                   11358:     }
1.1071    raeburn  11359:     my $dirptr = 16384;
1.984     raeburn  11360:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11361:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  11362:         if (($actionurl eq '/adm/portfolio') ||
                   11363:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  11364:             my ($sublistref,$listerror) =
                   11365:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11366:             if (ref($sublistref) eq 'ARRAY') {
                   11367:                 foreach my $line (@{$sublistref}) {
                   11368:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11369:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11370:                 }
1.984     raeburn  11371:             }
1.987     raeburn  11372:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11373:             if (opendir(my $dir,$url.'/'.$path)) {
                   11374:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11375:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11376:             }
1.1075.2.11  raeburn  11377:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11378:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11379:                   ($args->{'context'} eq 'paste')) ||
                   11380:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11381:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  11382:                 my $dir;
                   11383:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11384:                     $dir = $fileloc;
                   11385:                 } else {
                   11386:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11387:                 }
1.1071    raeburn  11388:                 if ($dir ne '') {
                   11389:                     my ($sublistref,$listerror) =
                   11390:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11391:                     if (ref($sublistref) eq 'ARRAY') {
                   11392:                         foreach my $line (@{$sublistref}) {
                   11393:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11394:                                 undef,$mtime)=split(/\&/,$line,12);
                   11395:                             unless (($testdir&$dirptr) ||
                   11396:                                     ($file_name =~ /^\.\.?$/)) {
                   11397:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11398:                             }
                   11399:                         }
                   11400:                     }
                   11401:                 }
1.984     raeburn  11402:             }
                   11403:         }
                   11404:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11405:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11406:                 my $item = $path.'/'.$file;
                   11407:                 unless ($mapping{$item} eq $item) {
                   11408:                     $pathchanges{$item} = 1;
                   11409:                 }
                   11410:                 $existing{$item} = 1;
                   11411:                 $numexisting ++;
                   11412:             } else {
                   11413:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11414:             }
                   11415:         }
1.1071    raeburn  11416:         if ($actionurl eq '/adm/dependencies') {
                   11417:             foreach my $path (keys(%currsubfile)) {
                   11418:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11419:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11420:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11421:                              next if (($rem ne '') &&
                   11422:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11423:                                        (ref($navmap) &&
                   11424:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11425:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11426:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11427:                              $unused{$path.'/'.$file} = 1; 
                   11428:                          }
                   11429:                     }
                   11430:                 }
                   11431:             }
                   11432:         }
1.984     raeburn  11433:     }
1.987     raeburn  11434:     my %currfile;
1.1075.2.35  raeburn  11435:     if (($actionurl eq '/adm/portfolio') ||
                   11436:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11437:         my ($dirlistref,$listerror) =
                   11438:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11439:         if (ref($dirlistref) eq 'ARRAY') {
                   11440:             foreach my $line (@{$dirlistref}) {
                   11441:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11442:                 $currfile{$file_name} = 1;
                   11443:             }
1.984     raeburn  11444:         }
1.987     raeburn  11445:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11446:         if (opendir(my $dir,$url)) {
1.987     raeburn  11447:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11448:             map {$currfile{$_} = 1;} @dir_list;
                   11449:         }
1.1075.2.11  raeburn  11450:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11451:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11452:               ($args->{'context'} eq 'paste')) ||
                   11453:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11454:         if ($env{'request.course.id'} ne '') {
                   11455:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11456:             if ($dir ne '') {
                   11457:                 my ($dirlistref,$listerror) =
                   11458:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11459:                 if (ref($dirlistref) eq 'ARRAY') {
                   11460:                     foreach my $line (@{$dirlistref}) {
                   11461:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11462:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11463:                         unless (($testdir&$dirptr) ||
                   11464:                                 ($file_name =~ /^\.\.?$/)) {
                   11465:                             $currfile{$file_name} = [$size,$mtime];
                   11466:                         }
                   11467:                     }
                   11468:                 }
                   11469:             }
                   11470:         }
1.984     raeburn  11471:     }
                   11472:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11473:         if (exists($currfile{$file})) {
1.987     raeburn  11474:             unless ($mapping{$file} eq $file) {
                   11475:                 $pathchanges{$file} = 1;
                   11476:             }
                   11477:             $existing{$file} = 1;
                   11478:             $numexisting ++;
                   11479:         } else {
1.984     raeburn  11480:             $newfiles{$file} = 1;
                   11481:         }
                   11482:     }
1.1071    raeburn  11483:     foreach my $file (keys(%currfile)) {
                   11484:         unless (($file eq $filename) ||
                   11485:                 ($file eq $filename.'.bak') ||
                   11486:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11487:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11488:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11489:                     next if (($rem ne '') &&
                   11490:                              (($env{"httpref.$rem".$file} ne '') ||
                   11491:                               (ref($navmap) &&
                   11492:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11493:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11494:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11495:                 }
1.1075.2.11  raeburn  11496:             }
1.1071    raeburn  11497:             $unused{$file} = 1;
                   11498:         }
                   11499:     }
1.1075.2.11  raeburn  11500:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11501:         ($args->{'context'} eq 'paste')) {
                   11502:         $counter = scalar(keys(%existing));
                   11503:         $numpathchg = scalar(keys(%pathchanges));
                   11504:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11505:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11506:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11507:         $counter = scalar(keys(%existing));
                   11508:         $numpathchg = scalar(keys(%pathchanges));
                   11509:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11510:     }
1.984     raeburn  11511:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11512:         if ($actionurl eq '/adm/dependencies') {
                   11513:             next if ($embed_file =~ m{^\w+://});
                   11514:         }
1.660     raeburn  11515:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11516:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11517:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11518:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11519:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11520:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11521:         }
1.1075.2.35  raeburn  11522:         $upload_output .= '</td>';
1.1071    raeburn  11523:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11524:             $upload_output.='<td align="right">'.
                   11525:                             '<span class="LC_info LC_fontsize_medium">'.
                   11526:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11527:             $numremref++;
1.660     raeburn  11528:         } elsif ($args->{'error_on_invalid_names'}
                   11529:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11530:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11531:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11532:             $numinvalid++;
1.660     raeburn  11533:         } else {
1.1075.2.35  raeburn  11534:             $upload_output .= '<td>'.
                   11535:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11536:                                                      $embed_file,\%mapping,
1.1071    raeburn  11537:                                                      $allfiles,$codebase,'upload');
                   11538:             $counter ++;
                   11539:             $numnew ++;
1.987     raeburn  11540:         }
                   11541:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11542:     }
                   11543:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11544:         if ($actionurl eq '/adm/dependencies') {
                   11545:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11546:             $modify_output .= &start_data_table_row().
                   11547:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11548:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11549:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11550:                               '<td>'.$size.'</td>'.
                   11551:                               '<td>'.$mtime.'</td>'.
                   11552:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11553:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11554:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11555:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11556:                               &embedded_file_element('upload_embedded',$counter,
                   11557:                                                      $embed_file,\%mapping,
                   11558:                                                      $allfiles,$codebase,'modify').
                   11559:                               '</div></td>'.
                   11560:                               &end_data_table_row()."\n";
                   11561:             $counter ++;
                   11562:         } else {
                   11563:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11564:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11565:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11566:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11567:                               &Apache::loncommon::end_data_table_row()."\n";
                   11568:         }
                   11569:     }
                   11570:     my $delidx = $counter;
                   11571:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11572:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11573:         $delete_output .= &start_data_table_row().
                   11574:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11575:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11576:                           '<td>'.$size.'</td>'.
                   11577:                           '<td>'.$mtime.'</td>'.
                   11578:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11579:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11580:                           &embedded_file_element('upload_embedded',$delidx,
                   11581:                                                  $oldfile,\%mapping,$allfiles,
                   11582:                                                  $codebase,'delete').'</td>'.
                   11583:                           &end_data_table_row()."\n"; 
                   11584:         $numunused ++;
                   11585:         $delidx ++;
1.987     raeburn  11586:     }
                   11587:     if ($upload_output) {
                   11588:         $upload_output = &start_data_table().
                   11589:                          $upload_output.
                   11590:                          &end_data_table()."\n";
                   11591:     }
1.1071    raeburn  11592:     if ($modify_output) {
                   11593:         $modify_output = &start_data_table().
                   11594:                          &start_data_table_header_row().
                   11595:                          '<th>'.&mt('File').'</th>'.
                   11596:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11597:                          '<th>'.&mt('Modified').'</th>'.
                   11598:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11599:                          &end_data_table_header_row().
                   11600:                          $modify_output.
                   11601:                          &end_data_table()."\n";
                   11602:     }
                   11603:     if ($delete_output) {
                   11604:         $delete_output = &start_data_table().
                   11605:                          &start_data_table_header_row().
                   11606:                          '<th>'.&mt('File').'</th>'.
                   11607:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11608:                          '<th>'.&mt('Modified').'</th>'.
                   11609:                          '<th>'.&mt('Delete?').'</th>'.
                   11610:                          &end_data_table_header_row().
                   11611:                          $delete_output.
                   11612:                          &end_data_table()."\n";
                   11613:     }
1.987     raeburn  11614:     my $applies = 0;
                   11615:     if ($numremref) {
                   11616:         $applies ++;
                   11617:     }
                   11618:     if ($numinvalid) {
                   11619:         $applies ++;
                   11620:     }
                   11621:     if ($numexisting) {
                   11622:         $applies ++;
                   11623:     }
1.1071    raeburn  11624:     if ($counter || $numunused) {
1.987     raeburn  11625:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11626:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11627:                   $state.'<h3>'.$heading.'</h3>'; 
                   11628:         if ($actionurl eq '/adm/dependencies') {
                   11629:             if ($numnew) {
                   11630:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11631:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11632:                            $upload_output.'<br />'."\n";
                   11633:             }
                   11634:             if ($numexisting) {
                   11635:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11636:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11637:                            $modify_output.'<br />'."\n";
                   11638:                            $buttontext = &mt('Save changes');
                   11639:             }
                   11640:             if ($numunused) {
                   11641:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11642:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11643:                            $delete_output.'<br />'."\n";
                   11644:                            $buttontext = &mt('Save changes');
                   11645:             }
                   11646:         } else {
                   11647:             $output .= $upload_output.'<br />'."\n";
                   11648:         }
                   11649:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11650:                    $counter.'" />'."\n";
                   11651:         if ($actionurl eq '/adm/dependencies') { 
                   11652:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11653:                        $numnew.'" />'."\n";
                   11654:         } elsif ($actionurl eq '') {
1.987     raeburn  11655:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11656:         }
                   11657:     } elsif ($applies) {
                   11658:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11659:         if ($applies > 1) {
                   11660:             $output .=  
1.1075.2.35  raeburn  11661:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11662:             if ($numremref) {
                   11663:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11664:             }
                   11665:             if ($numinvalid) {
                   11666:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11667:             }
                   11668:             if ($numexisting) {
                   11669:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11670:             }
                   11671:             $output .= '</ul><br />';
                   11672:         } elsif ($numremref) {
                   11673:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11674:         } elsif ($numinvalid) {
                   11675:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11676:         } elsif ($numexisting) {
                   11677:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11678:         }
                   11679:         $output .= $upload_output.'<br />';
                   11680:     }
                   11681:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11682:     $chgcount = $counter;
1.987     raeburn  11683:     if (keys(%pathchanges) > 0) {
                   11684:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11685:             if ($counter) {
1.987     raeburn  11686:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11687:                                                   $embed_file,\%mapping,
1.1071    raeburn  11688:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11689:             } else {
                   11690:                 $pathchange_output .= 
                   11691:                     &start_data_table_row().
                   11692:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11693:                     $chgcount.'" checked="checked" /></td>'.
                   11694:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11695:                     '<td>'.$embed_file.
                   11696:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11697:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11698:                     '</td>'.&end_data_table_row();
1.660     raeburn  11699:             }
1.987     raeburn  11700:             $numpathchg ++;
                   11701:             $chgcount ++;
1.660     raeburn  11702:         }
                   11703:     }
1.1075.2.35  raeburn  11704:     if (($counter) || ($numunused)) {
1.987     raeburn  11705:         if ($numpathchg) {
                   11706:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11707:                        $numpathchg.'" />'."\n";
                   11708:         }
                   11709:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11710:             ($actionurl eq '/adm/imsimport')) {
                   11711:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11712:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11713:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11714:         } elsif ($actionurl eq '/adm/dependencies') {
                   11715:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11716:         }
1.1075.2.35  raeburn  11717:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11718:     } elsif ($numpathchg) {
                   11719:         my %pathchange = ();
                   11720:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11721:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11722:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11723:         }
1.987     raeburn  11724:     }
1.1071    raeburn  11725:     return ($output,$counter,$numpathchg);
1.987     raeburn  11726: }
                   11727: 
1.1075.2.47  raeburn  11728: =pod
                   11729: 
                   11730: =item * clean_path($name)
                   11731: 
                   11732: Performs clean-up of directories, subdirectories and filename in an
                   11733: embedded object, referenced in an HTML file which is being uploaded
                   11734: to a course or portfolio, where
                   11735: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11736: checked.
                   11737: 
                   11738: Clean-up is similar to replacements in lonnet::clean_filename()
                   11739: except each / between sub-directory and next level is preserved.
                   11740: 
                   11741: =cut
                   11742: 
                   11743: sub clean_path {
                   11744:     my ($embed_file) = @_;
                   11745:     $embed_file =~s{^/+}{};
                   11746:     my @contents;
                   11747:     if ($embed_file =~ m{/}) {
                   11748:         @contents = split(/\//,$embed_file);
                   11749:     } else {
                   11750:         @contents = ($embed_file);
                   11751:     }
                   11752:     my $lastidx = scalar(@contents)-1;
                   11753:     for (my $i=0; $i<=$lastidx; $i++) {
                   11754:         $contents[$i]=~s{\\}{/}g;
                   11755:         $contents[$i]=~s/\s+/\_/g;
                   11756:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11757:         if ($i == $lastidx) {
                   11758:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11759:         }
                   11760:     }
                   11761:     if ($lastidx > 0) {
                   11762:         return join('/',@contents);
                   11763:     } else {
                   11764:         return $contents[0];
                   11765:     }
                   11766: }
                   11767: 
1.987     raeburn  11768: sub embedded_file_element {
1.1071    raeburn  11769:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11770:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11771:                    (ref($codebase) eq 'HASH'));
                   11772:     my $output;
1.1071    raeburn  11773:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11774:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11775:     }
                   11776:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11777:                &escape($embed_file).'" />';
                   11778:     unless (($context eq 'upload_embedded') && 
                   11779:             ($mapping->{$embed_file} eq $embed_file)) {
                   11780:         $output .='
                   11781:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11782:     }
                   11783:     my $attrib;
                   11784:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11785:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11786:     }
                   11787:     $output .=
                   11788:         "\n\t\t".
                   11789:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11790:         $attrib.'" />';
                   11791:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11792:         $output .=
                   11793:             "\n\t\t".
                   11794:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11795:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11796:     }
1.987     raeburn  11797:     return $output;
1.660     raeburn  11798: }
                   11799: 
1.1071    raeburn  11800: sub get_dependency_details {
                   11801:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11802:     my ($size,$mtime,$showsize,$showmtime);
                   11803:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11804:         if ($embed_file =~ m{/}) {
                   11805:             my ($path,$fname) = split(/\//,$embed_file);
                   11806:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11807:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11808:             }
                   11809:         } else {
                   11810:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11811:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11812:             }
                   11813:         }
                   11814:         $showsize = $size/1024.0;
                   11815:         $showsize = sprintf("%.1f",$showsize);
                   11816:         if ($mtime > 0) {
                   11817:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11818:         }
                   11819:     }
                   11820:     return ($showsize,$showmtime);
                   11821: }
                   11822: 
                   11823: sub ask_embedded_js {
                   11824:     return <<"END";
                   11825: <script type="text/javascript"">
                   11826: // <![CDATA[
                   11827: function toggleBrowse(counter) {
                   11828:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11829:     var fileid = document.getElementById('embedded_item_'+counter);
                   11830:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11831:     if (chkboxid.checked == true) {
                   11832:         uploaddivid.style.display='block';
                   11833:     } else {
                   11834:         uploaddivid.style.display='none';
                   11835:         fileid.value = '';
                   11836:     }
                   11837: }
                   11838: // ]]>
                   11839: </script>
                   11840: 
                   11841: END
                   11842: }
                   11843: 
1.661     raeburn  11844: sub upload_embedded {
                   11845:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11846:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11847:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11848:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11849:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11850:         my $orig_uploaded_filename =
                   11851:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11852:         foreach my $type ('orig','ref','attrib','codebase') {
                   11853:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11854:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11855:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11856:             }
                   11857:         }
1.661     raeburn  11858:         my ($path,$fname) =
                   11859:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11860:         # no path, whole string is fname
                   11861:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11862:         $fname = &Apache::lonnet::clean_filename($fname);
                   11863:         # See if there is anything left
                   11864:         next if ($fname eq '');
                   11865: 
                   11866:         # Check if file already exists as a file or directory.
                   11867:         my ($state,$msg);
                   11868:         if ($context eq 'portfolio') {
                   11869:             my $port_path = $dirpath;
                   11870:             if ($group ne '') {
                   11871:                 $port_path = "groups/$group/$port_path";
                   11872:             }
1.987     raeburn  11873:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11874:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11875:                                               $dir_root,$port_path,$disk_quota,
                   11876:                                               $current_disk_usage,$uname,$udom);
                   11877:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11878:                 || $state eq 'file_locked') {
1.661     raeburn  11879:                 $output .= $msg;
                   11880:                 next;
                   11881:             }
                   11882:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11883:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11884:             if ($state eq 'exists') {
                   11885:                 $output .= $msg;
                   11886:                 next;
                   11887:             }
                   11888:         }
                   11889:         # Check if extension is valid
                   11890:         if (($fname =~ /\.(\w+)$/) &&
                   11891:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11892:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11893:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11894:             next;
                   11895:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11896:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11897:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11898:             next;
                   11899:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11900:             $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  11901:             next;
                   11902:         }
                   11903:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11904:         my $subdir = $path;
                   11905:         $subdir =~ s{/+$}{};
1.661     raeburn  11906:         if ($context eq 'portfolio') {
1.984     raeburn  11907:             my $result;
                   11908:             if ($state eq 'existingfile') {
                   11909:                 $result=
                   11910:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11911:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11912:             } else {
1.984     raeburn  11913:                 $result=
                   11914:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11915:                                                     $dirpath.
1.1075.2.35  raeburn  11916:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11917:                 if ($result !~ m|^/uploaded/|) {
                   11918:                     $output .= '<span class="LC_error">'
                   11919:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11920:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11921:                                .'</span><br />';
                   11922:                     next;
                   11923:                 } else {
1.987     raeburn  11924:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11925:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11926:                 }
1.661     raeburn  11927:             }
1.1075.2.35  raeburn  11928:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11929:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11930:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11931:             my $result =
1.1075.2.35  raeburn  11932:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11933:             if ($result !~ m|^/uploaded/|) {
                   11934:                 $output .= '<span class="LC_error">'
                   11935:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11936:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11937:                            .'</span><br />';
                   11938:                     next;
                   11939:             } else {
                   11940:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11941:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11942:                 if ($context eq 'syllabus') {
                   11943:                     &Apache::lonnet::make_public_indefinitely($result);
                   11944:                 }
1.987     raeburn  11945:             }
1.661     raeburn  11946:         } else {
                   11947: # Save the file
                   11948:             my $target = $env{'form.embedded_item_'.$i};
                   11949:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11950:             my $dest = $fullpath.$fname;
                   11951:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11952:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11953:             my $count;
                   11954:             my $filepath = $dir_root;
1.1027    raeburn  11955:             foreach my $subdir (@parts) {
                   11956:                 $filepath .= "/$subdir";
                   11957:                 if (!-e $filepath) {
1.661     raeburn  11958:                     mkdir($filepath,0770);
                   11959:                 }
                   11960:             }
                   11961:             my $fh;
                   11962:             if (!open($fh,'>'.$dest)) {
                   11963:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11964:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11965:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11966:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11967:                            '</span><br />';
                   11968:             } else {
                   11969:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11970:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11971:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11972:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11973:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11974:                               '</span><br />';
                   11975:                 } else {
1.987     raeburn  11976:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11977:                                $url.'</span>').'<br />';
                   11978:                     unless ($context eq 'testbank') {
                   11979:                         $footer .= &mt('View embedded file: [_1]',
                   11980:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11981:                     }
                   11982:                 }
                   11983:                 close($fh);
                   11984:             }
                   11985:         }
                   11986:         if ($env{'form.embedded_ref_'.$i}) {
                   11987:             $pathchange{$i} = 1;
                   11988:         }
                   11989:     }
                   11990:     if ($output) {
                   11991:         $output = '<p>'.$output.'</p>';
                   11992:     }
                   11993:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11994:     $returnflag = 'ok';
1.1071    raeburn  11995:     my $numpathchgs = scalar(keys(%pathchange));
                   11996:     if ($numpathchgs > 0) {
1.987     raeburn  11997:         if ($context eq 'portfolio') {
                   11998:             $output .= '<p>'.&mt('or').'</p>';
                   11999:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12000:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12001:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12002:             $returnflag = 'modify_orightml';
                   12003:         }
                   12004:     }
1.1071    raeburn  12005:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12006: }
                   12007: 
                   12008: sub modify_html_form {
                   12009:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12010:     my $end = 0;
                   12011:     my $modifyform;
                   12012:     if ($context eq 'upload_embedded') {
                   12013:         return unless (ref($pathchange) eq 'HASH');
                   12014:         if ($env{'form.number_embedded_items'}) {
                   12015:             $end += $env{'form.number_embedded_items'};
                   12016:         }
                   12017:         if ($env{'form.number_pathchange_items'}) {
                   12018:             $end += $env{'form.number_pathchange_items'};
                   12019:         }
                   12020:         if ($end) {
                   12021:             for (my $i=0; $i<$end; $i++) {
                   12022:                 if ($i < $env{'form.number_embedded_items'}) {
                   12023:                     next unless($pathchange->{$i});
                   12024:                 }
                   12025:                 $modifyform .=
                   12026:                     &start_data_table_row().
                   12027:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12028:                     'checked="checked" /></td>'.
                   12029:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12030:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12031:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12032:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12033:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12034:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12035:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12036:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12037:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12038:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12039:                     &end_data_table_row();
1.1071    raeburn  12040:             }
1.987     raeburn  12041:         }
                   12042:     } else {
                   12043:         $modifyform = $pathchgtable;
                   12044:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12045:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12046:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12047:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12048:         }
                   12049:     }
                   12050:     if ($modifyform) {
1.1071    raeburn  12051:         if ($actionurl eq '/adm/dependencies') {
                   12052:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12053:         }
1.987     raeburn  12054:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12055:                '<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".
                   12056:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12057:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12058:                '</ol></p>'."\n".'<p>'.
                   12059:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12060:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12061:                &start_data_table()."\n".
                   12062:                &start_data_table_header_row().
                   12063:                '<th>'.&mt('Change?').'</th>'.
                   12064:                '<th>'.&mt('Current reference').'</th>'.
                   12065:                '<th>'.&mt('Required reference').'</th>'.
                   12066:                &end_data_table_header_row()."\n".
                   12067:                $modifyform.
                   12068:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12069:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12070:                '</form>'."\n";
                   12071:     }
                   12072:     return;
                   12073: }
                   12074: 
                   12075: sub modify_html_refs {
1.1075.2.35  raeburn  12076:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12077:     my $container;
                   12078:     if ($context eq 'portfolio') {
                   12079:         $container = $env{'form.container'};
                   12080:     } elsif ($context eq 'coursedoc') {
                   12081:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12082:     } elsif ($context eq 'manage_dependencies') {
                   12083:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12084:         $container = "/$container";
1.1075.2.35  raeburn  12085:     } elsif ($context eq 'syllabus') {
                   12086:         $container = $url;
1.987     raeburn  12087:     } else {
1.1027    raeburn  12088:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12089:     }
                   12090:     my (%allfiles,%codebase,$output,$content);
                   12091:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12092:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12093:         if (wantarray) {
                   12094:             return ('',0,0); 
                   12095:         } else {
                   12096:             return;
                   12097:         }
                   12098:     }
                   12099:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12100:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12101:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12102:             if (wantarray) {
                   12103:                 return ('',0,0);
                   12104:             } else {
                   12105:                 return;
                   12106:             }
                   12107:         } 
1.987     raeburn  12108:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12109:         if ($content eq '-1') {
                   12110:             if (wantarray) {
                   12111:                 return ('',0,0);
                   12112:             } else {
                   12113:                 return;
                   12114:             }
                   12115:         }
1.987     raeburn  12116:     } else {
1.1071    raeburn  12117:         unless ($container =~ /^\Q$dir_root\E/) {
                   12118:             if (wantarray) {
                   12119:                 return ('',0,0);
                   12120:             } else {
                   12121:                 return;
                   12122:             }
                   12123:         } 
1.1075.2.128  raeburn  12124:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12125:             $content = join('', <$fh>);
                   12126:             close($fh);
                   12127:         } else {
1.1071    raeburn  12128:             if (wantarray) {
                   12129:                 return ('',0,0);
                   12130:             } else {
                   12131:                 return;
                   12132:             }
1.987     raeburn  12133:         }
                   12134:     }
                   12135:     my ($count,$codebasecount) = (0,0);
                   12136:     my $mm = new File::MMagic;
                   12137:     my $mime_type = $mm->checktype_contents($content);
                   12138:     if ($mime_type eq 'text/html') {
                   12139:         my $parse_result = 
                   12140:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12141:                                                     \%codebase,\$content);
                   12142:         if ($parse_result eq 'ok') {
                   12143:             foreach my $i (@changes) {
                   12144:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12145:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12146:                 if ($allfiles{$ref}) {
                   12147:                     my $newname =  $orig;
                   12148:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12149:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12150:                     if ($attrib_regexp =~ /:/) {
                   12151:                         $attrib_regexp =~ s/\:/|/g;
                   12152:                     }
                   12153:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12154:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12155:                         $count += $numchg;
1.1075.2.35  raeburn  12156:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12157:                         delete($allfiles{$ref});
1.987     raeburn  12158:                     }
                   12159:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12160:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12161:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12162:                         $codebasecount ++;
                   12163:                     }
                   12164:                 }
                   12165:             }
1.1075.2.35  raeburn  12166:             my $skiprewrites;
1.987     raeburn  12167:             if ($count || $codebasecount) {
                   12168:                 my $saveresult;
1.1071    raeburn  12169:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12170:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12171:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12172:                     if ($url eq $container) {
                   12173:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12174:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12175:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12176:                                             $fname.'</span>').'</p>';
1.987     raeburn  12177:                     } else {
                   12178:                          $output = '<p class="LC_error">'.
                   12179:                                    &mt('Error: update failed for: [_1].',
                   12180:                                    '<span class="LC_filename">'.
                   12181:                                    $container.'</span>').'</p>';
                   12182:                     }
1.1075.2.35  raeburn  12183:                     if ($context eq 'syllabus') {
                   12184:                         unless ($saveresult eq 'ok') {
                   12185:                             $skiprewrites = 1;
                   12186:                         }
                   12187:                     }
1.987     raeburn  12188:                 } else {
1.1075.2.128  raeburn  12189:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12190:                         print $fh $content;
                   12191:                         close($fh);
                   12192:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12193:                                   $count,'<span class="LC_filename">'.
                   12194:                                   $container.'</span>').'</p>';
1.661     raeburn  12195:                     } else {
1.987     raeburn  12196:                          $output = '<p class="LC_error">'.
                   12197:                                    &mt('Error: could not update [_1].',
                   12198:                                    '<span class="LC_filename">'.
                   12199:                                    $container.'</span>').'</p>';
1.661     raeburn  12200:                     }
                   12201:                 }
                   12202:             }
1.1075.2.35  raeburn  12203:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12204:                 my ($actionurl,$state);
                   12205:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12206:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12207:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12208:                                               \%codebase,
                   12209:                                               {'context' => 'rewrites',
                   12210:                                                'ignore_remote_references' => 1,});
                   12211:                 if (ref($mapping) eq 'HASH') {
                   12212:                     my $rewrites = 0;
                   12213:                     foreach my $key (keys(%{$mapping})) {
                   12214:                         next if ($key =~ m{^https?://});
                   12215:                         my $ref = $mapping->{$key};
                   12216:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12217:                         my $attrib;
                   12218:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12219:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12220:                         }
                   12221:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12222:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12223:                             $rewrites += $numchg;
                   12224:                         }
                   12225:                     }
                   12226:                     if ($rewrites) {
                   12227:                         my $saveresult;
                   12228:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12229:                         if ($url eq $container) {
                   12230:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12231:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12232:                                             $count,'<span class="LC_filename">'.
                   12233:                                             $fname.'</span>').'</p>';
                   12234:                         } else {
                   12235:                             $output .= '<p class="LC_error">'.
                   12236:                                        &mt('Error: could not update links in [_1].',
                   12237:                                        '<span class="LC_filename">'.
                   12238:                                        $container.'</span>').'</p>';
                   12239: 
                   12240:                         }
                   12241:                     }
                   12242:                 }
                   12243:             }
1.987     raeburn  12244:         } else {
                   12245:             &logthis('Failed to parse '.$container.
                   12246:                      ' to modify references: '.$parse_result);
1.661     raeburn  12247:         }
                   12248:     }
1.1071    raeburn  12249:     if (wantarray) {
                   12250:         return ($output,$count,$codebasecount);
                   12251:     } else {
                   12252:         return $output;
                   12253:     }
1.661     raeburn  12254: }
                   12255: 
                   12256: sub check_for_existing {
                   12257:     my ($path,$fname,$element) = @_;
                   12258:     my ($state,$msg);
                   12259:     if (-d $path.'/'.$fname) {
                   12260:         $state = 'exists';
                   12261:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12262:     } elsif (-e $path.'/'.$fname) {
                   12263:         $state = 'exists';
                   12264:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12265:     }
                   12266:     if ($state eq 'exists') {
                   12267:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12268:     }
                   12269:     return ($state,$msg);
                   12270: }
                   12271: 
                   12272: sub check_for_upload {
                   12273:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12274:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12275:     my $filesize = length($env{'form.'.$element});
                   12276:     if (!$filesize) {
                   12277:         my $msg = '<span class="LC_error">'.
                   12278:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12279:                       '<span class="LC_filename">'.$fname.'</span>',
                   12280:                       $filesize).'<br />'.
1.1007    raeburn  12281:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12282:                   '</span>';
                   12283:         return ('zero_bytes',$msg);
                   12284:     }
                   12285:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12286:     my $getpropath = 1;
1.1021    raeburn  12287:     my ($dirlistref,$listerror) =
                   12288:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12289:     my $found_file = 0;
                   12290:     my $locked_file = 0;
1.991     raeburn  12291:     my @lockers;
                   12292:     my $navmap;
                   12293:     if ($env{'request.course.id'}) {
                   12294:         $navmap = Apache::lonnavmaps::navmap->new();
                   12295:     }
1.1021    raeburn  12296:     if (ref($dirlistref) eq 'ARRAY') {
                   12297:         foreach my $line (@{$dirlistref}) {
                   12298:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12299:             if ($file_name eq $fname){
                   12300:                 $file_name = $path.$file_name;
                   12301:                 if ($group ne '') {
                   12302:                     $file_name = $group.$file_name;
                   12303:                 }
                   12304:                 $found_file = 1;
                   12305:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12306:                     foreach my $lock (@lockers) {
                   12307:                         if (ref($lock) eq 'ARRAY') {
                   12308:                             my ($symb,$crsid) = @{$lock};
                   12309:                             if ($crsid eq $env{'request.course.id'}) {
                   12310:                                 if (ref($navmap)) {
                   12311:                                     my $res = $navmap->getBySymb($symb);
                   12312:                                     foreach my $part (@{$res->parts()}) { 
                   12313:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12314:                                         unless (($slot_status == $res->RESERVED) ||
                   12315:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12316:                                             $locked_file = 1;
                   12317:                                         }
1.991     raeburn  12318:                                     }
1.1021    raeburn  12319:                                 } else {
                   12320:                                     $locked_file = 1;
1.991     raeburn  12321:                                 }
                   12322:                             } else {
                   12323:                                 $locked_file = 1;
                   12324:                             }
                   12325:                         }
1.1021    raeburn  12326:                    }
                   12327:                 } else {
                   12328:                     my @info = split(/\&/,$rest);
                   12329:                     my $currsize = $info[6]/1000;
                   12330:                     if ($currsize < $filesize) {
                   12331:                         my $extra = $filesize - $currsize;
                   12332:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  12333:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12334:                                       &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  12335:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12336:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12337:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12338:                             return ('will_exceed_quota',$msg);
                   12339:                         }
1.984     raeburn  12340:                     }
                   12341:                 }
1.661     raeburn  12342:             }
                   12343:         }
                   12344:     }
                   12345:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  12346:         my $msg = '<p class="LC_warning">'.
                   12347:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   12348:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12349:         return ('will_exceed_quota',$msg);
                   12350:     } elsif ($found_file) {
                   12351:         if ($locked_file) {
1.1075.2.69  raeburn  12352:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12353:             $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  12354:             $msg .= '</p>';
1.661     raeburn  12355:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12356:             return ('file_locked',$msg);
                   12357:         } else {
1.1075.2.69  raeburn  12358:             my $msg = '<p class="LC_error">';
1.984     raeburn  12359:             $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  12360:             $msg .= '</p>';
1.984     raeburn  12361:             return ('existingfile',$msg);
1.661     raeburn  12362:         }
                   12363:     }
                   12364: }
                   12365: 
1.987     raeburn  12366: sub check_for_traversal {
                   12367:     my ($path,$url,$toplevel) = @_;
                   12368:     my @parts=split(/\//,$path);
                   12369:     my $cleanpath;
                   12370:     my $fullpath = $url;
                   12371:     for (my $i=0;$i<@parts;$i++) {
                   12372:         next if ($parts[$i] eq '.');
                   12373:         if ($parts[$i] eq '..') {
                   12374:             $fullpath =~ s{([^/]+/)$}{};
                   12375:         } else {
                   12376:             $fullpath .= $parts[$i].'/';
                   12377:         }
                   12378:     }
                   12379:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12380:         $cleanpath = $1;
                   12381:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12382:         my $curr_toprel = $1;
                   12383:         my @parts = split(/\//,$curr_toprel);
                   12384:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12385:         my @urlparts = split(/\//,$url_toprel);
                   12386:         my $doubledots;
                   12387:         my $startdiff = -1;
                   12388:         for (my $i=0; $i<@urlparts; $i++) {
                   12389:             if ($startdiff == -1) {
                   12390:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12391:                     $startdiff = $i;
                   12392:                     $doubledots .= '../';
                   12393:                 }
                   12394:             } else {
                   12395:                 $doubledots .= '../';
                   12396:             }
                   12397:         }
                   12398:         if ($startdiff > -1) {
                   12399:             $cleanpath = $doubledots;
                   12400:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12401:                 $cleanpath .= $parts[$i].'/';
                   12402:             }
                   12403:         }
                   12404:     }
                   12405:     $cleanpath =~ s{(/)$}{};
                   12406:     return $cleanpath;
                   12407: }
1.31      albertel 12408: 
1.1053    raeburn  12409: sub is_archive_file {
                   12410:     my ($mimetype) = @_;
                   12411:     if (($mimetype eq 'application/octet-stream') ||
                   12412:         ($mimetype eq 'application/x-stuffit') ||
                   12413:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12414:         return 1;
                   12415:     }
                   12416:     return;
                   12417: }
                   12418: 
                   12419: sub decompress_form {
1.1065    raeburn  12420:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12421:     my %lt = &Apache::lonlocal::texthash (
                   12422:         this => 'This file is an archive file.',
1.1067    raeburn  12423:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12424:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12425:         youm => 'You may wish to extract its contents.',
                   12426:         extr => 'Extract contents',
1.1067    raeburn  12427:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12428:         proa => 'Process automatically?',
1.1053    raeburn  12429:         yes  => 'Yes',
                   12430:         no   => 'No',
1.1067    raeburn  12431:         fold => 'Title for folder containing movie',
                   12432:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12433:     );
1.1065    raeburn  12434:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12435:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12436:     my $info = &list_archive_contents($fileloc,\@paths);
                   12437:     if (@paths) {
                   12438:         foreach my $path (@paths) {
                   12439:             $path =~ s{^/}{};
1.1067    raeburn  12440:             if ($path =~ m{^([^/]+)/$}) {
                   12441:                 $topdir = $1;
                   12442:             }
1.1065    raeburn  12443:             if ($path =~ m{^([^/]+)/}) {
                   12444:                 $toplevel{$1} = $path;
                   12445:             } else {
                   12446:                 $toplevel{$path} = $path;
                   12447:             }
                   12448:         }
                   12449:     }
1.1067    raeburn  12450:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12451:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12452:                         "$topdir/media/",
                   12453:                         "$topdir/media/$topdir.mp4",
                   12454:                         "$topdir/media/FirstFrame.png",
                   12455:                         "$topdir/media/player.swf",
                   12456:                         "$topdir/media/swfobject.js",
                   12457:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12458:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12459:                          "$topdir/$topdir.mp4",
                   12460:                          "$topdir/$topdir\_config.xml",
                   12461:                          "$topdir/$topdir\_controller.swf",
                   12462:                          "$topdir/$topdir\_embed.css",
                   12463:                          "$topdir/$topdir\_First_Frame.png",
                   12464:                          "$topdir/$topdir\_player.html",
                   12465:                          "$topdir/$topdir\_Thumbnails.png",
                   12466:                          "$topdir/playerProductInstall.swf",
                   12467:                          "$topdir/scripts/",
                   12468:                          "$topdir/scripts/config_xml.js",
                   12469:                          "$topdir/scripts/handlebars.js",
                   12470:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12471:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12472:                          "$topdir/scripts/modernizr.js",
                   12473:                          "$topdir/scripts/player-min.js",
                   12474:                          "$topdir/scripts/swfobject.js",
                   12475:                          "$topdir/skins/",
                   12476:                          "$topdir/skins/configuration_express.xml",
                   12477:                          "$topdir/skins/express_show/",
                   12478:                          "$topdir/skins/express_show/player-min.css",
                   12479:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12480:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12481:                          "$topdir/$topdir.mp4",
                   12482:                          "$topdir/$topdir\_config.xml",
                   12483:                          "$topdir/$topdir\_controller.swf",
                   12484:                          "$topdir/$topdir\_embed.css",
                   12485:                          "$topdir/$topdir\_First_Frame.png",
                   12486:                          "$topdir/$topdir\_player.html",
                   12487:                          "$topdir/$topdir\_Thumbnails.png",
                   12488:                          "$topdir/playerProductInstall.swf",
                   12489:                          "$topdir/scripts/",
                   12490:                          "$topdir/scripts/config_xml.js",
                   12491:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12492:                          "$topdir/skins/",
                   12493:                          "$topdir/skins/configuration_express.xml",
                   12494:                          "$topdir/skins/express_show/",
                   12495:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12496:                          "$topdir/skins/express_show/spritesheet.png",
                   12497:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12498:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12499:         if (@diffs == 0) {
1.1075.2.59  raeburn  12500:             $is_camtasia = 6;
                   12501:         } else {
1.1075.2.81  raeburn  12502:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12503:             if (@diffs == 0) {
                   12504:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12505:             } else {
                   12506:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12507:                 if (@diffs == 0) {
                   12508:                     $is_camtasia = 8;
                   12509:                 }
1.1075.2.59  raeburn  12510:             }
1.1067    raeburn  12511:         }
                   12512:     }
                   12513:     my $output;
                   12514:     if ($is_camtasia) {
                   12515:         $output = <<"ENDCAM";
                   12516: <script type="text/javascript" language="Javascript">
                   12517: // <![CDATA[
                   12518: 
                   12519: function camtasiaToggle() {
                   12520:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12521:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12522:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12523:                 document.getElementById('camtasia_titles').style.display='block';
                   12524:             } else {
                   12525:                 document.getElementById('camtasia_titles').style.display='none';
                   12526:             }
                   12527:         }
                   12528:     }
                   12529:     return;
                   12530: }
                   12531: 
                   12532: // ]]>
                   12533: </script>
                   12534: <p>$lt{'camt'}</p>
                   12535: ENDCAM
1.1065    raeburn  12536:     } else {
1.1067    raeburn  12537:         $output = '<p>'.$lt{'this'};
                   12538:         if ($info eq '') {
                   12539:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12540:         } else {
                   12541:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12542:                        '<div><pre>'.$info.'</pre></div>';
                   12543:         }
1.1065    raeburn  12544:     }
1.1067    raeburn  12545:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12546:     my $duplicates;
                   12547:     my $num = 0;
                   12548:     if (ref($dirlist) eq 'ARRAY') {
                   12549:         foreach my $item (@{$dirlist}) {
                   12550:             if (ref($item) eq 'ARRAY') {
                   12551:                 if (exists($toplevel{$item->[0]})) {
                   12552:                     $duplicates .= 
                   12553:                         &start_data_table_row().
                   12554:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12555:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12556:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12557:                         'value="1" />'.&mt('Yes').'</label>'.
                   12558:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12559:                         '<td>'.$item->[0].'</td>';
                   12560:                     if ($item->[2]) {
                   12561:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12562:                     } else {
                   12563:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12564:                     }
                   12565:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12566:                                    '<td>'.
                   12567:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12568:                                    '</td>'.
                   12569:                                    &end_data_table_row();
                   12570:                     $num ++;
                   12571:                 }
                   12572:             }
                   12573:         }
                   12574:     }
                   12575:     my $itemcount;
                   12576:     if (@paths > 0) {
                   12577:         $itemcount = scalar(@paths);
                   12578:     } else {
                   12579:         $itemcount = 1;
                   12580:     }
1.1067    raeburn  12581:     if ($is_camtasia) {
                   12582:         $output .= $lt{'auto'}.'<br />'.
                   12583:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12584:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12585:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12586:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12587:                    $lt{'no'}.'</label></span><br />'.
                   12588:                    '<div id="camtasia_titles" style="display:block">'.
                   12589:                    &Apache::lonhtmlcommon::start_pick_box().
                   12590:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12591:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12592:                    &Apache::lonhtmlcommon::row_closure().
                   12593:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12594:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12595:                    &Apache::lonhtmlcommon::row_closure(1).
                   12596:                    &Apache::lonhtmlcommon::end_pick_box().
                   12597:                    '</div>';
                   12598:     }
1.1065    raeburn  12599:     $output .= 
                   12600:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12601:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12602:         "\n";
1.1065    raeburn  12603:     if ($duplicates ne '') {
                   12604:         $output .= '<p><span class="LC_warning">'.
                   12605:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12606:                    &start_data_table().
                   12607:                    &start_data_table_header_row().
                   12608:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12609:                    '<th>'.&mt('Name').'</th>'.
                   12610:                    '<th>'.&mt('Type').'</th>'.
                   12611:                    '<th>'.&mt('Size').'</th>'.
                   12612:                    '<th>'.&mt('Last modified').'</th>'.
                   12613:                    &end_data_table_header_row().
                   12614:                    $duplicates.
                   12615:                    &end_data_table().
                   12616:                    '</p>';
                   12617:     }
1.1067    raeburn  12618:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12619:     if (ref($hiddenelements) eq 'HASH') {
                   12620:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12621:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12622:         }
                   12623:     }
                   12624:     $output .= <<"END";
1.1067    raeburn  12625: <br />
1.1053    raeburn  12626: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12627: </form>
                   12628: $noextract
                   12629: END
                   12630:     return $output;
                   12631: }
                   12632: 
1.1065    raeburn  12633: sub decompression_utility {
                   12634:     my ($program) = @_;
                   12635:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12636:     my $location;
                   12637:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12638:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12639:                          '/usr/sbin/') {
                   12640:             if (-x $dir.$program) {
                   12641:                 $location = $dir.$program;
                   12642:                 last;
                   12643:             }
                   12644:         }
                   12645:     }
                   12646:     return $location;
                   12647: }
                   12648: 
                   12649: sub list_archive_contents {
                   12650:     my ($file,$pathsref) = @_;
                   12651:     my (@cmd,$output);
                   12652:     my $needsregexp;
                   12653:     if ($file =~ /\.zip$/) {
                   12654:         @cmd = (&decompression_utility('unzip'),"-l");
                   12655:         $needsregexp = 1;
                   12656:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12657:              ($file =~ /\.tgz$/)) {
                   12658:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12659:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12660:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12661:     } elsif ($file =~ m|\.tar$|) {
                   12662:         @cmd = (&decompression_utility('tar'),"-tf");
                   12663:     }
                   12664:     if (@cmd) {
                   12665:         undef($!);
                   12666:         undef($@);
                   12667:         if (open(my $fh,"-|", @cmd, $file)) {
                   12668:             while (my $line = <$fh>) {
                   12669:                 $output .= $line;
                   12670:                 chomp($line);
                   12671:                 my $item;
                   12672:                 if ($needsregexp) {
                   12673:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12674:                 } else {
                   12675:                     $item = $line;
                   12676:                 }
                   12677:                 if ($item ne '') {
                   12678:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12679:                         push(@{$pathsref},$item);
                   12680:                     } 
                   12681:                 }
                   12682:             }
                   12683:             close($fh);
                   12684:         }
                   12685:     }
                   12686:     return $output;
                   12687: }
                   12688: 
1.1053    raeburn  12689: sub decompress_uploaded_file {
                   12690:     my ($file,$dir) = @_;
                   12691:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12692:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12693:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12694:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12695:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12696:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12697:     my $decompressed = $env{'cgi.decompressed'};
                   12698:     &Apache::lonnet::delenv('cgi.file');
                   12699:     &Apache::lonnet::delenv('cgi.dir');
                   12700:     &Apache::lonnet::delenv('cgi.decompressed');
                   12701:     return ($decompressed,$result);
                   12702: }
                   12703: 
1.1055    raeburn  12704: sub process_decompression {
                   12705:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12706:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12707:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12708:                &mt('Unexpected file path.').'</p>'."\n";
                   12709:     }
                   12710:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12711:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12712:                &mt('Unexpected course context.').'</p>'."\n";
                   12713:     }
                   12714:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12715:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12716:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12717:     }
1.1055    raeburn  12718:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12719:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12720:         $error = &mt('Filename not a supported archive file type.').
                   12721:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12722:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12723:     } else {
                   12724:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12725:         if ($docuhome eq 'no_host') {
                   12726:             $error = &mt('Could not determine home server for course.');
                   12727:         } else {
                   12728:             my @ids=&Apache::lonnet::current_machine_ids();
                   12729:             my $currdir = "$dir_root/$destination";
                   12730:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12731:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12732:                        "$dir_root/$destination";
                   12733:             } else {
                   12734:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12735:                        "$dir_root/$docudom/$docuname/$destination";
                   12736:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12737:                     $error = &mt('Archive file not found.');
                   12738:                 }
                   12739:             }
1.1065    raeburn  12740:             my (@to_overwrite,@to_skip);
                   12741:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12742:                 my $total = $env{'form.archive_overwrite_total'};
                   12743:                 for (my $i=0; $i<$total; $i++) {
                   12744:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12745:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12746:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12747:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12748:                     }
                   12749:                 }
                   12750:             }
                   12751:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12752:             my $numoverwrite = scalar(@to_overwrite);
                   12753:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12754:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12755:             } elsif ($dir eq '') {
1.1055    raeburn  12756:                 $error = &mt('Directory containing archive file unavailable.');
                   12757:             } elsif (!$error) {
1.1065    raeburn  12758:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12759:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12760:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12761:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12762:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12763:                         ($decompressed,$display) =
                   12764:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12765:                         foreach my $item (@to_skip) {
                   12766:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12767:                                 if (-f "$dir/$tempdir/$item") {
                   12768:                                     unlink("$dir/$tempdir/$item");
                   12769:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12770:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12771:                                 }
                   12772:                             }
                   12773:                         }
                   12774:                         foreach my $item (@to_overwrite) {
                   12775:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12776:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12777:                                     if (-f "$dir/$item") {
                   12778:                                         unlink("$dir/$item");
                   12779:                                     } elsif (-d "$dir/$item") {
                   12780:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12781:                                     }
                   12782:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12783:                                 }
1.1065    raeburn  12784:                             }
                   12785:                         }
1.1075.2.128  raeburn  12786:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12787:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12788:                         }
1.1065    raeburn  12789:                     }
                   12790:                 } else {
                   12791:                     ($decompressed,$display) = 
                   12792:                         &decompress_uploaded_file($file,$dir);
                   12793:                 }
1.1055    raeburn  12794:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12795:                     $output = '<p class="LC_info">'.
                   12796:                               &mt('Files extracted successfully from archive.').
                   12797:                               '</p>'."\n";
1.1055    raeburn  12798:                     my ($warning,$result,@contents);
                   12799:                     my ($newdirlistref,$newlisterror) =
                   12800:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12801:                                                  $docuname,1);
                   12802:                     my (%is_dir,%changes,@newitems);
                   12803:                     my $dirptr = 16384;
1.1065    raeburn  12804:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12805:                         foreach my $dir_line (@{$newdirlistref}) {
                   12806:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12807:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12808:                                 push(@newitems,$item);
                   12809:                                 if ($dirptr&$testdir) {
                   12810:                                     $is_dir{$item} = 1;
                   12811:                                 }
                   12812:                                 $changes{$item} = 1;
                   12813:                             }
                   12814:                         }
                   12815:                     }
                   12816:                     if (keys(%changes) > 0) {
                   12817:                         foreach my $item (sort(@newitems)) {
                   12818:                             if ($changes{$item}) {
                   12819:                                 push(@contents,$item);
                   12820:                             }
                   12821:                         }
                   12822:                     }
                   12823:                     if (@contents > 0) {
1.1067    raeburn  12824:                         my $wantform;
                   12825:                         unless ($env{'form.autoextract_camtasia'}) {
                   12826:                             $wantform = 1;
                   12827:                         }
1.1056    raeburn  12828:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12829:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12830:                                                                 $currdir,\%is_dir,
                   12831:                                                                 \%children,\%parent,
1.1056    raeburn  12832:                                                                 \@contents,\%dirorder,
                   12833:                                                                 \%titles,$wantform);
1.1055    raeburn  12834:                         if ($datatable ne '') {
                   12835:                             $output .= &archive_options_form('decompressed',$datatable,
                   12836:                                                              $count,$hiddenelem);
1.1065    raeburn  12837:                             my $startcount = 6;
1.1055    raeburn  12838:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12839:                                                            \%titles,\%children);
1.1055    raeburn  12840:                         }
1.1067    raeburn  12841:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12842:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12843:                             my %displayed;
                   12844:                             my $total = 1;
                   12845:                             $env{'form.archive_directory'} = [];
                   12846:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12847:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12848:                                 $path =~ s{/$}{};
                   12849:                                 my $item;
                   12850:                                 if ($path ne '') {
                   12851:                                     $item = "$path/$titles{$i}";
                   12852:                                 } else {
                   12853:                                     $item = $titles{$i};
                   12854:                                 }
                   12855:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12856:                                 if ($item eq $contents[0]) {
                   12857:                                     push(@{$env{'form.archive_directory'}},$i);
                   12858:                                     $env{'form.archive_'.$i} = 'display';
                   12859:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12860:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12861:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12862:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12863:                                     $env{'form.archive_'.$i} = 'display';
                   12864:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12865:                                     $displayed{'web'} = $i;
                   12866:                                 } else {
1.1075.2.59  raeburn  12867:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12868:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12869:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12870:                                         push(@{$env{'form.archive_directory'}},$i);
                   12871:                                     }
                   12872:                                     $env{'form.archive_'.$i} = 'dependency';
                   12873:                                 }
                   12874:                                 $total ++;
                   12875:                             }
                   12876:                             for (my $i=1; $i<$total; $i++) {
                   12877:                                 next if ($i == $displayed{'web'});
                   12878:                                 next if ($i == $displayed{'folder'});
                   12879:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12880:                             }
                   12881:                             $env{'form.phase'} = 'decompress_cleanup';
                   12882:                             $env{'form.archivedelete'} = 1;
                   12883:                             $env{'form.archive_count'} = $total-1;
                   12884:                             $output .=
                   12885:                                 &process_extracted_files('coursedocs',$docudom,
                   12886:                                                          $docuname,$destination,
                   12887:                                                          $dir_root,$hiddenelem);
                   12888:                         }
1.1055    raeburn  12889:                     } else {
                   12890:                         $warning = &mt('No new items extracted from archive file.');
                   12891:                     }
                   12892:                 } else {
                   12893:                     $output = $display;
                   12894:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12895:                 }
                   12896:             }
                   12897:         }
                   12898:     }
                   12899:     if ($error) {
                   12900:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12901:                    $error.'</p>'."\n";
                   12902:     }
                   12903:     if ($warning) {
                   12904:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12905:     }
                   12906:     return $output;
                   12907: }
                   12908: 
                   12909: sub get_extracted {
1.1056    raeburn  12910:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12911:         $titles,$wantform) = @_;
1.1055    raeburn  12912:     my $count = 0;
                   12913:     my $depth = 0;
                   12914:     my $datatable;
1.1056    raeburn  12915:     my @hierarchy;
1.1055    raeburn  12916:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12917:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12918:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12919:     foreach my $item (@{$contents}) {
                   12920:         $count ++;
1.1056    raeburn  12921:         @{$dirorder->{$count}} = @hierarchy;
                   12922:         $titles->{$count} = $item;
1.1055    raeburn  12923:         &archive_hierarchy($depth,$count,$parent,$children);
                   12924:         if ($wantform) {
                   12925:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12926:                                        $currdir,$depth,$count);
                   12927:         }
                   12928:         if ($is_dir->{$item}) {
                   12929:             $depth ++;
1.1056    raeburn  12930:             push(@hierarchy,$count);
                   12931:             $parent->{$depth} = $count;
1.1055    raeburn  12932:             $datatable .=
                   12933:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12934:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12935:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12936:             $depth --;
1.1056    raeburn  12937:             pop(@hierarchy);
1.1055    raeburn  12938:         }
                   12939:     }
                   12940:     return ($count,$datatable);
                   12941: }
                   12942: 
                   12943: sub recurse_extracted_archive {
1.1056    raeburn  12944:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12945:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12946:     my $result='';
1.1056    raeburn  12947:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12948:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12949:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12950:         return $result;
                   12951:     }
                   12952:     my $dirptr = 16384;
                   12953:     my ($newdirlistref,$newlisterror) =
                   12954:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12955:     if (ref($newdirlistref) eq 'ARRAY') {
                   12956:         foreach my $dir_line (@{$newdirlistref}) {
                   12957:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12958:             unless ($item =~ /^\.+$/) {
                   12959:                 $$count ++;
1.1056    raeburn  12960:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12961:                 $titles->{$$count} = $item;
1.1055    raeburn  12962:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12963: 
1.1055    raeburn  12964:                 my $is_dir;
                   12965:                 if ($dirptr&$testdir) {
                   12966:                     $is_dir = 1;
                   12967:                 }
                   12968:                 if ($wantform) {
                   12969:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12970:                 }
                   12971:                 if ($is_dir) {
                   12972:                     $$depth ++;
1.1056    raeburn  12973:                     push(@{$hierarchy},$$count);
                   12974:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12975:                     $result .=
                   12976:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12977:                                                    $docuname,$depth,$count,
1.1056    raeburn  12978:                                                    $hierarchy,$dirorder,$children,
                   12979:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12980:                     $$depth --;
1.1056    raeburn  12981:                     pop(@{$hierarchy});
1.1055    raeburn  12982:                 }
                   12983:             }
                   12984:         }
                   12985:     }
                   12986:     return $result;
                   12987: }
                   12988: 
                   12989: sub archive_hierarchy {
                   12990:     my ($depth,$count,$parent,$children) =@_;
                   12991:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12992:         if (exists($parent->{$depth})) {
                   12993:              $children->{$parent->{$depth}} .= $count.':';
                   12994:         }
                   12995:     }
                   12996:     return;
                   12997: }
                   12998: 
                   12999: sub archive_row {
                   13000:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13001:     my ($name) = ($item =~ m{([^/]+)$});
                   13002:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13003:                                        'display'    => 'Add as file',
1.1055    raeburn  13004:                                        'dependency' => 'Include as dependency',
                   13005:                                        'discard'    => 'Discard',
                   13006:                                       );
                   13007:     if ($is_dir) {
1.1059    raeburn  13008:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13009:     }
1.1056    raeburn  13010:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13011:     my $offset = 0;
1.1055    raeburn  13012:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13013:         $offset ++;
1.1065    raeburn  13014:         if ($action ne 'display') {
                   13015:             $offset ++;
                   13016:         }  
1.1055    raeburn  13017:         $output .= '<td><span class="LC_nobreak">'.
                   13018:                    '<label><input type="radio" name="archive_'.$count.
                   13019:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13020:         my $text = $choices{$action};
                   13021:         if ($is_dir) {
                   13022:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13023:             if ($action eq 'display') {
1.1059    raeburn  13024:                 $text = &mt('Add as folder');
1.1055    raeburn  13025:             }
1.1056    raeburn  13026:         } else {
                   13027:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13028: 
                   13029:         }
                   13030:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13031:         if ($action eq 'dependency') {
                   13032:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13033:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13034:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13035:                        '<option value=""></option>'."\n".
                   13036:                        '</select>'."\n".
                   13037:                        '</div>';
1.1059    raeburn  13038:         } elsif ($action eq 'display') {
                   13039:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13040:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13041:                        '</div>';
1.1055    raeburn  13042:         }
1.1056    raeburn  13043:         $output .= '</td>';
1.1055    raeburn  13044:     }
                   13045:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13046:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13047:     for (my $i=0; $i<$depth; $i++) {
                   13048:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13049:     }
                   13050:     if ($is_dir) {
                   13051:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13052:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13053:     } else {
                   13054:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13055:     }
                   13056:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13057:                &end_data_table_row();
                   13058:     return $output;
                   13059: }
                   13060: 
                   13061: sub archive_options_form {
1.1065    raeburn  13062:     my ($form,$display,$count,$hiddenelem) = @_;
                   13063:     my %lt = &Apache::lonlocal::texthash(
                   13064:                perm => 'Permanently remove archive file?',
                   13065:                hows => 'How should each extracted item be incorporated in the course?',
                   13066:                cont => 'Content actions for all',
                   13067:                addf => 'Add as folder/file',
                   13068:                incd => 'Include as dependency for a displayed file',
                   13069:                disc => 'Discard',
                   13070:                no   => 'No',
                   13071:                yes  => 'Yes',
                   13072:                save => 'Save',
                   13073:     );
                   13074:     my $output = <<"END";
                   13075: <form name="$form" method="post" action="">
                   13076: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13077: <label>
                   13078:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13079: </label>
                   13080: &nbsp;
                   13081: <label>
                   13082:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13083: </span>
                   13084: </p>
                   13085: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13086: <br />$lt{'hows'}
                   13087: <div class="LC_columnSection">
                   13088:   <fieldset>
                   13089:     <legend>$lt{'cont'}</legend>
                   13090:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13091:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13092:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13093:   </fieldset>
                   13094: </div>
                   13095: END
                   13096:     return $output.
1.1055    raeburn  13097:            &start_data_table()."\n".
1.1065    raeburn  13098:            $display."\n".
1.1055    raeburn  13099:            &end_data_table()."\n".
                   13100:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13101:            $hiddenelem.
1.1065    raeburn  13102:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13103:            '</form>';
                   13104: }
                   13105: 
                   13106: sub archive_javascript {
1.1056    raeburn  13107:     my ($startcount,$numitems,$titles,$children) = @_;
                   13108:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13109:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13110:     my $scripttag = <<START;
                   13111: <script type="text/javascript">
                   13112: // <![CDATA[
                   13113: 
                   13114: function checkAll(form,prefix) {
                   13115:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13116:     for (var i=0; i < form.elements.length; i++) {
                   13117:         var id = form.elements[i].id;
                   13118:         if ((id != '') && (id != undefined)) {
                   13119:             if (idstr.test(id)) {
                   13120:                 if (form.elements[i].type == 'radio') {
                   13121:                     form.elements[i].checked = true;
1.1056    raeburn  13122:                     var nostart = i-$startcount;
1.1059    raeburn  13123:                     var offset = nostart%7;
                   13124:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13125:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13126:                 }
                   13127:             }
                   13128:         }
                   13129:     }
                   13130: }
                   13131: 
                   13132: function propagateCheck(form,count) {
                   13133:     if (count > 0) {
1.1059    raeburn  13134:         var startelement = $startcount + ((count-1) * 7);
                   13135:         for (var j=1; j<6; j++) {
                   13136:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13137:                 var item = startelement + j; 
                   13138:                 if (form.elements[item].type == 'radio') {
                   13139:                     if (form.elements[item].checked) {
                   13140:                         containerCheck(form,count,j);
                   13141:                         break;
                   13142:                     }
1.1055    raeburn  13143:                 }
                   13144:             }
                   13145:         }
                   13146:     }
                   13147: }
                   13148: 
                   13149: numitems = $numitems
1.1056    raeburn  13150: var titles = new Array(numitems);
                   13151: var parents = new Array(numitems);
1.1055    raeburn  13152: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13153:     parents[i] = new Array;
1.1055    raeburn  13154: }
1.1059    raeburn  13155: var maintitle = '$maintitle';
1.1055    raeburn  13156: 
                   13157: START
                   13158: 
1.1056    raeburn  13159:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13160:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13161:         for (my $i=0; $i<@contents; $i ++) {
                   13162:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13163:         }
                   13164:     }
                   13165: 
1.1056    raeburn  13166:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13167:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13168:     }
                   13169: 
1.1055    raeburn  13170:     $scripttag .= <<END;
                   13171: 
                   13172: function containerCheck(form,count,offset) {
                   13173:     if (count > 0) {
1.1056    raeburn  13174:         dependencyCheck(form,count,offset);
1.1059    raeburn  13175:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13176:         form.elements[item].checked = true;
                   13177:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13178:             if (parents[count].length > 0) {
                   13179:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13180:                     containerCheck(form,parents[count][j],offset);
                   13181:                 }
                   13182:             }
                   13183:         }
                   13184:     }
                   13185: }
                   13186: 
                   13187: function dependencyCheck(form,count,offset) {
                   13188:     if (count > 0) {
1.1059    raeburn  13189:         var chosen = (offset+$startcount)+7*(count-1);
                   13190:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13191:         var currtype = form.elements[depitem].type;
                   13192:         if (form.elements[chosen].value == 'dependency') {
                   13193:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13194:             form.elements[depitem].options.length = 0;
                   13195:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  13196:             for (var i=1; i<=numitems; i++) {
                   13197:                 if (i == count) {
                   13198:                     continue;
                   13199:                 }
1.1059    raeburn  13200:                 var startelement = $startcount + (i-1) * 7;
                   13201:                 for (var j=1; j<6; j++) {
                   13202:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13203:                         var item = startelement + j;
                   13204:                         if (form.elements[item].type == 'radio') {
                   13205:                             if (form.elements[item].checked) {
                   13206:                                 if (form.elements[item].value == 'display') {
                   13207:                                     var n = form.elements[depitem].options.length;
                   13208:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13209:                                 }
                   13210:                             }
                   13211:                         }
                   13212:                     }
                   13213:                 }
                   13214:             }
                   13215:         } else {
                   13216:             document.getElementById('arc_depon_'+count).style.display='none';
                   13217:             form.elements[depitem].options.length = 0;
                   13218:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13219:         }
1.1059    raeburn  13220:         titleCheck(form,count,offset);
1.1056    raeburn  13221:     }
                   13222: }
                   13223: 
                   13224: function propagateSelect(form,count,offset) {
                   13225:     if (count > 0) {
1.1065    raeburn  13226:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13227:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13228:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13229:             if (parents[count].length > 0) {
                   13230:                 for (var j=0; j<parents[count].length; j++) {
                   13231:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13232:                 }
                   13233:             }
                   13234:         }
                   13235:     }
                   13236: }
1.1056    raeburn  13237: 
                   13238: function containerSelect(form,count,offset,picked) {
                   13239:     if (count > 0) {
1.1065    raeburn  13240:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13241:         if (form.elements[item].type == 'radio') {
                   13242:             if (form.elements[item].value == 'dependency') {
                   13243:                 if (form.elements[item+1].type == 'select-one') {
                   13244:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13245:                         if (form.elements[item+1].options[i].value == picked) {
                   13246:                             form.elements[item+1].selectedIndex = i;
                   13247:                             break;
                   13248:                         }
                   13249:                     }
                   13250:                 }
                   13251:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13252:                     if (parents[count].length > 0) {
                   13253:                         for (var j=0; j<parents[count].length; j++) {
                   13254:                             containerSelect(form,parents[count][j],offset,picked);
                   13255:                         }
                   13256:                     }
                   13257:                 }
                   13258:             }
                   13259:         }
                   13260:     }
                   13261: }
                   13262: 
1.1059    raeburn  13263: function titleCheck(form,count,offset) {
                   13264:     if (count > 0) {
                   13265:         var chosen = (offset+$startcount)+7*(count-1);
                   13266:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13267:         var currtype = form.elements[depitem].type;
                   13268:         if (form.elements[chosen].value == 'display') {
                   13269:             document.getElementById('arc_title_'+count).style.display='block';
                   13270:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13271:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13272:             }
                   13273:         } else {
                   13274:             document.getElementById('arc_title_'+count).style.display='none';
                   13275:             if (currtype == 'text') { 
                   13276:                 document.getElementById('archive_title_'+count).value='';
                   13277:             }
                   13278:         }
                   13279:     }
                   13280:     return;
                   13281: }
                   13282: 
1.1055    raeburn  13283: // ]]>
                   13284: </script>
                   13285: END
                   13286:     return $scripttag;
                   13287: }
                   13288: 
                   13289: sub process_extracted_files {
1.1067    raeburn  13290:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13291:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  13292:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13293:     my @ids=&Apache::lonnet::current_machine_ids();
                   13294:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13295:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13296:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13297:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13298:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13299:         $pathtocheck = "$dir_root/$destination";
                   13300:         $dir = $dir_root;
                   13301:         $ishome = 1;
                   13302:     } else {
                   13303:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13304:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  13305:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13306:     }
                   13307:     my $currdir = "$dir_root/$destination";
                   13308:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13309:     if ($env{'form.folderpath'}) {
                   13310:         my @items = split('&',$env{'form.folderpath'});
                   13311:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  13312:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13313:             $containers{'0'}='page';
                   13314:         } else {
                   13315:             $containers{'0'}='sequence';
                   13316:         }
1.1055    raeburn  13317:     }
                   13318:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13319:     if ($numitems) {
                   13320:         for (my $i=1; $i<=$numitems; $i++) {
                   13321:             my $path = $env{'form.archive_content_'.$i};
                   13322:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13323:                 my $item = $1;
                   13324:                 $toplevelitems{$item} = $i;
                   13325:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13326:                     $is_dir{$item} = 1;
                   13327:                 }
                   13328:             }
                   13329:         }
                   13330:     }
1.1067    raeburn  13331:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13332:     if (keys(%toplevelitems) > 0) {
                   13333:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13334:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13335:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13336:     }
1.1066    raeburn  13337:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13338:     if ($numitems) {
                   13339:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  13340:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13341:             my $path = $env{'form.archive_content_'.$i};
                   13342:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13343:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13344:                     if ($prefix ne '' && $path ne '') {
                   13345:                         if (-e $prefix.$path) {
1.1066    raeburn  13346:                             if ((@archdirs > 0) && 
                   13347:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13348:                                 $todeletedir{$prefix.$path} = 1;
                   13349:                             } else {
                   13350:                                 $todelete{$prefix.$path} = 1;
                   13351:                             }
1.1055    raeburn  13352:                         }
                   13353:                     }
                   13354:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13355:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13356:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13357:                     $docstitle = $env{'form.archive_title_'.$i};
                   13358:                     if ($docstitle eq '') {
                   13359:                         $docstitle = $title;
                   13360:                     }
1.1055    raeburn  13361:                     $outer = 0;
1.1056    raeburn  13362:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13363:                         if (@{$dirorder{$i}} > 0) {
                   13364:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13365:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13366:                                     $outer = $item;
                   13367:                                     last;
                   13368:                                 }
                   13369:                             }
                   13370:                         }
                   13371:                     }
                   13372:                     my ($errtext,$fatal) = 
                   13373:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13374:                                                '/'.$folders{$outer}.'.'.
                   13375:                                                $containers{$outer});
                   13376:                     next if ($fatal);
                   13377:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13378:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13379:                             $mapinner{$i} = time;
1.1055    raeburn  13380:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13381:                             $containers{$i} = 'sequence';
                   13382:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13383:                                       $folders{$i}.'.'.$containers{$i};
                   13384:                             my $newidx = &LONCAPA::map::getresidx();
                   13385:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13386:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13387:                             push(@LONCAPA::map::order,$newidx);
                   13388:                             my ($outtext,$errtext) =
                   13389:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13390:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  13391:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13392:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13393:                             unless ($errtext) {
1.1075.2.128  raeburn  13394:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13395:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13396:                                             '</li>'."\n";
1.1067    raeburn  13397:                             }
1.1055    raeburn  13398:                         }
                   13399:                     } else {
                   13400:                         if ($context eq 'coursedocs') {
                   13401:                             my $newidx=&LONCAPA::map::getresidx();
                   13402:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13403:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13404:                                       $title;
1.1075.2.128  raeburn  13405:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13406:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13407:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13408:                                 }
1.1075.2.128  raeburn  13409:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13410:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13411:                                 }
                   13412:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13413:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13414:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13415:                                         unless ($ishome) {
                   13416:                                             my $fetch = "$newdest{$i}/$title";
                   13417:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13418:                                             $prompttofetch{$fetch} = 1;
                   13419:                                         }
                   13420:                                    }
                   13421:                                 }
                   13422:                                 $LONCAPA::map::resources[$newidx]=
                   13423:                                     $docstitle.':'.$url.':false:normal:res';
                   13424:                                 push(@LONCAPA::map::order, $newidx);
                   13425:                                 my ($outtext,$errtext)=
                   13426:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13427:                                                             $docuname.'/'.$folders{$outer}.
                   13428:                                                             '.'.$containers{$outer},1,1);
                   13429:                                 unless ($errtext) {
                   13430:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13431:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13432:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13433:                                                    '</li>'."\n";
                   13434:                                     }
1.1067    raeburn  13435:                                 }
1.1075.2.128  raeburn  13436:                             } else {
                   13437:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13438:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13439:                             }
1.1055    raeburn  13440:                         }
                   13441:                     }
1.1075.2.11  raeburn  13442:                 }
                   13443:             } else {
1.1075.2.128  raeburn  13444:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13445:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13446:             }
                   13447:         }
                   13448:         for (my $i=1; $i<=$numitems; $i++) {
                   13449:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13450:             my $path = $env{'form.archive_content_'.$i};
                   13451:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13452:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13453:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13454:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13455:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13456:                         my ($itemidx,$fullpath,$relpath);
                   13457:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13458:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13459:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13460:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13461:                                     $itemidx = $j;
1.1056    raeburn  13462:                                 }
                   13463:                             }
1.1075.2.11  raeburn  13464:                         }
                   13465:                         if ($itemidx eq '') {
                   13466:                             $itemidx =  0;
                   13467:                         }
                   13468:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13469:                             if ($mapinner{$referrer{$i}}) {
                   13470:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13471:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13472:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13473:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13474:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13475:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13476:                                             if (!-e $fullpath) {
                   13477:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13478:                                             }
                   13479:                                         }
1.1075.2.11  raeburn  13480:                                     } else {
                   13481:                                         last;
1.1056    raeburn  13482:                                     }
1.1075.2.11  raeburn  13483:                                 }
                   13484:                             }
                   13485:                         } elsif ($newdest{$referrer{$i}}) {
                   13486:                             $fullpath = $newdest{$referrer{$i}};
                   13487:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13488:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13489:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13490:                                     last;
                   13491:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13492:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13493:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13494:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13495:                                         if (!-e $fullpath) {
                   13496:                                             mkdir($fullpath,0755);
1.1056    raeburn  13497:                                         }
                   13498:                                     }
1.1075.2.11  raeburn  13499:                                 } else {
                   13500:                                     last;
1.1056    raeburn  13501:                                 }
1.1075.2.11  raeburn  13502:                             }
                   13503:                         }
                   13504:                         if ($fullpath ne '') {
                   13505:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13506:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13507:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13508:                                 }
1.1075.2.11  raeburn  13509:                             }
                   13510:                             if (-e "$fullpath/$title") {
                   13511:                                 my $showpath;
                   13512:                                 if ($relpath ne '') {
                   13513:                                     $showpath = "$relpath/$title";
                   13514:                                 } else {
                   13515:                                     $showpath = "/$title";
1.1056    raeburn  13516:                                 }
1.1075.2.128  raeburn  13517:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13518:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13519:                                            '</li>'."\n";
                   13520:                                 unless ($ishome) {
                   13521:                                     my $fetch = "$fullpath/$title";
                   13522:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13523:                                     $prompttofetch{$fetch} = 1;
                   13524:                                 }
1.1055    raeburn  13525:                             }
                   13526:                         }
                   13527:                     }
1.1075.2.11  raeburn  13528:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13529:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13530:                                     &HTML::Entities::encode($path,'<>&"'),
                   13531:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13532:                                 '<br />';
1.1055    raeburn  13533:                 }
                   13534:             } else {
1.1075.2.128  raeburn  13535:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13536:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13537:             }
                   13538:         }
                   13539:         if (keys(%todelete)) {
                   13540:             foreach my $key (keys(%todelete)) {
                   13541:                 unlink($key);
1.1066    raeburn  13542:             }
                   13543:         }
                   13544:         if (keys(%todeletedir)) {
                   13545:             foreach my $key (keys(%todeletedir)) {
                   13546:                 rmdir($key);
                   13547:             }
                   13548:         }
                   13549:         foreach my $dir (sort(keys(%is_dir))) {
                   13550:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13551:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13552:             }
                   13553:         }
1.1067    raeburn  13554:         if ($result ne '') {
                   13555:             $output .= '<ul>'."\n".
                   13556:                        $result."\n".
                   13557:                        '</ul>';
                   13558:         }
                   13559:         unless ($ishome) {
                   13560:             my $replicationfail;
                   13561:             foreach my $item (keys(%prompttofetch)) {
                   13562:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13563:                 unless ($fetchresult eq 'ok') {
                   13564:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13565:                 }
                   13566:             }
                   13567:             if ($replicationfail) {
                   13568:                 $output .= '<p class="LC_error">'.
                   13569:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13570:                            $replicationfail.
                   13571:                            '</ul></p>';
                   13572:             }
                   13573:         }
1.1055    raeburn  13574:     } else {
                   13575:         $warning = &mt('No items found in archive.');
                   13576:     }
                   13577:     if ($error) {
                   13578:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13579:                    $error.'</p>'."\n";
                   13580:     }
                   13581:     if ($warning) {
                   13582:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13583:     }
                   13584:     return $output;
                   13585: }
                   13586: 
1.1066    raeburn  13587: sub cleanup_empty_dirs {
                   13588:     my ($path) = @_;
                   13589:     if (($path ne '') && (-d $path)) {
                   13590:         if (opendir(my $dirh,$path)) {
                   13591:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13592:             my $numitems = 0;
                   13593:             foreach my $item (@dircontents) {
                   13594:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13595:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13596:                     if (-e "$path/$item") {
                   13597:                         $numitems ++;
                   13598:                     }
                   13599:                 } else {
                   13600:                     $numitems ++;
                   13601:                 }
                   13602:             }
                   13603:             if ($numitems == 0) {
                   13604:                 rmdir($path);
                   13605:             }
                   13606:             closedir($dirh);
                   13607:         }
                   13608:     }
                   13609:     return;
                   13610: }
                   13611: 
1.41      ng       13612: =pod
1.45      matthew  13613: 
1.1075.2.56  raeburn  13614: =item * &get_folder_hierarchy()
1.1068    raeburn  13615: 
                   13616: Provides hierarchy of names of folders/sub-folders containing the current
                   13617: item,
                   13618: 
                   13619: Inputs: 3
                   13620:      - $navmap - navmaps object
                   13621: 
                   13622:      - $map - url for map (either the trigger itself, or map containing
                   13623:                            the resource, which is the trigger).
                   13624: 
                   13625:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13626: 
                   13627: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13628: 
                   13629: =cut
                   13630: 
                   13631: sub get_folder_hierarchy {
                   13632:     my ($navmap,$map,$showitem) = @_;
                   13633:     my @pathitems;
                   13634:     if (ref($navmap)) {
                   13635:         my $mapres = $navmap->getResourceByUrl($map);
                   13636:         if (ref($mapres)) {
                   13637:             my $pcslist = $mapres->map_hierarchy();
                   13638:             if ($pcslist ne '') {
                   13639:                 my @pcs = split(/,/,$pcslist);
                   13640:                 foreach my $pc (@pcs) {
                   13641:                     if ($pc == 1) {
1.1075.2.38  raeburn  13642:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13643:                     } else {
                   13644:                         my $res = $navmap->getByMapPc($pc);
                   13645:                         if (ref($res)) {
                   13646:                             my $title = $res->compTitle();
                   13647:                             $title =~ s/\W+/_/g;
                   13648:                             if ($title ne '') {
                   13649:                                 push(@pathitems,$title);
                   13650:                             }
                   13651:                         }
                   13652:                     }
                   13653:                 }
                   13654:             }
1.1071    raeburn  13655:             if ($showitem) {
                   13656:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13657:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13658:                 } else {
                   13659:                     my $maptitle = $mapres->compTitle();
                   13660:                     $maptitle =~ s/\W+/_/g;
                   13661:                     if ($maptitle ne '') {
                   13662:                         push(@pathitems,$maptitle);
                   13663:                     }
1.1068    raeburn  13664:                 }
                   13665:             }
                   13666:         }
                   13667:     }
                   13668:     return @pathitems;
                   13669: }
                   13670: 
                   13671: =pod
                   13672: 
1.1015    raeburn  13673: =item * &get_turnedin_filepath()
                   13674: 
                   13675: Determines path in a user's portfolio file for storage of files uploaded
                   13676: to a specific essayresponse or dropbox item.
                   13677: 
                   13678: Inputs: 3 required + 1 optional.
                   13679: $symb is symb for resource, $uname and $udom are for current user (required).
                   13680: $caller is optional (can be "submission", if routine is called when storing
                   13681: an upoaded file when "Submit Answer" button was pressed).
                   13682: 
                   13683: Returns array containing $path and $multiresp. 
                   13684: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13685: than one file upload item.  Callers of routine should append partid as a 
                   13686: subdirectory to $path in cases where $multiresp is 1.
                   13687: 
                   13688: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13689: 
                   13690: =cut
                   13691: 
                   13692: sub get_turnedin_filepath {
                   13693:     my ($symb,$uname,$udom,$caller) = @_;
                   13694:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13695:     my $turnindir;
                   13696:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13697:     $turnindir = $userhash{'turnindir'};
                   13698:     my ($path,$multiresp);
                   13699:     if ($turnindir eq '') {
                   13700:         if ($caller eq 'submission') {
                   13701:             $turnindir = &mt('turned in');
                   13702:             $turnindir =~ s/\W+/_/g;
                   13703:             my %newhash = (
                   13704:                             'turnindir' => $turnindir,
                   13705:                           );
                   13706:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13707:         }
                   13708:     }
                   13709:     if ($turnindir ne '') {
                   13710:         $path = '/'.$turnindir.'/';
                   13711:         my ($multipart,$turnin,@pathitems);
                   13712:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13713:         if (defined($navmap)) {
                   13714:             my $mapres = $navmap->getResourceByUrl($map);
                   13715:             if (ref($mapres)) {
                   13716:                 my $pcslist = $mapres->map_hierarchy();
                   13717:                 if ($pcslist ne '') {
                   13718:                     foreach my $pc (split(/,/,$pcslist)) {
                   13719:                         my $res = $navmap->getByMapPc($pc);
                   13720:                         if (ref($res)) {
                   13721:                             my $title = $res->compTitle();
                   13722:                             $title =~ s/\W+/_/g;
                   13723:                             if ($title ne '') {
1.1075.2.48  raeburn  13724:                                 if (($pc > 1) && (length($title) > 12)) {
                   13725:                                     $title = substr($title,0,12);
                   13726:                                 }
1.1015    raeburn  13727:                                 push(@pathitems,$title);
                   13728:                             }
                   13729:                         }
                   13730:                     }
                   13731:                 }
                   13732:                 my $maptitle = $mapres->compTitle();
                   13733:                 $maptitle =~ s/\W+/_/g;
                   13734:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13735:                     if (length($maptitle) > 12) {
                   13736:                         $maptitle = substr($maptitle,0,12);
                   13737:                     }
1.1015    raeburn  13738:                     push(@pathitems,$maptitle);
                   13739:                 }
                   13740:                 unless ($env{'request.state'} eq 'construct') {
                   13741:                     my $res = $navmap->getBySymb($symb);
                   13742:                     if (ref($res)) {
                   13743:                         my $partlist = $res->parts();
                   13744:                         my $totaluploads = 0;
                   13745:                         if (ref($partlist) eq 'ARRAY') {
                   13746:                             foreach my $part (@{$partlist}) {
                   13747:                                 my @types = $res->responseType($part);
                   13748:                                 my @ids = $res->responseIds($part);
                   13749:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13750:                                     if ($types[$i] eq 'essay') {
                   13751:                                         my $partid = $part.'_'.$ids[$i];
                   13752:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13753:                                             $totaluploads ++;
                   13754:                                         }
                   13755:                                     }
                   13756:                                 }
                   13757:                             }
                   13758:                             if ($totaluploads > 1) {
                   13759:                                 $multiresp = 1;
                   13760:                             }
                   13761:                         }
                   13762:                     }
                   13763:                 }
                   13764:             } else {
                   13765:                 return;
                   13766:             }
                   13767:         } else {
                   13768:             return;
                   13769:         }
                   13770:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13771:         $restitle =~ s/\W+/_/g;
                   13772:         if ($restitle eq '') {
                   13773:             $restitle = ($resurl =~ m{/[^/]+$});
                   13774:             if ($restitle eq '') {
                   13775:                 $restitle = time;
                   13776:             }
                   13777:         }
1.1075.2.48  raeburn  13778:         if (length($restitle) > 12) {
                   13779:             $restitle = substr($restitle,0,12);
                   13780:         }
1.1015    raeburn  13781:         push(@pathitems,$restitle);
                   13782:         $path .= join('/',@pathitems);
                   13783:     }
                   13784:     return ($path,$multiresp);
                   13785: }
                   13786: 
                   13787: =pod
                   13788: 
1.464     albertel 13789: =back
1.41      ng       13790: 
1.112     bowersj2 13791: =head1 CSV Upload/Handling functions
1.38      albertel 13792: 
1.41      ng       13793: =over 4
                   13794: 
1.648     raeburn  13795: =item * &upfile_store($r)
1.41      ng       13796: 
                   13797: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13798: needs $env{'form.upfile'}
1.41      ng       13799: returns $datatoken to be put into hidden field
                   13800: 
                   13801: =cut
1.31      albertel 13802: 
                   13803: sub upfile_store {
                   13804:     my $r=shift;
1.258     albertel 13805:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13806:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13807:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13808:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13809: 
1.1075.2.128  raeburn  13810:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13811:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13812:                                      time.'_'.$$);
                   13813:     return if ($datatoken eq '');
                   13814: 
1.31      albertel 13815:     {
1.158     raeburn  13816:         my $datafile = $r->dir_config('lonDaemons').
                   13817:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13818:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13819:             print $fh $env{'form.upfile'};
1.158     raeburn  13820:             close($fh);
                   13821:         }
1.31      albertel 13822:     }
                   13823:     return $datatoken;
                   13824: }
                   13825: 
1.56      matthew  13826: =pod
                   13827: 
1.1075.2.128  raeburn  13828: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13829: 
                   13830: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13831: $datatoken is the name to assign to the temporary file.
1.258     albertel 13832: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13833: 
                   13834: =cut
1.31      albertel 13835: 
                   13836: sub load_tmp_file {
1.1075.2.128  raeburn  13837:     my ($r,$datatoken) = @_;
                   13838:     return if ($datatoken eq '');
1.31      albertel 13839:     my @studentdata=();
                   13840:     {
1.158     raeburn  13841:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13842:                               '/tmp/'.$datatoken.'.tmp';
                   13843:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13844:             @studentdata=<$fh>;
                   13845:             close($fh);
                   13846:         }
1.31      albertel 13847:     }
1.258     albertel 13848:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13849: }
                   13850: 
1.1075.2.128  raeburn  13851: sub valid_datatoken {
                   13852:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13853:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13854:         return $datatoken;
                   13855:     }
                   13856:     return;
                   13857: }
                   13858: 
1.56      matthew  13859: =pod
                   13860: 
1.648     raeburn  13861: =item * &upfile_record_sep()
1.41      ng       13862: 
                   13863: Separate uploaded file into records
                   13864: returns array of records,
1.258     albertel 13865: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13866: 
                   13867: =cut
1.31      albertel 13868: 
                   13869: sub upfile_record_sep {
1.258     albertel 13870:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13871:     } else {
1.248     albertel 13872: 	my @records;
1.258     albertel 13873: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13874: 	    if ($line=~/^\s*$/) { next; }
                   13875: 	    push(@records,$line);
                   13876: 	}
                   13877: 	return @records;
1.31      albertel 13878:     }
                   13879: }
                   13880: 
1.56      matthew  13881: =pod
                   13882: 
1.648     raeburn  13883: =item * &record_sep($record)
1.41      ng       13884: 
1.258     albertel 13885: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13886: 
                   13887: =cut
                   13888: 
1.263     www      13889: sub takeleft {
                   13890:     my $index=shift;
                   13891:     return substr('0000'.$index,-4,4);
                   13892: }
                   13893: 
1.31      albertel 13894: sub record_sep {
                   13895:     my $record=shift;
                   13896:     my %components=();
1.258     albertel 13897:     if ($env{'form.upfiletype'} eq 'xml') {
                   13898:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13899:         my $i=0;
1.356     albertel 13900:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13901:             $field=~s/^(\"|\')//;
                   13902:             $field=~s/(\"|\')$//;
1.263     www      13903:             $components{&takeleft($i)}=$field;
1.31      albertel 13904:             $i++;
                   13905:         }
1.258     albertel 13906:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13907:         my $i=0;
1.356     albertel 13908:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13909:             $field=~s/^(\"|\')//;
                   13910:             $field=~s/(\"|\')$//;
1.263     www      13911:             $components{&takeleft($i)}=$field;
1.31      albertel 13912:             $i++;
                   13913:         }
                   13914:     } else {
1.561     www      13915:         my $separator=',';
1.480     banghart 13916:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13917:             $separator=';';
1.480     banghart 13918:         }
1.31      albertel 13919:         my $i=0;
1.561     www      13920: # the character we are looking for to indicate the end of a quote or a record 
                   13921:         my $looking_for=$separator;
                   13922: # do not add the characters to the fields
                   13923:         my $ignore=0;
                   13924: # we just encountered a separator (or the beginning of the record)
                   13925:         my $just_found_separator=1;
                   13926: # store the field we are working on here
                   13927:         my $field='';
                   13928: # work our way through all characters in record
                   13929:         foreach my $character ($record=~/(.)/g) {
                   13930:             if ($character eq $looking_for) {
                   13931:                if ($character ne $separator) {
                   13932: # Found the end of a quote, again looking for separator
                   13933:                   $looking_for=$separator;
                   13934:                   $ignore=1;
                   13935:                } else {
                   13936: # Found a separator, store away what we got
                   13937:                   $components{&takeleft($i)}=$field;
                   13938: 	          $i++;
                   13939:                   $just_found_separator=1;
                   13940:                   $ignore=0;
                   13941:                   $field='';
                   13942:                }
                   13943:                next;
                   13944:             }
                   13945: # single or double quotation marks after a separator indicate beginning of a quote
                   13946: # we are now looking for the end of the quote and need to ignore separators
                   13947:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13948:                $looking_for=$character;
                   13949:                next;
                   13950:             }
                   13951: # ignore would be true after we reached the end of a quote
                   13952:             if ($ignore) { next; }
                   13953:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13954:             $field.=$character;
                   13955:             $just_found_separator=0; 
1.31      albertel 13956:         }
1.561     www      13957: # catch the very last entry, since we never encountered the separator
                   13958:         $components{&takeleft($i)}=$field;
1.31      albertel 13959:     }
                   13960:     return %components;
                   13961: }
                   13962: 
1.144     matthew  13963: ######################################################
                   13964: ######################################################
                   13965: 
1.56      matthew  13966: =pod
                   13967: 
1.648     raeburn  13968: =item * &upfile_select_html()
1.41      ng       13969: 
1.144     matthew  13970: Return HTML code to select a file from the users machine and specify 
                   13971: the file type.
1.41      ng       13972: 
                   13973: =cut
                   13974: 
1.144     matthew  13975: ######################################################
                   13976: ######################################################
1.31      albertel 13977: sub upfile_select_html {
1.144     matthew  13978:     my %Types = (
                   13979:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13980:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13981:                  space => &mt('Space separated'),
                   13982:                  tab   => &mt('Tabulator separated'),
                   13983: #                 xml   => &mt('HTML/XML'),
                   13984:                  );
                   13985:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13986:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13987:     foreach my $type (sort(keys(%Types))) {
                   13988:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13989:     }
                   13990:     $Str .= "</select>\n";
                   13991:     return $Str;
1.31      albertel 13992: }
                   13993: 
1.301     albertel 13994: sub get_samples {
                   13995:     my ($records,$toget) = @_;
                   13996:     my @samples=({});
                   13997:     my $got=0;
                   13998:     foreach my $rec (@$records) {
                   13999: 	my %temp = &record_sep($rec);
                   14000: 	if (! grep(/\S/, values(%temp))) { next; }
                   14001: 	if (%temp) {
                   14002: 	    $samples[$got]=\%temp;
                   14003: 	    $got++;
                   14004: 	    if ($got == $toget) { last; }
                   14005: 	}
                   14006:     }
                   14007:     return \@samples;
                   14008: }
                   14009: 
1.144     matthew  14010: ######################################################
                   14011: ######################################################
                   14012: 
1.56      matthew  14013: =pod
                   14014: 
1.648     raeburn  14015: =item * &csv_print_samples($r,$records)
1.41      ng       14016: 
                   14017: Prints a table of sample values from each column uploaded $r is an
                   14018: Apache Request ref, $records is an arrayref from
                   14019: &Apache::loncommon::upfile_record_sep
                   14020: 
                   14021: =cut
                   14022: 
1.144     matthew  14023: ######################################################
                   14024: ######################################################
1.31      albertel 14025: sub csv_print_samples {
                   14026:     my ($r,$records) = @_;
1.662     bisitz   14027:     my $samples = &get_samples($records,5);
1.301     albertel 14028: 
1.594     raeburn  14029:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14030:               &start_data_table_header_row());
1.356     albertel 14031:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14032:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14033:     $r->print(&end_data_table_header_row());
1.301     albertel 14034:     foreach my $hash (@$samples) {
1.594     raeburn  14035: 	$r->print(&start_data_table_row());
1.356     albertel 14036: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14037: 	    $r->print('<td>');
1.356     albertel 14038: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14039: 	    $r->print('</td>');
                   14040: 	}
1.594     raeburn  14041: 	$r->print(&end_data_table_row());
1.31      albertel 14042:     }
1.594     raeburn  14043:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14044: }
                   14045: 
1.144     matthew  14046: ######################################################
                   14047: ######################################################
                   14048: 
1.56      matthew  14049: =pod
                   14050: 
1.648     raeburn  14051: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14052: 
                   14053: Prints a table to create associations between values and table columns.
1.144     matthew  14054: 
1.41      ng       14055: $r is an Apache Request ref,
                   14056: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14057: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14058: 
                   14059: =cut
                   14060: 
1.144     matthew  14061: ######################################################
                   14062: ######################################################
1.31      albertel 14063: sub csv_print_select_table {
                   14064:     my ($r,$records,$d) = @_;
1.301     albertel 14065:     my $i=0;
                   14066:     my $samples = &get_samples($records,1);
1.144     matthew  14067:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14068: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14069:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14070:               '<th>'.&mt('Column').'</th>'.
                   14071:               &end_data_table_header_row()."\n");
1.356     albertel 14072:     foreach my $array_ref (@$d) {
                   14073: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14074: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14075: 
1.875     bisitz   14076: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14077: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14078: 	$r->print('<option value="none"></option>');
1.356     albertel 14079: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14080: 	    $r->print('<option value="'.$sample.'"'.
                   14081:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14082:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14083: 	}
1.594     raeburn  14084: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14085: 	$i++;
                   14086:     }
1.594     raeburn  14087:     $r->print(&end_data_table());
1.31      albertel 14088:     $i--;
                   14089:     return $i;
                   14090: }
1.56      matthew  14091: 
1.144     matthew  14092: ######################################################
                   14093: ######################################################
                   14094: 
1.56      matthew  14095: =pod
1.31      albertel 14096: 
1.648     raeburn  14097: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14098: 
                   14099: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14100: 
                   14101: $r is an Apache Request ref,
                   14102: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14103: $d is an array of 2 element arrays (internal name, displayed name)
                   14104: 
                   14105: =cut
                   14106: 
1.144     matthew  14107: ######################################################
                   14108: ######################################################
1.31      albertel 14109: sub csv_samples_select_table {
                   14110:     my ($r,$records,$d) = @_;
                   14111:     my $i=0;
1.144     matthew  14112:     #
1.662     bisitz   14113:     my $max_samples = 5;
                   14114:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14115:     $r->print(&start_data_table().
                   14116:               &start_data_table_header_row().'<th>'.
                   14117:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14118:               &end_data_table_header_row());
1.301     albertel 14119: 
                   14120:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14121: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14122: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14123: 	foreach my $option (@$d) {
                   14124: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14125: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14126:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14127:                       $display.'</option>');
1.31      albertel 14128: 	}
                   14129: 	$r->print('</select></td><td>');
1.662     bisitz   14130: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14131: 	    if (defined($samples->[$line]{$key})) { 
                   14132: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14133: 	    }
                   14134: 	}
1.594     raeburn  14135: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14136: 	$i++;
                   14137:     }
1.594     raeburn  14138:     $r->print(&end_data_table());
1.31      albertel 14139:     $i--;
                   14140:     return($i);
1.115     matthew  14141: }
                   14142: 
1.144     matthew  14143: ######################################################
                   14144: ######################################################
                   14145: 
1.115     matthew  14146: =pod
                   14147: 
1.648     raeburn  14148: =item * &clean_excel_name($name)
1.115     matthew  14149: 
                   14150: Returns a replacement for $name which does not contain any illegal characters.
                   14151: 
                   14152: =cut
                   14153: 
1.144     matthew  14154: ######################################################
                   14155: ######################################################
1.115     matthew  14156: sub clean_excel_name {
                   14157:     my ($name) = @_;
                   14158:     $name =~ s/[:\*\?\/\\]//g;
                   14159:     if (length($name) > 31) {
                   14160:         $name = substr($name,0,31);
                   14161:     }
                   14162:     return $name;
1.25      albertel 14163: }
1.84      albertel 14164: 
1.85      albertel 14165: =pod
                   14166: 
1.648     raeburn  14167: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14168: 
                   14169: Returns either 1 or undef
                   14170: 
                   14171: 1 if the part is to be hidden, undef if it is to be shown
                   14172: 
                   14173: Arguments are:
                   14174: 
                   14175: $id the id of the part to be checked
                   14176: $symb, optional the symb of the resource to check
                   14177: $udom, optional the domain of the user to check for
                   14178: $uname, optional the username of the user to check for
                   14179: 
                   14180: =cut
1.84      albertel 14181: 
                   14182: sub check_if_partid_hidden {
                   14183:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14184:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14185: 					 $symb,$udom,$uname);
1.141     albertel 14186:     my $truth=1;
                   14187:     #if the string starts with !, then the list is the list to show not hide
                   14188:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14189:     my @hiddenlist=split(/,/,$hiddenparts);
                   14190:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14191: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14192:     }
1.141     albertel 14193:     return !$truth;
1.84      albertel 14194: }
1.127     matthew  14195: 
1.138     matthew  14196: 
                   14197: ############################################################
                   14198: ############################################################
                   14199: 
                   14200: =pod
                   14201: 
1.157     matthew  14202: =back 
                   14203: 
1.138     matthew  14204: =head1 cgi-bin script and graphing routines
                   14205: 
1.157     matthew  14206: =over 4
                   14207: 
1.648     raeburn  14208: =item * &get_cgi_id()
1.138     matthew  14209: 
                   14210: Inputs: none
                   14211: 
                   14212: Returns an id which can be used to pass environment variables
                   14213: to various cgi-bin scripts.  These environment variables will
                   14214: be removed from the users environment after a given time by
                   14215: the routine &Apache::lonnet::transfer_profile_to_env.
                   14216: 
                   14217: =cut
                   14218: 
                   14219: ############################################################
                   14220: ############################################################
1.152     albertel 14221: my $uniq=0;
1.136     matthew  14222: sub get_cgi_id {
1.154     albertel 14223:     $uniq=($uniq+1)%100000;
1.280     albertel 14224:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14225: }
                   14226: 
1.127     matthew  14227: ############################################################
                   14228: ############################################################
                   14229: 
                   14230: =pod
                   14231: 
1.648     raeburn  14232: =item * &DrawBarGraph()
1.127     matthew  14233: 
1.138     matthew  14234: Facilitates the plotting of data in a (stacked) bar graph.
                   14235: Puts plot definition data into the users environment in order for 
                   14236: graph.png to plot it.  Returns an <img> tag for the plot.
                   14237: The bars on the plot are labeled '1','2',...,'n'.
                   14238: 
                   14239: Inputs:
                   14240: 
                   14241: =over 4
                   14242: 
                   14243: =item $Title: string, the title of the plot
                   14244: 
                   14245: =item $xlabel: string, text describing the X-axis of the plot
                   14246: 
                   14247: =item $ylabel: string, text describing the Y-axis of the plot
                   14248: 
                   14249: =item $Max: scalar, the maximum Y value to use in the plot
                   14250: If $Max is < any data point, the graph will not be rendered.
                   14251: 
1.140     matthew  14252: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14253: they are plotted.  If undefined, default values will be used.
                   14254: 
1.178     matthew  14255: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14256: 
1.138     matthew  14257: =item @Values: An array of array references.  Each array reference holds data
                   14258: to be plotted in a stacked bar chart.
                   14259: 
1.239     matthew  14260: =item If the final element of @Values is a hash reference the key/value
                   14261: pairs will be added to the graph definition.
                   14262: 
1.138     matthew  14263: =back
                   14264: 
                   14265: Returns:
                   14266: 
                   14267: An <img> tag which references graph.png and the appropriate identifying
                   14268: information for the plot.
                   14269: 
1.127     matthew  14270: =cut
                   14271: 
                   14272: ############################################################
                   14273: ############################################################
1.134     matthew  14274: sub DrawBarGraph {
1.178     matthew  14275:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14276:     #
                   14277:     if (! defined($colors)) {
                   14278:         $colors = ['#33ff00', 
                   14279:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14280:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14281:                   ]; 
                   14282:     }
1.228     matthew  14283:     my $extra_settings = {};
                   14284:     if (ref($Values[-1]) eq 'HASH') {
                   14285:         $extra_settings = pop(@Values);
                   14286:     }
1.127     matthew  14287:     #
1.136     matthew  14288:     my $identifier = &get_cgi_id();
                   14289:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14290:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14291:         return '';
                   14292:     }
1.225     matthew  14293:     #
                   14294:     my @Labels;
                   14295:     if (defined($labels)) {
                   14296:         @Labels = @$labels;
                   14297:     } else {
                   14298:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  14299:             push(@Labels,$i+1);
1.225     matthew  14300:         }
                   14301:     }
                   14302:     #
1.129     matthew  14303:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14304:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14305:     my %ValuesHash;
                   14306:     my $NumSets=1;
                   14307:     foreach my $array (@Values) {
                   14308:         next if (! ref($array));
1.136     matthew  14309:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14310:             join(',',@$array);
1.129     matthew  14311:     }
1.127     matthew  14312:     #
1.136     matthew  14313:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14314:     if ($NumBars < 3) {
                   14315:         $width = 120+$NumBars*32;
1.220     matthew  14316:         $xskip = 1;
1.225     matthew  14317:         $bar_width = 30;
                   14318:     } elsif ($NumBars < 5) {
                   14319:         $width = 120+$NumBars*20;
                   14320:         $xskip = 1;
                   14321:         $bar_width = 20;
1.220     matthew  14322:     } elsif ($NumBars < 10) {
1.136     matthew  14323:         $width = 120+$NumBars*15;
                   14324:         $xskip = 1;
                   14325:         $bar_width = 15;
                   14326:     } elsif ($NumBars <= 25) {
                   14327:         $width = 120+$NumBars*11;
                   14328:         $xskip = 5;
                   14329:         $bar_width = 8;
                   14330:     } elsif ($NumBars <= 50) {
                   14331:         $width = 120+$NumBars*8;
                   14332:         $xskip = 5;
                   14333:         $bar_width = 4;
                   14334:     } else {
                   14335:         $width = 120+$NumBars*8;
                   14336:         $xskip = 5;
                   14337:         $bar_width = 4;
                   14338:     }
                   14339:     #
1.137     matthew  14340:     $Max = 1 if ($Max < 1);
                   14341:     if ( int($Max) < $Max ) {
                   14342:         $Max++;
                   14343:         $Max = int($Max);
                   14344:     }
1.127     matthew  14345:     $Title  = '' if (! defined($Title));
                   14346:     $xlabel = '' if (! defined($xlabel));
                   14347:     $ylabel = '' if (! defined($ylabel));
1.369     www      14348:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14349:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14350:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14351:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14352:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14353:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14354:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14355:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14356:     $ValuesHash{$id.'.height'}   = $height;
                   14357:     $ValuesHash{$id.'.width'}    = $width;
                   14358:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14359:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14360:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14361:     #
1.228     matthew  14362:     # Deal with other parameters
                   14363:     while (my ($key,$value) = each(%$extra_settings)) {
                   14364:         $ValuesHash{$id.'.'.$key} = $value;
                   14365:     }
                   14366:     #
1.646     raeburn  14367:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14368:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14369: }
                   14370: 
                   14371: ############################################################
                   14372: ############################################################
                   14373: 
                   14374: =pod
                   14375: 
1.648     raeburn  14376: =item * &DrawXYGraph()
1.137     matthew  14377: 
1.138     matthew  14378: Facilitates the plotting of data in an XY graph.
                   14379: Puts plot definition data into the users environment in order for 
                   14380: graph.png to plot it.  Returns an <img> tag for the plot.
                   14381: 
                   14382: Inputs:
                   14383: 
                   14384: =over 4
                   14385: 
                   14386: =item $Title: string, the title of the plot
                   14387: 
                   14388: =item $xlabel: string, text describing the X-axis of the plot
                   14389: 
                   14390: =item $ylabel: string, text describing the Y-axis of the plot
                   14391: 
                   14392: =item $Max: scalar, the maximum Y value to use in the plot
                   14393: If $Max is < any data point, the graph will not be rendered.
                   14394: 
                   14395: =item $colors: Array ref containing the hex color codes for the data to be 
                   14396: plotted in.  If undefined, default values will be used.
                   14397: 
                   14398: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14399: 
                   14400: =item $Ydata: Array ref containing Array refs.  
1.185     www      14401: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14402: 
                   14403: =item %Values: hash indicating or overriding any default values which are 
                   14404: passed to graph.png.  
                   14405: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14406: 
                   14407: =back
                   14408: 
                   14409: Returns:
                   14410: 
                   14411: An <img> tag which references graph.png and the appropriate identifying
                   14412: information for the plot.
                   14413: 
1.137     matthew  14414: =cut
                   14415: 
                   14416: ############################################################
                   14417: ############################################################
                   14418: sub DrawXYGraph {
                   14419:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14420:     #
                   14421:     # Create the identifier for the graph
                   14422:     my $identifier = &get_cgi_id();
                   14423:     my $id = 'cgi.'.$identifier;
                   14424:     #
                   14425:     $Title  = '' if (! defined($Title));
                   14426:     $xlabel = '' if (! defined($xlabel));
                   14427:     $ylabel = '' if (! defined($ylabel));
                   14428:     my %ValuesHash = 
                   14429:         (
1.369     www      14430:          $id.'.title'  => &escape($Title),
                   14431:          $id.'.xlabel' => &escape($xlabel),
                   14432:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14433:          $id.'.y_max_value'=> $Max,
                   14434:          $id.'.labels'     => join(',',@$Xlabels),
                   14435:          $id.'.PlotType'   => 'XY',
                   14436:          );
                   14437:     #
                   14438:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14439:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14440:     }
                   14441:     #
                   14442:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14443:         return '';
                   14444:     }
                   14445:     my $NumSets=1;
1.138     matthew  14446:     foreach my $array (@{$Ydata}){
1.137     matthew  14447:         next if (! ref($array));
                   14448:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14449:     }
1.138     matthew  14450:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14451:     #
                   14452:     # Deal with other parameters
                   14453:     while (my ($key,$value) = each(%Values)) {
                   14454:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14455:     }
                   14456:     #
1.646     raeburn  14457:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14458:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14459: }
                   14460: 
                   14461: ############################################################
                   14462: ############################################################
                   14463: 
                   14464: =pod
                   14465: 
1.648     raeburn  14466: =item * &DrawXYYGraph()
1.138     matthew  14467: 
                   14468: Facilitates the plotting of data in an XY graph with two Y axes.
                   14469: Puts plot definition data into the users environment in order for 
                   14470: graph.png to plot it.  Returns an <img> tag for the plot.
                   14471: 
                   14472: Inputs:
                   14473: 
                   14474: =over 4
                   14475: 
                   14476: =item $Title: string, the title of the plot
                   14477: 
                   14478: =item $xlabel: string, text describing the X-axis of the plot
                   14479: 
                   14480: =item $ylabel: string, text describing the Y-axis of the plot
                   14481: 
                   14482: =item $colors: Array ref containing the hex color codes for the data to be 
                   14483: plotted in.  If undefined, default values will be used.
                   14484: 
                   14485: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14486: 
                   14487: =item $Ydata1: The first data set
                   14488: 
                   14489: =item $Min1: The minimum value of the left Y-axis
                   14490: 
                   14491: =item $Max1: The maximum value of the left Y-axis
                   14492: 
                   14493: =item $Ydata2: The second data set
                   14494: 
                   14495: =item $Min2: The minimum value of the right Y-axis
                   14496: 
                   14497: =item $Max2: The maximum value of the left Y-axis
                   14498: 
                   14499: =item %Values: hash indicating or overriding any default values which are 
                   14500: passed to graph.png.  
                   14501: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14502: 
                   14503: =back
                   14504: 
                   14505: Returns:
                   14506: 
                   14507: An <img> tag which references graph.png and the appropriate identifying
                   14508: information for the plot.
1.136     matthew  14509: 
                   14510: =cut
                   14511: 
                   14512: ############################################################
                   14513: ############################################################
1.137     matthew  14514: sub DrawXYYGraph {
                   14515:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14516:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14517:     #
                   14518:     # Create the identifier for the graph
                   14519:     my $identifier = &get_cgi_id();
                   14520:     my $id = 'cgi.'.$identifier;
                   14521:     #
                   14522:     $Title  = '' if (! defined($Title));
                   14523:     $xlabel = '' if (! defined($xlabel));
                   14524:     $ylabel = '' if (! defined($ylabel));
                   14525:     my %ValuesHash = 
                   14526:         (
1.369     www      14527:          $id.'.title'  => &escape($Title),
                   14528:          $id.'.xlabel' => &escape($xlabel),
                   14529:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14530:          $id.'.labels' => join(',',@$Xlabels),
                   14531:          $id.'.PlotType' => 'XY',
                   14532:          $id.'.NumSets' => 2,
1.137     matthew  14533:          $id.'.two_axes' => 1,
                   14534:          $id.'.y1_max_value' => $Max1,
                   14535:          $id.'.y1_min_value' => $Min1,
                   14536:          $id.'.y2_max_value' => $Max2,
                   14537:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14538:          );
                   14539:     #
1.137     matthew  14540:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14541:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14542:     }
                   14543:     #
                   14544:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14545:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14546:         return '';
                   14547:     }
                   14548:     my $NumSets=1;
1.137     matthew  14549:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14550:         next if (! ref($array));
                   14551:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14552:     }
                   14553:     #
                   14554:     # Deal with other parameters
                   14555:     while (my ($key,$value) = each(%Values)) {
                   14556:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14557:     }
                   14558:     #
1.646     raeburn  14559:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14560:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14561: }
                   14562: 
                   14563: ############################################################
                   14564: ############################################################
                   14565: 
                   14566: =pod
                   14567: 
1.157     matthew  14568: =back 
                   14569: 
1.139     matthew  14570: =head1 Statistics helper routines?  
                   14571: 
                   14572: Bad place for them but what the hell.
                   14573: 
1.157     matthew  14574: =over 4
                   14575: 
1.648     raeburn  14576: =item * &chartlink()
1.139     matthew  14577: 
                   14578: Returns a link to the chart for a specific student.  
                   14579: 
                   14580: Inputs:
                   14581: 
                   14582: =over 4
                   14583: 
                   14584: =item $linktext: The text of the link
                   14585: 
                   14586: =item $sname: The students username
                   14587: 
                   14588: =item $sdomain: The students domain
                   14589: 
                   14590: =back
                   14591: 
1.157     matthew  14592: =back
                   14593: 
1.139     matthew  14594: =cut
                   14595: 
                   14596: ############################################################
                   14597: ############################################################
                   14598: sub chartlink {
                   14599:     my ($linktext, $sname, $sdomain) = @_;
                   14600:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14601:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14602:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14603:        '">'.$linktext.'</a>';
1.153     matthew  14604: }
                   14605: 
                   14606: #######################################################
                   14607: #######################################################
                   14608: 
                   14609: =pod
                   14610: 
                   14611: =head1 Course Environment Routines
1.157     matthew  14612: 
                   14613: =over 4
1.153     matthew  14614: 
1.648     raeburn  14615: =item * &restore_course_settings()
1.153     matthew  14616: 
1.648     raeburn  14617: =item * &store_course_settings()
1.153     matthew  14618: 
                   14619: Restores/Store indicated form parameters from the course environment.
                   14620: Will not overwrite existing values of the form parameters.
                   14621: 
                   14622: Inputs: 
                   14623: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14624: 
                   14625: a hash ref describing the data to be stored.  For example:
                   14626:    
                   14627: %Save_Parameters = ('Status' => 'scalar',
                   14628:     'chartoutputmode' => 'scalar',
                   14629:     'chartoutputdata' => 'scalar',
                   14630:     'Section' => 'array',
1.373     raeburn  14631:     'Group' => 'array',
1.153     matthew  14632:     'StudentData' => 'array',
                   14633:     'Maps' => 'array');
                   14634: 
                   14635: Returns: both routines return nothing
                   14636: 
1.631     raeburn  14637: =back
                   14638: 
1.153     matthew  14639: =cut
                   14640: 
                   14641: #######################################################
                   14642: #######################################################
                   14643: sub store_course_settings {
1.496     albertel 14644:     return &store_settings($env{'request.course.id'},@_);
                   14645: }
                   14646: 
                   14647: sub store_settings {
1.153     matthew  14648:     # save to the environment
                   14649:     # appenv the same items, just to be safe
1.300     albertel 14650:     my $udom  = $env{'user.domain'};
                   14651:     my $uname = $env{'user.name'};
1.496     albertel 14652:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14653:     my %SaveHash;
                   14654:     my %AppHash;
                   14655:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14656:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14657:         my $envname = 'environment.'.$basename;
1.258     albertel 14658:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14659:             # Save this value away
                   14660:             if ($type eq 'scalar' &&
1.258     albertel 14661:                 (! exists($env{$envname}) || 
                   14662:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14663:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14664:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14665:             } elsif ($type eq 'array') {
                   14666:                 my $stored_form;
1.258     albertel 14667:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14668:                     $stored_form = join(',',
                   14669:                                         map {
1.369     www      14670:                                             &escape($_);
1.258     albertel 14671:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14672:                 } else {
                   14673:                     $stored_form = 
1.369     www      14674:                         &escape($env{'form.'.$setting});
1.153     matthew  14675:                 }
                   14676:                 # Determine if the array contents are the same.
1.258     albertel 14677:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14678:                     $SaveHash{$basename} = $stored_form;
                   14679:                     $AppHash{$envname}   = $stored_form;
                   14680:                 }
                   14681:             }
                   14682:         }
                   14683:     }
                   14684:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14685:                                           $udom,$uname);
1.153     matthew  14686:     if ($put_result !~ /^(ok|delayed)/) {
                   14687:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14688:                                  'got error:'.$put_result);
                   14689:     }
                   14690:     # Make sure these settings stick around in this session, too
1.646     raeburn  14691:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14692:     return;
                   14693: }
                   14694: 
                   14695: sub restore_course_settings {
1.499     albertel 14696:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14697: }
                   14698: 
                   14699: sub restore_settings {
                   14700:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14701:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14702:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14703:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14704:             '.'.$setting;
1.258     albertel 14705:         if (exists($env{$envname})) {
1.153     matthew  14706:             if ($type eq 'scalar') {
1.258     albertel 14707:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14708:             } elsif ($type eq 'array') {
1.258     albertel 14709:                 $env{'form.'.$setting} = [ 
1.153     matthew  14710:                                            map { 
1.369     www      14711:                                                &unescape($_); 
1.258     albertel 14712:                                            } split(',',$env{$envname})
1.153     matthew  14713:                                            ];
                   14714:             }
                   14715:         }
                   14716:     }
1.127     matthew  14717: }
                   14718: 
1.618     raeburn  14719: #######################################################
                   14720: #######################################################
                   14721: 
                   14722: =pod
                   14723: 
                   14724: =head1 Domain E-mail Routines  
                   14725: 
                   14726: =over 4
                   14727: 
1.648     raeburn  14728: =item * &build_recipient_list()
1.618     raeburn  14729: 
1.1075.2.44  raeburn  14730: Build recipient lists for following types of e-mail:
1.766     raeburn  14731: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14732: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14733: module change checking, student/employee ID conflict checks, as
                   14734: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14735: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14736: 
                   14737: Inputs:
1.1075.2.44  raeburn  14738: defmail (scalar - email address of default recipient),
                   14739: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14740: requestsmail, updatesmail, or idconflictsmail).
                   14741: 
1.619     raeburn  14742: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14743: 
                   14744: origmail (scalar - email address of recipient from loncapa.conf,
                   14745: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14746: 
1.1075.2.139  raeburn  14747: $requname username of requester (if mailing type is helpdeskmail)
                   14748: 
                   14749: $requdom domain of requester (if mailing type is helpdeskmail)
                   14750: 
                   14751: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14752: 
1.655     raeburn  14753: Returns: comma separated list of addresses to which to send e-mail.
                   14754: 
                   14755: =back
1.618     raeburn  14756: 
                   14757: =cut
                   14758: 
                   14759: ############################################################
                   14760: ############################################################
                   14761: sub build_recipient_list {
1.1075.2.139  raeburn  14762:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14763:     my @recipients;
1.1075.2.122  raeburn  14764:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14765:     my %domconfig =
1.1075.2.122  raeburn  14766:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14767:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14768:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14769:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14770:                 my @contacts = ('adminemail','supportemail');
                   14771:                 foreach my $item (@contacts) {
                   14772:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14773:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14774:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14775:                             push(@recipients,$addr);
                   14776:                         }
1.619     raeburn  14777:                     }
1.1075.2.122  raeburn  14778:                 }
                   14779:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14780:                 if ($mailing eq 'helpdeskmail') {
                   14781:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14782:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14783:                         my @ok_bccs;
                   14784:                         foreach my $bcc (@bccs) {
                   14785:                             $bcc =~ s/^\s+//g;
                   14786:                             $bcc =~ s/\s+$//g;
                   14787:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14788:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14789:                                     push(@ok_bccs,$bcc);
                   14790:                                 }
                   14791:                             }
                   14792:                         }
                   14793:                         if (@ok_bccs > 0) {
                   14794:                             $allbcc = join(', ',@ok_bccs);
                   14795:                         }
                   14796:                     }
                   14797:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14798:                 }
                   14799:             }
1.766     raeburn  14800:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14801:             $lastresort = $origmail;
1.618     raeburn  14802:         }
1.1075.2.139  raeburn  14803:         if ($mailing eq 'helpdeskmail') {
                   14804:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14805:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14806:                 my ($inststatus,$inststatus_checked);
                   14807:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14808:                     ($env{'user.domain'} ne 'public')) {
                   14809:                     $inststatus_checked = 1;
                   14810:                     $inststatus = $env{'environment.inststatus'};
                   14811:                 }
                   14812:                 unless ($inststatus_checked) {
                   14813:                     if (($requname ne '') && ($requdom ne '')) {
                   14814:                         if (($requname =~ /^$match_username$/) &&
                   14815:                             ($requdom =~ /^$match_domain$/) &&
                   14816:                             (&Apache::lonnet::domain($requdom))) {
                   14817:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14818:                                                                       $requdom);
                   14819:                             unless ($requhome eq 'no_host') {
                   14820:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14821:                                 $inststatus = $userenv{'inststatus'};
                   14822:                                 $inststatus_checked = 1;
                   14823:                             }
                   14824:                         }
                   14825:                     }
                   14826:                 }
                   14827:                 unless ($inststatus_checked) {
                   14828:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14829:                         my %srch = (srchby     => 'email',
                   14830:                                     srchdomain => $defdom,
                   14831:                                     srchterm   => $reqemail,
                   14832:                                     srchtype   => 'exact');
                   14833:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14834:                         foreach my $uname (keys(%srch_results)) {
                   14835:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14836:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14837:                                 $inststatus_checked = 1;
                   14838:                                 last;
                   14839:                             }
                   14840:                         }
                   14841:                         unless ($inststatus_checked) {
                   14842:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14843:                             if ($dirsrchres eq 'ok') {
                   14844:                                 foreach my $uname (keys(%srch_results)) {
                   14845:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14846:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14847:                                         $inststatus_checked = 1;
                   14848:                                         last;
                   14849:                                     }
                   14850:                                 }
                   14851:                             }
                   14852:                         }
                   14853:                     }
                   14854:                 }
                   14855:                 if ($inststatus ne '') {
                   14856:                     foreach my $status (split(/\:/,$inststatus)) {
                   14857:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14858:                             my @contacts = ('adminemail','supportemail');
                   14859:                             foreach my $item (@contacts) {
                   14860:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14861:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14862:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14863:                                         push(@recipients,$addr);
                   14864:                                     }
                   14865:                                 }
                   14866:                             }
                   14867:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14868:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14869:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14870:                                 my @ok_bccs;
                   14871:                                 foreach my $bcc (@bccs) {
                   14872:                                     $bcc =~ s/^\s+//g;
                   14873:                                     $bcc =~ s/\s+$//g;
                   14874:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14875:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14876:                                             push(@ok_bccs,$bcc);
                   14877:                                         }
                   14878:                                     }
                   14879:                                 }
                   14880:                                 if (@ok_bccs > 0) {
                   14881:                                     $allbcc = join(', ',@ok_bccs);
                   14882:                                 }
                   14883:                             }
                   14884:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14885:                             last;
                   14886:                         }
                   14887:                     }
                   14888:                 }
                   14889:             }
                   14890:         }
1.619     raeburn  14891:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14892:         $lastresort = $origmail;
                   14893:     }
1.1075.2.128  raeburn  14894:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14895:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14896:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14897:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14898:             my %what = (
                   14899:                           perlvar => 1,
                   14900:                        );
                   14901:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14902:             if ($primary) {
                   14903:                 my $gotaddr;
                   14904:                 my ($result,$returnhash) =
                   14905:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14906:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14907:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14908:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14909:                         $gotaddr = 1;
                   14910:                     }
                   14911:                 }
                   14912:                 unless ($gotaddr) {
                   14913:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14914:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14915:                     unless ($uintdom eq $intdom) {
                   14916:                         my %domconfig =
                   14917:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14918:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14919:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14920:                                 my @contacts = ('adminemail','supportemail');
                   14921:                                 foreach my $item (@contacts) {
                   14922:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14923:                                         my $addr = $domconfig{'contacts'}{$item};
                   14924:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14925:                                             push(@recipients,$addr);
                   14926:                                         }
                   14927:                                     }
                   14928:                                 }
                   14929:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14930:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14931:                                 }
                   14932:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14933:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14934:                                     my @ok_bccs;
                   14935:                                     foreach my $bcc (@bccs) {
                   14936:                                         $bcc =~ s/^\s+//g;
                   14937:                                         $bcc =~ s/\s+$//g;
                   14938:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14939:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14940:                                                 push(@ok_bccs,$bcc);
                   14941:                                             }
                   14942:                                         }
                   14943:                                     }
                   14944:                                     if (@ok_bccs > 0) {
                   14945:                                         $allbcc = join(', ',@ok_bccs);
                   14946:                                     }
                   14947:                                 }
                   14948:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14949:                             }
                   14950:                         }
                   14951:                     }
                   14952:                 }
                   14953:             }
                   14954:         }
1.618     raeburn  14955:     }
1.688     raeburn  14956:     if (defined($defmail)) {
                   14957:         if ($defmail ne '') {
                   14958:             push(@recipients,$defmail);
                   14959:         }
1.618     raeburn  14960:     }
                   14961:     if ($otheremails) {
1.619     raeburn  14962:         my @others;
                   14963:         if ($otheremails =~ /,/) {
                   14964:             @others = split(/,/,$otheremails);
1.618     raeburn  14965:         } else {
1.619     raeburn  14966:             push(@others,$otheremails);
                   14967:         }
                   14968:         foreach my $addr (@others) {
                   14969:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14970:                 push(@recipients,$addr);
                   14971:             }
1.618     raeburn  14972:         }
                   14973:     }
1.1075.2.128  raeburn  14974:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14975:         if ((!@recipients) && ($lastresort ne '')) {
                   14976:             push(@recipients,$lastresort);
                   14977:         }
                   14978:     } elsif ($lastresort ne '') {
                   14979:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14980:             push(@recipients,$lastresort);
                   14981:         }
                   14982:     }
                   14983:     my $recipientlist = join(',',@recipients);
                   14984:     if (wantarray) {
                   14985:         return ($recipientlist,$allbcc,$addtext);
                   14986:     } else {
                   14987:         return $recipientlist;
                   14988:     }
1.618     raeburn  14989: }
                   14990: 
1.127     matthew  14991: ############################################################
                   14992: ############################################################
1.154     albertel 14993: 
1.655     raeburn  14994: =pod
                   14995: 
                   14996: =head1 Course Catalog Routines
                   14997: 
                   14998: =over 4
                   14999: 
                   15000: =item * &gather_categories()
                   15001: 
                   15002: Converts category definitions - keys of categories hash stored in  
                   15003: coursecategories in configuration.db on the primary library server in a 
                   15004: domain - to an array.  Also generates javascript and idx hash used to 
                   15005: generate Domain Coordinator interface for editing Course Categories.
                   15006: 
                   15007: Inputs:
1.663     raeburn  15008: 
1.655     raeburn  15009: categories (reference to hash of category definitions).
1.663     raeburn  15010: 
1.655     raeburn  15011: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15012:       categories and subcategories).
1.663     raeburn  15013: 
1.655     raeburn  15014: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15015:       editing Course Categories).
1.663     raeburn  15016: 
1.655     raeburn  15017: jsarray (reference to array of categories used to create Javascript arrays for
                   15018:          Domain Coordinator interface for editing Course Categories).
                   15019: 
                   15020: Returns: nothing
                   15021: 
                   15022: Side effects: populates cats, idx and jsarray. 
                   15023: 
                   15024: =cut
                   15025: 
                   15026: sub gather_categories {
                   15027:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15028:     my %counters;
                   15029:     my $num = 0;
                   15030:     foreach my $item (keys(%{$categories})) {
                   15031:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15032:         if ($container eq '' && $depth == 0) {
                   15033:             $cats->[$depth][$categories->{$item}] = $cat;
                   15034:         } else {
                   15035:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15036:         }
                   15037:         my ($escitem,$tail) = split(/:/,$item,2);
                   15038:         if ($counters{$tail} eq '') {
                   15039:             $counters{$tail} = $num;
                   15040:             $num ++;
                   15041:         }
                   15042:         if (ref($idx) eq 'HASH') {
                   15043:             $idx->{$item} = $counters{$tail};
                   15044:         }
                   15045:         if (ref($jsarray) eq 'ARRAY') {
                   15046:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15047:         }
                   15048:     }
                   15049:     return;
                   15050: }
                   15051: 
                   15052: =pod
                   15053: 
                   15054: =item * &extract_categories()
                   15055: 
                   15056: Used to generate breadcrumb trails for course categories.
                   15057: 
                   15058: Inputs:
1.663     raeburn  15059: 
1.655     raeburn  15060: categories (reference to hash of category definitions).
1.663     raeburn  15061: 
1.655     raeburn  15062: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15063:       categories and subcategories).
1.663     raeburn  15064: 
1.655     raeburn  15065: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15066: 
1.655     raeburn  15067: allitems (reference to hash - key is category key 
                   15068:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15069: 
1.655     raeburn  15070: idx (reference to hash of counters used in Domain Coordinator interface for
                   15071:       editing Course Categories).
1.663     raeburn  15072: 
1.655     raeburn  15073: jsarray (reference to array of categories used to create Javascript arrays for
                   15074:          Domain Coordinator interface for editing Course Categories).
                   15075: 
1.665     raeburn  15076: subcats (reference to hash of arrays containing all subcategories within each 
                   15077:          category, -recursive)
                   15078: 
1.1075.2.132  raeburn  15079: maxd (reference to hash used to hold max depth for all top-level categories).
                   15080: 
1.655     raeburn  15081: Returns: nothing
                   15082: 
                   15083: Side effects: populates trails and allitems hash references.
                   15084: 
                   15085: =cut
                   15086: 
                   15087: sub extract_categories {
1.1075.2.132  raeburn  15088:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15089:     if (ref($categories) eq 'HASH') {
                   15090:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15091:         if (ref($cats->[0]) eq 'ARRAY') {
                   15092:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15093:                 my $name = $cats->[0][$i];
                   15094:                 my $item = &escape($name).'::0';
                   15095:                 my $trailstr;
                   15096:                 if ($name eq 'instcode') {
                   15097:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15098:                 } elsif ($name eq 'communities') {
                   15099:                     $trailstr = &mt('Communities');
1.655     raeburn  15100:                 } else {
                   15101:                     $trailstr = $name;
                   15102:                 }
                   15103:                 if ($allitems->{$item} eq '') {
                   15104:                     push(@{$trails},$trailstr);
                   15105:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15106:                 }
                   15107:                 my @parents = ($name);
                   15108:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15109:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15110:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15111:                         if (ref($subcats) eq 'HASH') {
                   15112:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15113:                         }
1.1075.2.132  raeburn  15114:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15115:                     }
                   15116:                 } else {
                   15117:                     if (ref($subcats) eq 'HASH') {
                   15118:                         $subcats->{$item} = [];
1.655     raeburn  15119:                     }
1.1075.2.132  raeburn  15120:                     if (ref($maxd) eq 'HASH') {
                   15121:                         $maxd->{$name} = 1;
                   15122:                     }
1.655     raeburn  15123:                 }
                   15124:             }
                   15125:         }
                   15126:     }
                   15127:     return;
                   15128: }
                   15129: 
                   15130: =pod
                   15131: 
1.1075.2.56  raeburn  15132: =item * &recurse_categories()
1.655     raeburn  15133: 
                   15134: Recursively used to generate breadcrumb trails for course categories.
                   15135: 
                   15136: Inputs:
1.663     raeburn  15137: 
1.655     raeburn  15138: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15139:       categories and subcategories).
1.663     raeburn  15140: 
1.655     raeburn  15141: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15142: 
                   15143: category (current course category, for which breadcrumb trail is being generated).
                   15144: 
                   15145: trails (reference to array of breadcrumb trails for each category).
                   15146: 
1.655     raeburn  15147: allitems (reference to hash - key is category key
                   15148:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15149: 
1.655     raeburn  15150: parents (array containing containers directories for current category, 
                   15151:          back to top level). 
                   15152: 
                   15153: Returns: nothing
                   15154: 
                   15155: Side effects: populates trails and allitems hash references
                   15156: 
                   15157: =cut
                   15158: 
                   15159: sub recurse_categories {
1.1075.2.132  raeburn  15160:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15161:     my $shallower = $depth - 1;
                   15162:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15163:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15164:             my $name = $cats->[$depth]{$category}[$k];
                   15165:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15166:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15167:             if ($allitems->{$item} eq '') {
                   15168:                 push(@{$trails},$trailstr);
                   15169:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15170:             }
                   15171:             my $deeper = $depth+1;
                   15172:             push(@{$parents},$category);
1.665     raeburn  15173:             if (ref($subcats) eq 'HASH') {
                   15174:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15175:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15176:                     my $higher;
                   15177:                     if ($j > 0) {
                   15178:                         $higher = &escape($parents->[$j]).':'.
                   15179:                                   &escape($parents->[$j-1]).':'.$j;
                   15180:                     } else {
                   15181:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15182:                     }
                   15183:                     push(@{$subcats->{$higher}},$subcat);
                   15184:                 }
                   15185:             }
                   15186:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  15187:                                 $subcats,$maxd);
1.655     raeburn  15188:             pop(@{$parents});
                   15189:         }
                   15190:     } else {
                   15191:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  15192:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15193:         if ($allitems->{$item} eq '') {
                   15194:             push(@{$trails},$trailstr);
                   15195:             $allitems->{$item} = scalar(@{$trails})-1;
                   15196:         }
1.1075.2.132  raeburn  15197:         if (ref($maxd) eq 'HASH') {
                   15198:             if ($depth > $maxd->{$parents->[0]}) {
                   15199:                 $maxd->{$parents->[0]} = $depth;
                   15200:             }
                   15201:         }
1.655     raeburn  15202:     }
                   15203:     return;
                   15204: }
                   15205: 
1.663     raeburn  15206: =pod
                   15207: 
1.1075.2.56  raeburn  15208: =item * &assign_categories_table()
1.663     raeburn  15209: 
                   15210: Create a datatable for display of hierarchical categories in a domain,
                   15211: with checkboxes to allow a course to be categorized. 
                   15212: 
                   15213: Inputs:
                   15214: 
                   15215: cathash - reference to hash of categories defined for the domain (from
                   15216:           configuration.db)
                   15217: 
                   15218: currcat - scalar with an & separated list of categories assigned to a course. 
                   15219: 
1.919     raeburn  15220: type    - scalar contains course type (Course or Community).
                   15221: 
1.1075.2.117  raeburn  15222: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15223:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15224: 
1.663     raeburn  15225: Returns: $output (markup to be displayed) 
                   15226: 
                   15227: =cut
                   15228: 
                   15229: sub assign_categories_table {
1.1075.2.117  raeburn  15230:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15231:     my $output;
                   15232:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  15233:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15234:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15235:         $maxdepth = scalar(@cats);
                   15236:         if (@cats > 0) {
                   15237:             my $itemcount = 0;
                   15238:             if (ref($cats[0]) eq 'ARRAY') {
                   15239:                 my @currcategories;
                   15240:                 if ($currcat ne '') {
                   15241:                     @currcategories = split('&',$currcat);
                   15242:                 }
1.919     raeburn  15243:                 my $table;
1.663     raeburn  15244:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15245:                     my $parent = $cats[0][$i];
1.919     raeburn  15246:                     next if ($parent eq 'instcode');
                   15247:                     if ($type eq 'Community') {
                   15248:                         next unless ($parent eq 'communities');
                   15249:                     } else {
                   15250:                         next if ($parent eq 'communities');
                   15251:                     }
1.663     raeburn  15252:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15253:                     my $item = &escape($parent).'::0';
                   15254:                     my $checked = '';
                   15255:                     if (@currcategories > 0) {
                   15256:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15257:                             $checked = ' checked="checked"';
1.663     raeburn  15258:                         }
                   15259:                     }
1.919     raeburn  15260:                     my $parent_title = $parent;
                   15261:                     if ($parent eq 'communities') {
                   15262:                         $parent_title = &mt('Communities');
                   15263:                     }
                   15264:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15265:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15266:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15267:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15268:                     my $depth = 1;
                   15269:                     push(@path,$parent);
1.1075.2.117  raeburn  15270:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15271:                     pop(@path);
1.919     raeburn  15272:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15273:                     $itemcount ++;
                   15274:                 }
1.919     raeburn  15275:                 if ($itemcount) {
                   15276:                     $output = &Apache::loncommon::start_data_table().
                   15277:                               $table.
                   15278:                               &Apache::loncommon::end_data_table();
                   15279:                 }
1.663     raeburn  15280:             }
                   15281:         }
                   15282:     }
                   15283:     return $output;
                   15284: }
                   15285: 
                   15286: =pod
                   15287: 
1.1075.2.56  raeburn  15288: =item * &assign_category_rows()
1.663     raeburn  15289: 
                   15290: Create a datatable row for display of nested categories in a domain,
                   15291: with checkboxes to allow a course to be categorized,called recursively.
                   15292: 
                   15293: Inputs:
                   15294: 
                   15295: itemcount - track row number for alternating colors
                   15296: 
                   15297: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15298:       categories and subcategories.
                   15299: 
                   15300: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15301: 
                   15302: parent - parent of current category item
                   15303: 
                   15304: path - Array containing all categories back up through the hierarchy from the
                   15305:        current category to the top level.
                   15306: 
                   15307: currcategories - reference to array of current categories assigned to the course
                   15308: 
1.1075.2.117  raeburn  15309: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15310:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15311: 
1.663     raeburn  15312: Returns: $output (markup to be displayed).
                   15313: 
                   15314: =cut
                   15315: 
                   15316: sub assign_category_rows {
1.1075.2.117  raeburn  15317:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15318:     my ($text,$name,$item,$chgstr);
                   15319:     if (ref($cats) eq 'ARRAY') {
                   15320:         my $maxdepth = scalar(@{$cats});
                   15321:         if (ref($cats->[$depth]) eq 'HASH') {
                   15322:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15323:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15324:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  15325:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15326:                 for (my $j=0; $j<$numchildren; $j++) {
                   15327:                     $name = $cats->[$depth]{$parent}[$j];
                   15328:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15329:                     my $deeper = $depth+1;
                   15330:                     my $checked = '';
                   15331:                     if (ref($currcategories) eq 'ARRAY') {
                   15332:                         if (@{$currcategories} > 0) {
                   15333:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15334:                                 $checked = ' checked="checked"';
1.663     raeburn  15335:                             }
                   15336:                         }
                   15337:                     }
1.664     raeburn  15338:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15339:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15340:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15341:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15342:                              '</td><td>';
1.663     raeburn  15343:                     if (ref($path) eq 'ARRAY') {
                   15344:                         push(@{$path},$name);
1.1075.2.117  raeburn  15345:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15346:                         pop(@{$path});
                   15347:                     }
                   15348:                     $text .= '</td></tr>';
                   15349:                 }
                   15350:                 $text .= '</table></td>';
                   15351:             }
                   15352:         }
                   15353:     }
                   15354:     return $text;
                   15355: }
                   15356: 
1.1075.2.69  raeburn  15357: =pod
                   15358: 
                   15359: =back
                   15360: 
                   15361: =cut
                   15362: 
1.655     raeburn  15363: ############################################################
                   15364: ############################################################
                   15365: 
                   15366: 
1.443     albertel 15367: sub commit_customrole {
1.664     raeburn  15368:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15369:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15370:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15371:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15372:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15373:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15374:                  '</b><br />';
                   15375:     return $output;
                   15376: }
                   15377: 
                   15378: sub commit_standardrole {
1.1075.2.31  raeburn  15379:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15380:     my ($output,$logmsg,$linefeed);
                   15381:     if ($context eq 'auto') {
                   15382:         $linefeed = "\n";
                   15383:     } else {
                   15384:         $linefeed = "<br />\n";
                   15385:     }  
1.443     albertel 15386:     if ($three eq 'st') {
1.541     raeburn  15387:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  15388:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15389:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15390:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15391:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15392:         } else {
1.541     raeburn  15393:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15394:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15395:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15396:             if ($context eq 'auto') {
                   15397:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15398:             } else {
                   15399:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15400:                &mt('Add to classlist').': <b>ok</b>';
                   15401:             }
                   15402:             $output .= $linefeed;
1.443     albertel 15403:         }
                   15404:     } else {
                   15405:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15406:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15407:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15408:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15409:         if ($context eq 'auto') {
                   15410:             $output .= $result.$linefeed;
                   15411:         } else {
                   15412:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15413:         }
1.443     albertel 15414:     }
                   15415:     return $output;
                   15416: }
                   15417: 
                   15418: sub commit_studentrole {
1.1075.2.31  raeburn  15419:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15420:         $credits) = @_;
1.626     raeburn  15421:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15422:     if ($context eq 'auto') {
                   15423:         $linefeed = "\n";
                   15424:     } else {
                   15425:         $linefeed = '<br />'."\n";
                   15426:     }
1.443     albertel 15427:     if (defined($one) && defined($two)) {
                   15428:         my $cid=$one.'_'.$two;
                   15429:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15430:         my $secchange = 0;
                   15431:         my $expire_role_result;
                   15432:         my $modify_section_result;
1.628     raeburn  15433:         if ($oldsec ne '-1') { 
                   15434:             if ($oldsec ne $sec) {
1.443     albertel 15435:                 $secchange = 1;
1.628     raeburn  15436:                 my $now = time;
1.443     albertel 15437:                 my $uurl='/'.$cid;
                   15438:                 $uurl=~s/\_/\//g;
                   15439:                 if ($oldsec) {
                   15440:                     $uurl.='/'.$oldsec;
                   15441:                 }
1.626     raeburn  15442:                 $oldsecurl = $uurl;
1.628     raeburn  15443:                 $expire_role_result = 
1.652     raeburn  15444:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15445:                 if ($env{'request.course.sec'} ne '') { 
                   15446:                     if ($expire_role_result eq 'refused') {
                   15447:                         my @roles = ('st');
                   15448:                         my @statuses = ('previous');
                   15449:                         my @roledoms = ($one);
                   15450:                         my $withsec = 1;
                   15451:                         my %roleshash = 
                   15452:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15453:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15454:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15455:                             my ($oldstart,$oldend) = 
                   15456:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15457:                             if ($oldend > 0 && $oldend <= $now) {
                   15458:                                 $expire_role_result = 'ok';
                   15459:                             }
                   15460:                         }
                   15461:                     }
                   15462:                 }
1.443     albertel 15463:                 $result = $expire_role_result;
                   15464:             }
                   15465:         }
                   15466:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15467:             $modify_section_result = 
                   15468:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15469:                                                            undef,undef,undef,$sec,
                   15470:                                                            $end,$start,'','',$cid,
                   15471:                                                            '',$context,$credits);
1.443     albertel 15472:             if ($modify_section_result =~ /^ok/) {
                   15473:                 if ($secchange == 1) {
1.628     raeburn  15474:                     if ($sec eq '') {
                   15475:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15476:                     } else {
                   15477:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15478:                     }
1.443     albertel 15479:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15480:                     if ($sec eq '') {
                   15481:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15482:                     } else {
                   15483:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15484:                     }
1.443     albertel 15485:                 } else {
1.628     raeburn  15486:                     if ($sec eq '') {
                   15487:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15488:                     } else {
                   15489:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15490:                     }
1.443     albertel 15491:                 }
                   15492:             } else {
1.628     raeburn  15493:                 if ($secchange) {       
                   15494:                     $$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;
                   15495:                 } else {
                   15496:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15497:                 }
1.443     albertel 15498:             }
                   15499:             $result = $modify_section_result;
                   15500:         } elsif ($secchange == 1) {
1.628     raeburn  15501:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15502:                 $$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  15503:             } else {
                   15504:                 $$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;
                   15505:             }
1.626     raeburn  15506:             if ($expire_role_result eq 'refused') {
                   15507:                 my $newsecurl = '/'.$cid;
                   15508:                 $newsecurl =~ s/\_/\//g;
                   15509:                 if ($sec ne '') {
                   15510:                     $newsecurl.='/'.$sec;
                   15511:                 }
                   15512:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15513:                     if ($sec eq '') {
                   15514:                         $$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;
                   15515:                     } else {
                   15516:                         $$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;
                   15517:                     }
                   15518:                 }
                   15519:             }
1.443     albertel 15520:         }
                   15521:     } else {
1.626     raeburn  15522:         $$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 15523:         $result = "error: incomplete course id\n";
                   15524:     }
                   15525:     return $result;
                   15526: }
                   15527: 
1.1075.2.25  raeburn  15528: sub show_role_extent {
                   15529:     my ($scope,$context,$role) = @_;
                   15530:     $scope =~ s{^/}{};
                   15531:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15532:     push(@courseroles,'co');
                   15533:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15534:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15535:         $scope =~ s{/}{_};
                   15536:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15537:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15538:         my ($audom,$auname) = split(/\//,$scope);
                   15539:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15540:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15541:     } else {
                   15542:         $scope =~ s{/$}{};
                   15543:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15544:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15545:     }
                   15546: }
                   15547: 
1.443     albertel 15548: ############################################################
                   15549: ############################################################
                   15550: 
1.566     albertel 15551: sub check_clone {
1.578     raeburn  15552:     my ($args,$linefeed) = @_;
1.566     albertel 15553:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15554:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15555:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 15556:21):     my $clonetitle;
                   15557:21):     my @clonemsg;
1.566     albertel 15558:     my $can_clone = 0;
1.944     raeburn  15559:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15560:     if ($lctype ne 'community') {
                   15561:         $lctype = 'course';
                   15562:     }
1.566     albertel 15563:     if ($clonehome eq 'no_host') {
1.944     raeburn  15564:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15565:21):             push(@clonemsg,({
                   15566:21):                               mt => 'No new community created.',
                   15567:21):                               args => [],
                   15568:21):                             },
                   15569:21):                             {
                   15570:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15571:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15572:21):                             }));
1.908     raeburn  15573:         } else {
1.1075.2.161.  .1(raebu 15574:21):             push(@clonemsg,({
                   15575:21):                               mt => 'No new course created.',
                   15576:21):                               args => [],
                   15577:21):                             },
                   15578:21):                             {
                   15579:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15580:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15581:21):                             }));
                   15582:21):         }
1.566     albertel 15583:     } else {
                   15584: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 15585:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15586:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15587:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 15588:21):                 push(@clonemsg,({
                   15589:21):                                   mt => 'No new community created.',
                   15590:21):                                   args => [],
                   15591:21):                                 },
                   15592:21):                                 {
                   15593:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15594:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15595:21):                                 }));
                   15596:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15597:             }
                   15598:         }
1.1075.2.119  raeburn  15599: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15600:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15601: 	    $can_clone = 1;
                   15602: 	} else {
1.1075.2.95  raeburn  15603: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15604: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15605:             if ($clonehash{'cloners'} eq '') {
                   15606:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15607:                 if ($domdefs{'canclone'}) {
                   15608:                     unless ($domdefs{'canclone'} eq 'none') {
                   15609:                         if ($domdefs{'canclone'} eq 'domain') {
                   15610:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15611:                                 $can_clone = 1;
                   15612:                             }
                   15613:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15614:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15615:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15616:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15617:                                 $can_clone = 1;
                   15618:                             }
                   15619:                         }
                   15620:                     }
1.908     raeburn  15621:                 }
1.1075.2.95  raeburn  15622:             } else {
                   15623: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15624:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15625:                     $can_clone = 1;
1.1075.2.95  raeburn  15626:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15627:                     $can_clone = 1;
1.1075.2.96  raeburn  15628:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15629:                     $can_clone = 1;
1.1075.2.95  raeburn  15630:                 }
                   15631:                 unless ($can_clone) {
1.1075.2.96  raeburn  15632:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15633:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15634:                         my (%gotdomdefaults,%gotcodedefaults);
                   15635:                         foreach my $cloner (@cloners) {
                   15636:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15637:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15638:                                 my (%codedefaults,@code_order);
                   15639:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15640:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15641:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15642:                                     }
                   15643:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15644:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15645:                                     }
                   15646:                                 } else {
                   15647:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15648:                                                                             \%codedefaults,
                   15649:                                                                             \@code_order);
                   15650:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15651:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15652:                                 }
                   15653:                                 if (@code_order > 0) {
                   15654:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15655:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15656:                                                                                 $args->{'crscode'})) {
                   15657:                                         $can_clone = 1;
                   15658:                                         last;
                   15659:                                     }
                   15660:                                 }
                   15661:                             }
                   15662:                         }
                   15663:                     }
1.1075.2.96  raeburn  15664:                 }
                   15665:             }
                   15666:             unless ($can_clone) {
                   15667:                 my $ccrole = 'cc';
                   15668:                 if ($args->{'crstype'} eq 'Community') {
                   15669:                     $ccrole = 'co';
                   15670:                 }
                   15671:                 my %roleshash =
                   15672:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15673:                                                   $args->{'ccdomain'},
                   15674:                                                   'userroles',['active'],[$ccrole],
                   15675:                                                   [$args->{'clonedomain'}]);
                   15676:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15677:                     $can_clone = 1;
                   15678:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15679:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15680:                     $can_clone = 1;
1.1075.2.95  raeburn  15681:                 }
                   15682:             }
                   15683:             unless ($can_clone) {
                   15684:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15685:21):                     push(@clonemsg,({
                   15686:21):                                       mt => 'No new community created.',
                   15687:21):                                       args => [],
                   15688:21):                                     },
                   15689:21):                                     {
                   15690: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]).',
                   15691:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15692:21):                                     }));
1.1075.2.95  raeburn  15693:                 } else {
1.1075.2.161.  .1(raebu 15694:21):                     push(@clonemsg,({
                   15695:21):                                       mt => 'No new course created.',
                   15696:21):                                       args => [],
                   15697:21):                                     },
                   15698:21):                                     {
                   15699: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]).',
                   15700:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15701:21):                                     }));
1.578     raeburn  15702: 	        }
1.566     albertel 15703: 	    }
1.578     raeburn  15704:         }
1.566     albertel 15705:     }
1.1075.2.161.  .1(raebu 15706:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15707: }
                   15708: 
1.444     albertel 15709: sub construct_course {
1.1075.2.119  raeburn  15710:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 15711:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   15712:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  15713:     my $linefeed =  '<br />'."\n";
                   15714:     if ($context eq 'auto') {
                   15715:         $linefeed = "\n";
                   15716:     }
1.566     albertel 15717: 
                   15718: #
                   15719: # Are we cloning?
                   15720: #
1.1075.2.161.  .1(raebu 15721:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15722:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 15723:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 15724:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 15725:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 15726: 	}
                   15727:     }
                   15728: 
1.444     albertel 15729: #
                   15730: # Open course
                   15731: #
                   15732:     my $crstype = lc($args->{'crstype'});
                   15733:     my %cenv=();
                   15734:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15735:                                              $args->{'cdescr'},
                   15736:                                              $args->{'curl'},
                   15737:                                              $args->{'course_home'},
                   15738:                                              $args->{'nonstandard'},
                   15739:                                              $args->{'crscode'},
                   15740:                                              $args->{'ccuname'}.':'.
                   15741:                                              $args->{'ccdomain'},
1.882     raeburn  15742:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 15743:21):                                              $cnum,$context,$category,
                   15744:21):                                              $callercontext);
1.444     albertel 15745: 
                   15746:     # Note: The testing routines depend on this being output; see 
                   15747:     # Utils::Course. This needs to at least be output as a comment
                   15748:     # if anyone ever decides to not show this, and Utils::Course::new
                   15749:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 15750:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15751:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15752:21):     } else {
                   15753:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15754:21):     }
1.943     raeburn  15755:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 15756:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15757:     }
                   15758: 
1.444     albertel 15759: #
                   15760: # Check if created correctly
                   15761: #
1.479     albertel 15762:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15763:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15764:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 15765:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15766:21):             $outcome .= &mt_user($user_lh,
                   15767:21):                             'Course creation failed, unrecognized course home server.');
                   15768:21):         } else {
                   15769:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   15770:21):         }
                   15771:21):         $outcome .= $linefeed;
                   15772:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15773:     }
1.541     raeburn  15774:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15775: 
1.444     albertel 15776: #
1.566     albertel 15777: # Do the cloning
1.1075.2.161.  .1(raebu 15778:21): #
                   15779:21):     my @clonemsg;
1.566     albertel 15780:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 15781:21):         push(@clonemsg,
                   15782:21):                       {
                   15783:21):                           mt => 'Created [_1] by cloning from [_2]',
                   15784:21):                           args => [$crstype,$clonetitle],
                   15785:21):                       });
1.566     albertel 15786: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15787: # Copy all files
1.1075.2.161.  .1(raebu 15788:21):         my @info =
                   15789:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   15790:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   15791:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   15792:21):                                                      $args->{'tinyurls'});
                   15793:21):         if (@info) {
                   15794:21):             push(@clonemsg,@info);
                   15795:21):         }
1.444     albertel 15796: # Restore URL
1.566     albertel 15797: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15798: # Restore title
1.566     albertel 15799: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15800: # Restore creation date, creator and creation context.
                   15801:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15802:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15803:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15804: # Mark as cloned
1.566     albertel 15805: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15806: # Need to clone grading mode
                   15807:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15808:         $cenv{'grading'}=$newenv{'grading'};
                   15809: # Do not clone these environment entries
                   15810:         &Apache::lonnet::del('environment',
                   15811:                   ['default_enrollment_start_date',
                   15812:                    'default_enrollment_end_date',
                   15813:                    'question.email',
                   15814:                    'policy.email',
                   15815:                    'comment.email',
                   15816:                    'pch.users.denied',
1.725     raeburn  15817:                    'plc.users.denied',
                   15818:                    'hidefromcat',
1.1075.2.36  raeburn  15819:                    'checkforpriv',
1.1075.2.158  raeburn  15820:                    'categories'],
1.638     www      15821:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15822:         if ($args->{'textbook'}) {
                   15823:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15824:         }
1.444     albertel 15825:     }
1.566     albertel 15826: 
1.444     albertel 15827: #
                   15828: # Set environment (will override cloned, if existing)
                   15829: #
                   15830:     my @sections = ();
                   15831:     my @xlists = ();
                   15832:     if ($args->{'crstype'}) {
                   15833:         $cenv{'type'}=$args->{'crstype'};
                   15834:     }
                   15835:     if ($args->{'crsid'}) {
                   15836:         $cenv{'courseid'}=$args->{'crsid'};
                   15837:     }
                   15838:     if ($args->{'crscode'}) {
                   15839:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15840:     }
                   15841:     if ($args->{'crsquota'} ne '') {
                   15842:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15843:     } else {
                   15844:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15845:     }
                   15846:     if ($args->{'ccuname'}) {
                   15847:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15848:                                         ':'.$args->{'ccdomain'};
                   15849:     } else {
                   15850:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15851:     }
1.1075.2.31  raeburn  15852:     if ($args->{'defaultcredits'}) {
                   15853:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15854:     }
1.444     albertel 15855:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15856:     if ($args->{'crssections'}) {
                   15857:         $cenv{'internal.sectionnums'} = '';
                   15858:         if ($args->{'crssections'} =~ m/,/) {
                   15859:             @sections = split/,/,$args->{'crssections'};
                   15860:         } else {
                   15861:             $sections[0] = $args->{'crssections'};
                   15862:         }
                   15863:         if (@sections > 0) {
                   15864:             foreach my $item (@sections) {
                   15865:                 my ($sec,$gp) = split/:/,$item;
                   15866:                 my $class = $args->{'crscode'}.$sec;
                   15867:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15868:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15869:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15870:                     push(@badclasses,$class);
1.444     albertel 15871:                 }
                   15872:             }
                   15873:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15874:         }
                   15875:     }
                   15876: # do not hide course coordinator from staff listing, 
                   15877: # even if privileged
                   15878:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15879: # add course coordinator's domain to domains to check for privileged users
                   15880: # if different to course domain
                   15881:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15882:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15883:     }
1.444     albertel 15884: # add crosslistings
                   15885:     if ($args->{'crsxlist'}) {
                   15886:         $cenv{'internal.crosslistings'}='';
                   15887:         if ($args->{'crsxlist'} =~ m/,/) {
                   15888:             @xlists = split/,/,$args->{'crsxlist'};
                   15889:         } else {
                   15890:             $xlists[0] = $args->{'crsxlist'};
                   15891:         }
                   15892:         if (@xlists > 0) {
                   15893:             foreach my $item (@xlists) {
                   15894:                 my ($xl,$gp) = split/:/,$item;
                   15895:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15896:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15897:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15898:                     push(@badclasses,$xl);
1.444     albertel 15899:                 }
                   15900:             }
                   15901:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15902:         }
                   15903:     }
                   15904:     if ($args->{'autoadds'}) {
                   15905:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15906:     }
                   15907:     if ($args->{'autodrops'}) {
                   15908:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15909:     }
                   15910: # check for notification of enrollment changes
                   15911:     my @notified = ();
                   15912:     if ($args->{'notify_owner'}) {
                   15913:         if ($args->{'ccuname'} ne '') {
                   15914:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15915:         }
                   15916:     }
                   15917:     if ($args->{'notify_dc'}) {
                   15918:         if ($uname ne '') { 
1.630     raeburn  15919:             push(@notified,$uname.':'.$udom);
1.444     albertel 15920:         }
                   15921:     }
                   15922:     if (@notified > 0) {
                   15923:         my $notifylist;
                   15924:         if (@notified > 1) {
                   15925:             $notifylist = join(',',@notified);
                   15926:         } else {
                   15927:             $notifylist = $notified[0];
                   15928:         }
                   15929:         $cenv{'internal.notifylist'} = $notifylist;
                   15930:     }
                   15931:     if (@badclasses > 0) {
                   15932:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15933:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15934:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15935:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15936:         );
1.1075.2.119  raeburn  15937:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15938:                            &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  15939:         if ($context eq 'auto') {
                   15940:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15941:         } else {
1.566     albertel 15942:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15943:         }
                   15944:         foreach my $item (@badclasses) {
1.541     raeburn  15945:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15946:                 $outcome .= " - $item\n";
1.541     raeburn  15947:             } else {
1.1075.2.119  raeburn  15948:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15949:             }
1.1075.2.119  raeburn  15950:         }
                   15951:         if ($context eq 'auto') {
                   15952:             $outcome .= $linefeed;
                   15953:         } else {
                   15954:             $outcome .= "</ul><br /><br /></div>\n";
                   15955:         }
1.444     albertel 15956:     }
                   15957:     if ($args->{'no_end_date'}) {
                   15958:         $args->{'endaccess'} = 0;
                   15959:     }
                   15960:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15961:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15962:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15963:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15964:     if ($args->{'showphotos'}) {
                   15965:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15966:     }
                   15967:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15968:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15969:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15970:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15971:             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'); 
                   15972:             if ($context eq 'auto') {
                   15973:                 $outcome .= $krb_msg;
                   15974:             } else {
1.566     albertel 15975:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15976:             }
                   15977:             $outcome .= $linefeed;
1.444     albertel 15978:         }
                   15979:     }
                   15980:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15981:        if ($args->{'setpolicy'}) {
                   15982:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15983:        }
                   15984:        if ($args->{'setcontent'}) {
                   15985:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15986:        }
1.1075.2.110  raeburn  15987:        if ($args->{'setcomment'}) {
                   15988:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15989:        }
1.444     albertel 15990:     }
                   15991:     if ($args->{'reshome'}) {
                   15992: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15993: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15994:     }
                   15995: #
                   15996: # course has keyed access
                   15997: #
                   15998:     if ($args->{'setkeys'}) {
                   15999:        $cenv{'keyaccess'}='yes';
                   16000:     }
                   16001: # if specified, key authority is not course, but user
                   16002: # only active if keyaccess is yes
                   16003:     if ($args->{'keyauth'}) {
1.487     albertel 16004: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16005: 	$user = &LONCAPA::clean_username($user);
                   16006: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16007: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16008: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16009: 	}
                   16010:     }
                   16011: 
1.1075.2.59  raeburn  16012: #
                   16013: #  generate and store uniquecode (available to course requester), if course should have one.
                   16014: #
                   16015:     if ($args->{'uniquecode'}) {
                   16016:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16017:         if ($code) {
                   16018:             $cenv{'internal.uniquecode'} = $code;
                   16019:             my %crsinfo =
                   16020:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16021:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16022:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16023:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16024:             }
                   16025:             if (ref($coderef)) {
                   16026:                 $$coderef = $code;
                   16027:             }
                   16028:         }
                   16029:     }
                   16030: 
1.444     albertel 16031:     if ($args->{'disresdis'}) {
                   16032:         $cenv{'pch.roles.denied'}='st';
                   16033:     }
                   16034:     if ($args->{'disablechat'}) {
                   16035:         $cenv{'plc.roles.denied'}='st';
                   16036:     }
                   16037: 
                   16038:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16039:     # course
                   16040:     $cenv{'course.helper.not.run'} = 1;
                   16041:     #
                   16042:     # Use new Randomseed
                   16043:     #
                   16044:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16045:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16046:     #
                   16047:     # The encryption code and receipt prefix for this course
                   16048:     #
                   16049:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16050:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16051:     #
                   16052:     # By default, use standard grading
                   16053:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16054: 
1.541     raeburn  16055:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16056:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16057: #
                   16058: # Open all assignments
                   16059: #
                   16060:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16061:        my $opendate = time;
                   16062:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16063:            $opendate = $args->{'openallfrom'};
                   16064:        }
1.444     albertel 16065:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16066:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16067:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16068:        $outcome .= &mt('All assignments open starting [_1]',
                   16069:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16070:                    &Apache::lonnet::cput
                   16071:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16072:    }
                   16073: #
                   16074: # Set first page
                   16075: #
                   16076:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16077: 	    || ($cloneid)) {
1.445     albertel 16078: 	use LONCAPA::map;
1.444     albertel 16079: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16080: 
                   16081: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16082:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16083: 
1.444     albertel 16084:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16085:         my $title; my $url;
                   16086:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16087: 	    $title=&mt('Syllabus');
1.444     albertel 16088:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16089:         } else {
1.963     raeburn  16090:             $title=&mt('Table of Contents');
1.444     albertel 16091:             $url='/adm/navmaps';
                   16092:         }
1.445     albertel 16093: 
                   16094:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16095: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16096: 
                   16097: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16098:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16099:     }
1.566     albertel 16100: 
1.1075.2.161.  .1(raebu 16101:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16102: }
                   16103: 
1.1075.2.59  raeburn  16104: sub make_unique_code {
                   16105:     my ($cdom,$cnum) = @_;
                   16106:     # get lock on uniquecodes db
                   16107:     my $lockhash = {
                   16108:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16109:                                                   ':'.$env{'user.domain'},
                   16110:                    };
                   16111:     my $tries = 0;
                   16112:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16113:     my ($code,$error);
                   16114: 
                   16115:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16116:         $tries ++;
                   16117:         sleep 1;
                   16118:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16119:     }
                   16120:     if ($gotlock eq 'ok') {
                   16121:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16122:         my $gotcode;
                   16123:         my $attempts = 0;
                   16124:         while ((!$gotcode) && ($attempts < 100)) {
                   16125:             $code = &generate_code();
                   16126:             if (!exists($currcodes{$code})) {
                   16127:                 $gotcode = 1;
                   16128:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16129:                     $error = 'nostore';
                   16130:                 }
                   16131:             }
                   16132:             $attempts ++;
                   16133:         }
                   16134:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16135:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16136:     } else {
                   16137:         $error = 'nolock';
                   16138:     }
                   16139:     return ($code,$error);
                   16140: }
                   16141: 
                   16142: sub generate_code {
                   16143:     my $code;
                   16144:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16145:     for (my $i=0; $i<6; $i++) {
                   16146:         my $lettnum = int (rand 2);
                   16147:         my $item = '';
                   16148:         if ($lettnum) {
                   16149:             $item = $letts[int( rand(18) )];
                   16150:         } else {
                   16151:             $item = 1+int( rand(8) );
                   16152:         }
                   16153:         $code .= $item;
                   16154:     }
                   16155:     return $code;
                   16156: }
                   16157: 
1.444     albertel 16158: ############################################################
                   16159: ############################################################
                   16160: 
1.953     droeschl 16161: #SD
                   16162: # only Community and Course, or anything else?
1.378     raeburn  16163: sub course_type {
                   16164:     my ($cid) = @_;
                   16165:     if (!defined($cid)) {
                   16166:         $cid = $env{'request.course.id'};
                   16167:     }
1.404     albertel 16168:     if (defined($env{'course.'.$cid.'.type'})) {
                   16169:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16170:     } else {
                   16171:         return 'Course';
1.377     raeburn  16172:     }
                   16173: }
1.156     albertel 16174: 
1.406     raeburn  16175: sub group_term {
                   16176:     my $crstype = &course_type();
                   16177:     my %names = (
                   16178:                   'Course' => 'group',
1.865     raeburn  16179:                   'Community' => 'group',
1.406     raeburn  16180:                 );
                   16181:     return $names{$crstype};
                   16182: }
                   16183: 
1.902     raeburn  16184: sub course_types {
1.1075.2.59  raeburn  16185:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  16186:     my %typename = (
                   16187:                          official   => 'Official course',
                   16188:                          unofficial => 'Unofficial course',
                   16189:                          community  => 'Community',
1.1075.2.59  raeburn  16190:                          textbook   => 'Textbook course',
1.902     raeburn  16191:                    );
                   16192:     return (\@types,\%typename);
                   16193: }
                   16194: 
1.156     albertel 16195: sub icon {
                   16196:     my ($file)=@_;
1.505     albertel 16197:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16198:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16199:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16200:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16201: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16202: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16203: 	            $curfext.".gif") {
                   16204: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16205: 		$curfext.".gif";
                   16206: 	}
                   16207:     }
1.249     albertel 16208:     return &lonhttpdurl($iconname);
1.154     albertel 16209: } 
1.84      albertel 16210: 
1.575     albertel 16211: sub lonhttpdurl {
1.692     www      16212: #
                   16213: # Had been used for "small fry" static images on separate port 8080.
                   16214: # Modify here if lightweight http functionality desired again.
                   16215: # Currently eliminated due to increasing firewall issues.
                   16216: #
1.575     albertel 16217:     my ($url)=@_;
1.692     www      16218:     return $url;
1.215     albertel 16219: }
                   16220: 
1.213     albertel 16221: sub connection_aborted {
                   16222:     my ($r)=@_;
                   16223:     $r->print(" ");$r->rflush();
                   16224:     my $c = $r->connection;
                   16225:     return $c->aborted();
                   16226: }
                   16227: 
1.221     foxr     16228: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16229: #    strings as 'strings'.
                   16230: sub escape_single {
1.221     foxr     16231:     my ($input) = @_;
1.223     albertel 16232:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16233:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16234:     return $input;
                   16235: }
1.223     albertel 16236: 
1.222     foxr     16237: #  Same as escape_single, but escape's "'s  This 
                   16238: #  can be used for  "strings"
                   16239: sub escape_double {
                   16240:     my ($input) = @_;
                   16241:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16242:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16243:     return $input;
                   16244: }
1.223     albertel 16245:  
1.222     foxr     16246: #   Escapes the last element of a full URL.
                   16247: sub escape_url {
                   16248:     my ($url)   = @_;
1.238     raeburn  16249:     my @urlslices = split(/\//, $url,-1);
1.369     www      16250:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  16251:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16252: }
1.462     albertel 16253: 
1.820     raeburn  16254: sub compare_arrays {
                   16255:     my ($arrayref1,$arrayref2) = @_;
                   16256:     my (@difference,%count);
                   16257:     @difference = ();
                   16258:     %count = ();
                   16259:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16260:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16261:         foreach my $element (keys(%count)) {
                   16262:             if ($count{$element} == 1) {
                   16263:                 push(@difference,$element);
                   16264:             }
                   16265:         }
                   16266:     }
                   16267:     return @difference;
                   16268: }
                   16269: 
1.1075.2.152  raeburn  16270: sub lon_status_items {
                   16271:     my %defaults = (
                   16272:                      E         => 100,
                   16273:                      W         => 4,
                   16274:                      N         => 1,
                   16275:                      U         => 5,
                   16276:                      threshold => 200,
                   16277:                      sysmail   => 2500,
                   16278:                    );
                   16279:     my %names = (
                   16280:                    E => 'Errors',
                   16281:                    W => 'Warnings',
                   16282:                    N => 'Notices',
                   16283:                    U => 'Unsent',
                   16284:                 );
                   16285:     return (\%defaults,\%names);
                   16286: }
                   16287: 
1.817     bisitz   16288: # -------------------------------------------------------- Initialize user login
1.462     albertel 16289: sub init_user_environment {
1.463     albertel 16290:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16291:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16292: 
                   16293:     my $public=($username eq 'public' && $domain eq 'public');
                   16294: 
                   16295: # See if old ID present, if so, remove
                   16296: 
1.1062    raeburn  16297:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16298:     my $now=time;
                   16299: 
                   16300:     if ($public) {
                   16301: 	my $max_public=100;
                   16302: 	my $oldest;
                   16303: 	my $oldest_time=0;
                   16304: 	for(my $next=1;$next<=$max_public;$next++) {
                   16305: 	    if (-e $lonids."/publicuser_$next.id") {
                   16306: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16307: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16308: 		    $oldest_time=$mtime;
                   16309: 		    $oldest=$next;
                   16310: 		}
                   16311: 	    } else {
                   16312: 		$cookie="publicuser_$next";
                   16313: 		last;
                   16314: 	    }
                   16315: 	}
                   16316: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16317:     } else {
1.463     albertel 16318: 	# if this isn't a robot, kill any existing non-robot sessions
                   16319: 	if (!$args->{'robot'}) {
                   16320: 	    opendir(DIR,$lonids);
                   16321: 	    while ($filename=readdir(DIR)) {
                   16322: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  16323:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16324:                             &GDBM_READER(),0640)) {
                   16325:                         my $linkedfile;
                   16326:                         if (exists($oldenv{'user.linkedenv'})) {
                   16327:                             $linkedfile = $oldenv{'user.linkedenv'};
                   16328:                         }
                   16329:                         untie(%oldenv);
                   16330:                         if (unlink("$lonids/$filename")) {
                   16331:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16332:                                 if (-l "$lonids/$linkedfile.id") {
                   16333:                                     unlink("$lonids/$linkedfile.id");
                   16334:                                 }
                   16335:                             }
                   16336:                         }
                   16337:                     } else {
                   16338:                         unlink($lonids.'/'.$filename);
                   16339:                     }
1.463     albertel 16340: 		}
1.462     albertel 16341: 	    }
1.463     albertel 16342: 	    closedir(DIR);
1.1075.2.84  raeburn  16343: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16344:             my $namespace = 'nohist_courseeditor';
                   16345:             my $lockingkey = 'paste'."\0".'locked_num';
                   16346:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16347:                                                 $domain,$username);
                   16348:             if (exists($lockhash{$lockingkey})) {
                   16349:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16350:                 unless ($delresult eq 'ok') {
                   16351:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16352:                 }
                   16353:             }
1.462     albertel 16354: 	}
                   16355: # Give them a new cookie
1.463     albertel 16356: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16357: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16358: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16359:     
                   16360: # Initialize roles
                   16361: 
1.1062    raeburn  16362: 	($userroles,$firstaccenv,$timerintenv) = 
                   16363:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16364:     }
                   16365: # ------------------------------------ Check browser type and MathML capability
                   16366: 
1.1075.2.77  raeburn  16367:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16368:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16369: 
                   16370: # ------------------------------------------------------------- Get environment
                   16371: 
                   16372:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16373:     my ($tmp) = keys(%userenv);
                   16374:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   16375:     } else {
                   16376: 	undef(%userenv);
                   16377:     }
                   16378:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16379: 	$form->{'interface'}=$userenv{'interface'};
                   16380:     }
                   16381:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16382: 
                   16383: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16384:     foreach my $option ('interface','localpath','localres') {
                   16385:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16386:     }
                   16387: # --------------------------------------------------------- Write first profile
                   16388: 
                   16389:     {
1.1075.2.150  raeburn  16390:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 16391: 	my %initial_env = 
                   16392: 	    ("user.name"          => $username,
                   16393: 	     "user.domain"        => $domain,
                   16394: 	     "user.home"          => $authhost,
                   16395: 	     "browser.type"       => $clientbrowser,
                   16396: 	     "browser.version"    => $clientversion,
                   16397: 	     "browser.mathml"     => $clientmathml,
                   16398: 	     "browser.unicode"    => $clientunicode,
                   16399: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  16400:              "browser.mobile"     => $clientmobile,
                   16401:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  16402:              "browser.osversion"  => $clientosversion,
1.462     albertel 16403: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16404: 	     "request.course.fn"  => '',
                   16405: 	     "request.course.uri" => '',
                   16406: 	     "request.course.sec" => '',
                   16407: 	     "request.role"       => 'cm',
                   16408: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  16409: 	     "request.host"       => $ip,);
1.462     albertel 16410: 
                   16411:         if ($form->{'localpath'}) {
                   16412: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16413: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16414:         }
                   16415: 	
                   16416: 	if ($form->{'interface'}) {
                   16417: 	    $form->{'interface'}=~s/\W//gs;
                   16418: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16419: 	    $env{'browser.interface'}=$form->{'interface'};
                   16420: 	}
                   16421: 
1.1075.2.54  raeburn  16422:         if ($form->{'iptoken'}) {
                   16423:             my $lonhost = $r->dir_config('lonHostID');
                   16424:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16425:             $env{'user.noloadbalance'} = $lonhost;
                   16426:         }
                   16427: 
1.1075.2.120  raeburn  16428:         if ($form->{'noloadbalance'}) {
                   16429:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16430:             my $hosthere = $form->{'noloadbalance'};
                   16431:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16432:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16433:                 $env{'user.noloadbalance'} = $hosthere;
                   16434:             }
                   16435:         }
                   16436: 
1.1016    raeburn  16437:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  16438:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16439:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  16440: 
1.1075.2.125  raeburn  16441:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16442:                 $userenv{'availabletools.'.$tool} = 
                   16443:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16444:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16445:             }
1.724     raeburn  16446: 
1.1075.2.125  raeburn  16447:             foreach my $crstype ('official','unofficial','community','textbook') {
                   16448:                 $userenv{'canrequest.'.$crstype} =
                   16449:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16450:                                                       'reload','requestcourses',
                   16451:                                                       \%userenv,\%domdef,\%is_adv);
                   16452:             }
1.765     raeburn  16453: 
1.1075.2.125  raeburn  16454:             $userenv{'canrequest.author'} =
                   16455:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16456:                                                   'reload','requestauthor',
                   16457:                                                   \%userenv,\%domdef,\%is_adv);
                   16458:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16459:                                                  $domain,$username);
                   16460:             my $reqstatus = $reqauthor{'author_status'};
                   16461:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16462:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16463:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16464:                                                       $reqauthor{'author'}{'timestamp'};
                   16465:                 }
1.1075.2.14  raeburn  16466:             }
                   16467:         }
                   16468: 
1.462     albertel 16469: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16470: 
1.462     albertel 16471: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16472: 		 &GDBM_WRCREAT(),0640)) {
                   16473: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16474: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16475: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16476:             if (ref($firstaccenv) eq 'HASH') {
                   16477:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16478:             }
                   16479:             if (ref($timerintenv) eq 'HASH') {
                   16480:                 &_add_to_env(\%disk_env,$timerintenv);
                   16481:             }
1.463     albertel 16482: 	    if (ref($args->{'extra_env'})) {
                   16483: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16484: 	    }
1.462     albertel 16485: 	    untie(%disk_env);
                   16486: 	} else {
1.705     tempelho 16487: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16488: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16489: 	    return 'error: '.$!;
                   16490: 	}
                   16491:     }
                   16492:     $env{'request.role'}='cm';
                   16493:     $env{'request.role.adv'}=$env{'user.adv'};
                   16494:     $env{'browser.type'}=$clientbrowser;
                   16495: 
                   16496:     return $cookie;
                   16497: 
                   16498: }
                   16499: 
                   16500: sub _add_to_env {
                   16501:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16502:     if (ref($env_data) eq 'HASH') {
                   16503:         while (my ($key,$value) = each(%$env_data)) {
                   16504: 	    $idf->{$prefix.$key} = $value;
                   16505: 	    $env{$prefix.$key}   = $value;
                   16506:         }
1.462     albertel 16507:     }
                   16508: }
                   16509: 
1.685     tempelho 16510: # --- Get the symbolic name of a problem and the url
                   16511: sub get_symb {
                   16512:     my ($request,$silent) = @_;
1.726     raeburn  16513:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16514:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16515:     if ($symb eq '') {
                   16516:         if (!$silent) {
1.1071    raeburn  16517:             if (ref($request)) { 
                   16518:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16519:             }
1.685     tempelho 16520:             return ();
                   16521:         }
                   16522:     }
                   16523:     &Apache::lonenc::check_decrypt(\$symb);
                   16524:     return ($symb);
                   16525: }
                   16526: 
                   16527: # --------------------------------------------------------------Get annotation
                   16528: 
                   16529: sub get_annotation {
                   16530:     my ($symb,$enc) = @_;
                   16531: 
                   16532:     my $key = $symb;
                   16533:     if (!$enc) {
                   16534:         $key =
                   16535:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16536:     }
                   16537:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16538:     return $annotation{$key};
                   16539: }
                   16540: 
                   16541: sub clean_symb {
1.731     raeburn  16542:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16543: 
                   16544:     &Apache::lonenc::check_decrypt(\$symb);
                   16545:     my $enc = $env{'request.enc'};
1.731     raeburn  16546:     if ($delete_enc) {
1.730     raeburn  16547:         delete($env{'request.enc'});
                   16548:     }
1.685     tempelho 16549: 
                   16550:     return ($symb,$enc);
                   16551: }
1.462     albertel 16552: 
1.1075.2.69  raeburn  16553: ############################################################
                   16554: ############################################################
                   16555: 
                   16556: =pod
                   16557: 
                   16558: =head1 Routines for building display used to search for courses
                   16559: 
                   16560: 
                   16561: =over 4
                   16562: 
                   16563: =item * &build_filters()
                   16564: 
                   16565: Create markup for a table used to set filters to use when selecting
                   16566: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16567: and quotacheck.pl
                   16568: 
                   16569: 
                   16570: Inputs:
                   16571: 
                   16572: filterlist - anonymous array of fields to include as potential filters
                   16573: 
                   16574: crstype - course type
                   16575: 
                   16576: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16577:               to pop-open a course selector (will contain "extra element").
                   16578: 
                   16579: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16580: 
                   16581: filter - anonymous hash of criteria and their values
                   16582: 
                   16583: action - form action
                   16584: 
                   16585: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16586: 
                   16587: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16588: 
                   16589: cloneruname - username of owner of new course who wants to clone
                   16590: 
                   16591: clonerudom - domain of owner of new course who wants to clone
                   16592: 
                   16593: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16594: 
                   16595: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16596: 
                   16597: codedom - domain
                   16598: 
                   16599: formname - value of form element named "form".
                   16600: 
                   16601: fixeddom - domain, if fixed.
                   16602: 
                   16603: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16604: 
                   16605: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16606: 
                   16607: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16608: 
                   16609: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16610: 
                   16611: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16612: 
                   16613: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16614: 
                   16615: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16616: 
                   16617: 
                   16618: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16619: 
                   16620: 
                   16621: Side Effects: None
                   16622: 
                   16623: =cut
                   16624: 
                   16625: # ---------------------------------------------- search for courses based on last activity etc.
                   16626: 
                   16627: sub build_filters {
                   16628:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16629:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16630:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16631:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16632:         $clonetext,$clonewarning) = @_;
                   16633:     my ($list,$jscript);
                   16634:     my $onchange = 'javascript:updateFilters(this)';
                   16635:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16636:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16637:         $typeselectform,$instcodetitle);
                   16638:     if ($formname eq '') {
                   16639:         $formname = $caller;
                   16640:     }
                   16641:     foreach my $item (@{$filterlist}) {
                   16642:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16643:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16644:             if ($item eq 'domainfilter') {
                   16645:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16646:             } elsif ($item eq 'coursefilter') {
                   16647:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16648:             } elsif ($item eq 'ownerfilter') {
                   16649:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16650:             } elsif ($item eq 'ownerdomfilter') {
                   16651:                 $filter->{'ownerdomfilter'} =
                   16652:                     &LONCAPA::clean_domain($filter->{$item});
                   16653:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16654:                                                        'ownerdomfilter',1);
                   16655:             } elsif ($item eq 'personfilter') {
                   16656:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16657:             } elsif ($item eq 'persondomfilter') {
                   16658:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16659:                                                         'persondomfilter',1);
                   16660:             } else {
                   16661:                 $filter->{$item} =~ s/\W//g;
                   16662:             }
                   16663:             if (!$filter->{$item}) {
                   16664:                 $filter->{$item} = '';
                   16665:             }
                   16666:         }
                   16667:         if ($item eq 'domainfilter') {
                   16668:             my $allow_blank = 1;
                   16669:             if ($formname eq 'portform') {
                   16670:                 $allow_blank=0;
                   16671:             } elsif ($formname eq 'studentform') {
                   16672:                 $allow_blank=0;
                   16673:             }
                   16674:             if ($fixeddom) {
                   16675:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16676:                                     ' value="'.$codedom.'" />'.
                   16677:                                     &Apache::lonnet::domain($codedom,'description');
                   16678:             } else {
                   16679:                 $domainselectform = &select_dom_form($filter->{$item},
                   16680:                                                      'domainfilter',
                   16681:                                                       $allow_blank,'',$onchange);
                   16682:             }
                   16683:         } else {
                   16684:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16685:         }
                   16686:     }
                   16687: 
                   16688:     # last course activity filter and selection
                   16689:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16690: 
                   16691:     # course created filter and selection
                   16692:     if (exists($filter->{'createdfilter'})) {
                   16693:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16694:     }
                   16695: 
                   16696:     my %lt = &Apache::lonlocal::texthash(
                   16697:                 'cac' => "$crstype Activity",
                   16698:                 'ccr' => "$crstype Created",
                   16699:                 'cde' => "$crstype Title",
                   16700:                 'cdo' => "$crstype Domain",
                   16701:                 'ins' => 'Institutional Code',
                   16702:                 'inc' => 'Institutional Categorization',
                   16703:                 'cow' => "$crstype Owner/Co-owner",
                   16704:                 'cop' => "$crstype Personnel Includes",
                   16705:                 'cog' => 'Type',
                   16706:              );
                   16707: 
                   16708:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16709:         my $typeval = 'Course';
                   16710:         if ($crstype eq 'Community') {
                   16711:             $typeval = 'Community';
                   16712:         }
                   16713:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16714:     } else {
                   16715:         $typeselectform =  '<select name="type" size="1"';
                   16716:         if ($onchange) {
                   16717:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16718:         }
                   16719:         $typeselectform .= '>'."\n";
                   16720:         foreach my $posstype ('Course','Community') {
                   16721:             $typeselectform.='<option value="'.$posstype.'"'.
                   16722:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16723:         }
                   16724:         $typeselectform.="</select>";
                   16725:     }
                   16726: 
                   16727:     my ($cloneableonlyform,$cloneabletitle);
                   16728:     if (exists($filter->{'cloneableonly'})) {
                   16729:         my $cloneableon = '';
                   16730:         my $cloneableoff = ' checked="checked"';
                   16731:         if ($filter->{'cloneableonly'}) {
                   16732:             $cloneableon = $cloneableoff;
                   16733:             $cloneableoff = '';
                   16734:         }
                   16735:         $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>';
                   16736:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16737:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16738:         } else {
                   16739:             $cloneabletitle = &mt('Cloneable by you');
                   16740:         }
                   16741:     }
                   16742:     my $officialjs;
                   16743:     if ($crstype eq 'Course') {
                   16744:         if (exists($filter->{'instcodefilter'})) {
                   16745: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16746: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16747:             if ($codedom) {
                   16748:                 $officialjs = 1;
                   16749:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16750:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16751:                                                                   $officialjs,$codetitlesref);
                   16752:                 if ($jscript) {
                   16753:                     $jscript = '<script type="text/javascript">'."\n".
                   16754:                                '// <![CDATA['."\n".
                   16755:                                $jscript."\n".
                   16756:                                '// ]]>'."\n".
                   16757:                                '</script>'."\n";
                   16758:                 }
                   16759:             }
                   16760:             if ($instcodeform eq '') {
                   16761:                 $instcodeform =
                   16762:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16763:                     $list->{'instcodefilter'}.'" />';
                   16764:                 $instcodetitle = $lt{'ins'};
                   16765:             } else {
                   16766:                 $instcodetitle = $lt{'inc'};
                   16767:             }
                   16768:             if ($fixeddom) {
                   16769:                 $instcodetitle .= '<br />('.$codedom.')';
                   16770:             }
                   16771:         }
                   16772:     }
                   16773:     my $output = qq|
                   16774: <form method="post" name="filterpicker" action="$action">
                   16775: <input type="hidden" name="form" value="$formname" />
                   16776: |;
                   16777:     if ($formname eq 'modifycourse') {
                   16778:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16779:                    '<input type="hidden" name="prevphase" value="'.
                   16780:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16781:     } elsif ($formname eq 'quotacheck') {
                   16782:         $output .= qq|
                   16783: <input type="hidden" name="sortby" value="" />
                   16784: <input type="hidden" name="sortorder" value="" />
                   16785: |;
                   16786:     } else {
1.1075.2.69  raeburn  16787:         my $name_input;
                   16788:         if ($cnameelement ne '') {
                   16789:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16790:                           $cnameelement.'" />';
                   16791:         }
                   16792:         $output .= qq|
                   16793: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16794: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16795: $name_input
                   16796: $roleelement
                   16797: $multelement
                   16798: $typeelement
                   16799: |;
                   16800:         if ($formname eq 'portform') {
                   16801:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16802:         }
                   16803:     }
                   16804:     if ($fixeddom) {
                   16805:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16806:     }
                   16807:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16808:     if ($sincefilterform) {
                   16809:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16810:                   .$sincefilterform
                   16811:                   .&Apache::lonhtmlcommon::row_closure();
                   16812:     }
                   16813:     if ($createdfilterform) {
                   16814:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16815:                   .$createdfilterform
                   16816:                   .&Apache::lonhtmlcommon::row_closure();
                   16817:     }
                   16818:     if ($domainselectform) {
                   16819:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16820:                   .$domainselectform
                   16821:                   .&Apache::lonhtmlcommon::row_closure();
                   16822:     }
                   16823:     if ($typeselectform) {
                   16824:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16825:             $output .= $typeselectform;
                   16826:         } else {
                   16827:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16828:                       .$typeselectform
                   16829:                       .&Apache::lonhtmlcommon::row_closure();
                   16830:         }
                   16831:     }
                   16832:     if ($instcodeform) {
                   16833:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16834:                   .$instcodeform
                   16835:                   .&Apache::lonhtmlcommon::row_closure();
                   16836:     }
                   16837:     if (exists($filter->{'ownerfilter'})) {
                   16838:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16839:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16840:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16841:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16842:                    $ownerdomselectform.'</td></tr></table>'.
                   16843:                    &Apache::lonhtmlcommon::row_closure();
                   16844:     }
                   16845:     if (exists($filter->{'personfilter'})) {
                   16846:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16847:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16848:                    '<input type="text" name="personfilter" size="20" value="'.
                   16849:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16850:                    $persondomselectform.'</td></tr></table>'.
                   16851:                    &Apache::lonhtmlcommon::row_closure();
                   16852:     }
                   16853:     if (exists($filter->{'coursefilter'})) {
                   16854:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16855:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16856:                   .$list->{'coursefilter'}.'" />'
                   16857:                   .&Apache::lonhtmlcommon::row_closure();
                   16858:     }
                   16859:     if ($cloneableonlyform) {
                   16860:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16861:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16862:     }
                   16863:     if (exists($filter->{'descriptfilter'})) {
                   16864:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16865:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16866:                   .$list->{'descriptfilter'}.'" />'
                   16867:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16868:     }
                   16869:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16870:                '<input type="hidden" name="updater" value="" />'."\n".
                   16871:                '<input type="submit" name="gosearch" value="'.
                   16872:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16873:     return $jscript.$clonewarning.$output;
                   16874: }
                   16875: 
                   16876: =pod
                   16877: 
                   16878: =item * &timebased_select_form()
                   16879: 
                   16880: Create markup for a dropdown list used to select a time-based
                   16881: filter e.g., Course Activity, Course Created, when searching for courses
                   16882: or communities
                   16883: 
                   16884: Inputs:
                   16885: 
                   16886: item - name of form element (sincefilter or createdfilter)
                   16887: 
                   16888: filter - anonymous hash of criteria and their values
                   16889: 
                   16890: Returns: HTML for a select box contained a blank, then six time selections,
                   16891:          with value set in incoming form variables currently selected.
                   16892: 
                   16893: Side Effects: None
                   16894: 
                   16895: =cut
                   16896: 
                   16897: sub timebased_select_form {
                   16898:     my ($item,$filter) = @_;
                   16899:     if (ref($filter) eq 'HASH') {
                   16900:         $filter->{$item} =~ s/[^\d-]//g;
                   16901:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16902:         return &select_form(
                   16903:                             $filter->{$item},
                   16904:                             $item,
                   16905:                             {      '-1' => '',
                   16906:                                 '86400' => &mt('today'),
                   16907:                                '604800' => &mt('last week'),
                   16908:                               '2592000' => &mt('last month'),
                   16909:                               '7776000' => &mt('last three months'),
                   16910:                              '15552000' => &mt('last six months'),
                   16911:                              '31104000' => &mt('last year'),
                   16912:                     'select_form_order' =>
                   16913:                            ['-1','86400','604800','2592000','7776000',
                   16914:                             '15552000','31104000']});
                   16915:     }
                   16916: }
                   16917: 
                   16918: =pod
                   16919: 
                   16920: =item * &js_changer()
                   16921: 
                   16922: Create script tag containing Javascript used to submit course search form
                   16923: when course type or domain is changed, and also to hide 'Searching ...' on
                   16924: page load completion for page showing search result.
                   16925: 
                   16926: Inputs: None
                   16927: 
                   16928: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16929: 
                   16930: Side Effects: None
                   16931: 
                   16932: =cut
                   16933: 
                   16934: sub js_changer {
                   16935:     return <<ENDJS;
                   16936: <script type="text/javascript">
                   16937: // <![CDATA[
                   16938: function updateFilters(caller) {
                   16939:     if (typeof(caller) != "undefined") {
                   16940:         document.filterpicker.updater.value = caller.name;
                   16941:     }
                   16942:     document.filterpicker.submit();
                   16943: }
                   16944: 
                   16945: function hideSearching() {
                   16946:     if (document.getElementById('searching')) {
                   16947:         document.getElementById('searching').style.display = 'none';
                   16948:     }
                   16949:     return;
                   16950: }
                   16951: 
                   16952: // ]]>
                   16953: </script>
                   16954: 
                   16955: ENDJS
                   16956: }
                   16957: 
                   16958: =pod
                   16959: 
                   16960: =item * &search_courses()
                   16961: 
                   16962: Process selected filters form course search form and pass to lonnet::courseiddump
                   16963: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16964: 
                   16965: Inputs:
                   16966: 
                   16967: dom - domain being searched
                   16968: 
                   16969: type - course type ('Course' or 'Community' or '.' if any).
                   16970: 
                   16971: filter - anonymous hash of criteria and their values
                   16972: 
                   16973: numtitles - for institutional codes - number of categories
                   16974: 
                   16975: cloneruname - optional username of new course owner
                   16976: 
                   16977: clonerudom - optional domain of new course owner
                   16978: 
1.1075.2.95  raeburn  16979: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16980:             (used when DC is using course creation form)
                   16981: 
                   16982: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16983: 
1.1075.2.95  raeburn  16984: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16985:            (and so can clone automatically)
                   16986: 
                   16987: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16988: 
                   16989: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16990:               courses to clone
1.1075.2.69  raeburn  16991: 
                   16992: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16993: 
                   16994: 
                   16995: Side Effects: None
                   16996: 
                   16997: =cut
                   16998: 
                   16999: 
                   17000: sub search_courses {
1.1075.2.95  raeburn  17001:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17002:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17003:     my (%courses,%showcourses,$cloner);
                   17004:     if (($filter->{'ownerfilter'} ne '') ||
                   17005:         ($filter->{'ownerdomfilter'} ne '')) {
                   17006:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17007:                                        $filter->{'ownerdomfilter'};
                   17008:     }
                   17009:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17010:         if (!$filter->{$item}) {
                   17011:             $filter->{$item}='.';
                   17012:         }
                   17013:     }
                   17014:     my $now = time;
                   17015:     my $timefilter =
                   17016:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17017:     my ($createdbefore,$createdafter);
                   17018:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17019:         $createdbefore = $now;
                   17020:         $createdafter = $now-$filter->{'createdfilter'};
                   17021:     }
                   17022:     my ($instcodefilter,$regexpok);
                   17023:     if ($numtitles) {
                   17024:         if ($env{'form.official'} eq 'on') {
                   17025:             $instcodefilter =
                   17026:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17027:             $regexpok = 1;
                   17028:         } elsif ($env{'form.official'} eq 'off') {
                   17029:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17030:             unless ($instcodefilter eq '') {
                   17031:                 $regexpok = -1;
                   17032:             }
                   17033:         }
                   17034:     } else {
                   17035:         $instcodefilter = $filter->{'instcodefilter'};
                   17036:     }
                   17037:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17038:     if ($type eq '') { $type = '.'; }
                   17039: 
                   17040:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17041:         $cloner = $cloneruname.':'.$clonerudom;
                   17042:     }
                   17043:     %courses = &Apache::lonnet::courseiddump($dom,
                   17044:                                              $filter->{'descriptfilter'},
                   17045:                                              $timefilter,
                   17046:                                              $instcodefilter,
                   17047:                                              $filter->{'combownerfilter'},
                   17048:                                              $filter->{'coursefilter'},
                   17049:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17050:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17051:                                              $filter->{'cloneableonly'},
                   17052:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17053:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17054:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17055:         my $ccrole;
                   17056:         if ($type eq 'Community') {
                   17057:             $ccrole = 'co';
                   17058:         } else {
                   17059:             $ccrole = 'cc';
                   17060:         }
                   17061:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17062:                                                      $filter->{'persondomfilter'},
                   17063:                                                      'userroles',undef,
                   17064:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17065:                                                      $dom);
                   17066:         foreach my $role (keys(%rolehash)) {
                   17067:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17068:             my $cid = $cdom.'_'.$cnum;
                   17069:             if (exists($courses{$cid})) {
                   17070:                 if (ref($courses{$cid}) eq 'HASH') {
                   17071:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17072:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17073:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17074:                         }
                   17075:                     } else {
                   17076:                         $courses{$cid}{roles} = [$courserole];
                   17077:                     }
                   17078:                     $showcourses{$cid} = $courses{$cid};
                   17079:                 }
                   17080:             }
                   17081:         }
                   17082:         %courses = %showcourses;
                   17083:     }
                   17084:     return %courses;
                   17085: }
                   17086: 
                   17087: =pod
                   17088: 
                   17089: =back
                   17090: 
1.1075.2.88  raeburn  17091: =head1 Routines for version requirements for current course.
                   17092: 
                   17093: =over 4
                   17094: 
                   17095: =item * &check_release_required()
                   17096: 
                   17097: Compares required LON-CAPA version with version on server, and
                   17098: if required version is newer looks for a server with the required version.
                   17099: 
                   17100: Looks first at servers in user's owen domain; if none suitable, looks at
                   17101: servers in course's domain are permitted to host sessions for user's domain.
                   17102: 
                   17103: Inputs:
                   17104: 
                   17105: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17106: 
                   17107: $courseid - Course ID of current course
                   17108: 
                   17109: $rolecode - User's current role in course (for switchserver query string).
                   17110: 
                   17111: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17112: 
                   17113: 
                   17114: Returns:
                   17115: 
                   17116: $switchserver - query string tp append to /adm/switchserver call (if
                   17117:                 current server's LON-CAPA version is too old.
                   17118: 
                   17119: $warning - Message is displayed if no suitable server could be found.
                   17120: 
                   17121: =cut
                   17122: 
                   17123: sub check_release_required {
                   17124:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17125:     my ($switchserver,$warning);
                   17126:     if ($required ne '') {
                   17127:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17128:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17129:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17130:             my $otherserver;
                   17131:             if (($major eq '' && $minor eq '') ||
                   17132:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17133:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17134:                 my $switchlcrev =
                   17135:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17136:                                                            $userdomserver);
                   17137:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17138:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17139:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17140:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17141:                     if ($cdom ne $env{'user.domain'}) {
                   17142:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17143:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17144:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17145:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17146:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17147:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17148:                         my $canhost =
                   17149:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17150:                                                               $coursedomserver,
                   17151:                                                               $remoterev,
                   17152:                                                               $udomdefaults{'remotesessions'},
                   17153:                                                               $defdomdefaults{'hostedsessions'});
                   17154: 
                   17155:                         if ($canhost) {
                   17156:                             $otherserver = $coursedomserver;
                   17157:                         } else {
                   17158:                             $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.");
                   17159:                         }
                   17160:                     } else {
                   17161:                         $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).");
                   17162:                     }
                   17163:                 } else {
                   17164:                     $otherserver = $userdomserver;
                   17165:                 }
                   17166:             }
                   17167:             if ($otherserver ne '') {
                   17168:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17169:             }
                   17170:         }
                   17171:     }
                   17172:     return ($switchserver,$warning);
                   17173: }
                   17174: 
                   17175: =pod
                   17176: 
                   17177: =item * &check_release_result()
                   17178: 
                   17179: Inputs:
                   17180: 
                   17181: $switchwarning - Warning message if no suitable server found to host session.
                   17182: 
                   17183: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17184:                 and current role.
                   17185: 
                   17186: Returns: HTML to display with information about requirement to switch server.
                   17187:          Either displaying warning with link to Roles/Courses screen or
                   17188:          display link to switchserver.
                   17189: 
1.1075.2.69  raeburn  17190: =cut
                   17191: 
1.1075.2.88  raeburn  17192: sub check_release_result {
                   17193:     my ($switchwarning,$switchserver) = @_;
                   17194:     my $output = &start_page('Selected course unavailable on this server').
                   17195:                  '<p class="LC_warning">';
                   17196:     if ($switchwarning) {
                   17197:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17198:         if (&show_course()) {
                   17199:             $output .= &mt('Display courses');
                   17200:         } else {
                   17201:             $output .= &mt('Display roles');
                   17202:         }
                   17203:         $output .= '</a>';
                   17204:     } elsif ($switchserver) {
                   17205:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17206:                    '<br />'.
                   17207:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17208:                    &mt('Switch Server').
                   17209:                    '</a>';
                   17210:     }
                   17211:     $output .= '</p>'.&end_page();
                   17212:     return $output;
                   17213: }
                   17214: 
                   17215: =pod
                   17216: 
                   17217: =item * &needs_coursereinit()
                   17218: 
                   17219: Determine if course contents stored for user's session needs to be
                   17220: refreshed, because content has changed since "Big Hash" last tied.
                   17221: 
                   17222: Check for change is made if time last checked is more than 10 minutes ago
                   17223: (by default).
                   17224: 
                   17225: Inputs:
                   17226: 
                   17227: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17228: 
                   17229: $interval (optional) - Time which may elapse (in s) between last check for content
                   17230:                        change in current course. (default: 600 s).
                   17231: 
                   17232: Returns: an array; first element is:
                   17233: 
                   17234: =over 4
                   17235: 
                   17236: 'switch' - if content updates mean user's session
                   17237:            needs to be switched to a server running a newer LON-CAPA version
                   17238: 
                   17239: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17240:            on current server hosting user's session
                   17241: 
                   17242: ''       - if no action required.
                   17243: 
                   17244: =back
                   17245: 
                   17246: If first item element is 'switch':
                   17247: 
                   17248: second item is $switchwarning - Warning message if no suitable server found to host session.
                   17249: 
                   17250: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17251:                               and current role.
                   17252: 
                   17253: otherwise: no other elements returned.
                   17254: 
                   17255: =back
                   17256: 
                   17257: =cut
                   17258: 
                   17259: sub needs_coursereinit {
                   17260:     my ($loncaparev,$interval) = @_;
                   17261:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17262:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17263:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17264:     my $now = time;
                   17265:     if ($interval eq '') {
                   17266:         $interval = 600;
                   17267:     }
                   17268:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   17269:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .1(raebu 17270:21):         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
                   17271:21):         if ($blocked) {
                   17272:21):             return ();
                   17273:21):         }
                   17274:21):         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
1.1075.2.88  raeburn  17275:         if ($lastchange > $env{'request.course.tied'}) {
                   17276:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17277:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17278:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17279:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17280:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17281:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17282:                     my ($switchserver,$switchwarning) =
                   17283:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17284:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17285:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17286:                         return ('switch',$switchwarning,$switchserver);
                   17287:                     }
                   17288:                 }
                   17289:             }
                   17290:             return ('update');
                   17291:         }
                   17292:     }
                   17293:     return ();
                   17294: }
1.1075.2.69  raeburn  17295: 
1.1075.2.11  raeburn  17296: sub update_content_constraints {
                   17297:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17298:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17299:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17300:     my %checkresponsetypes;
                   17301:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   17302:         my ($item,$name,$value) = split(/:/,$key);
                   17303:         if ($item eq 'resourcetag') {
                   17304:             if ($name eq 'responsetype') {
                   17305:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17306:             }
                   17307:         }
                   17308:     }
                   17309:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17310:     if (defined($navmap)) {
                   17311:         my %allresponses;
                   17312:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17313:             my %responses = $res->responseTypes();
                   17314:             foreach my $key (keys(%responses)) {
                   17315:                 next unless(exists($checkresponsetypes{$key}));
                   17316:                 $allresponses{$key} += $responses{$key};
                   17317:             }
                   17318:         }
                   17319:         foreach my $key (keys(%allresponses)) {
                   17320:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17321:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17322:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17323:             }
                   17324:         }
                   17325:         undef($navmap);
                   17326:     }
                   17327:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17328:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17329:     }
                   17330:     return;
                   17331: }
                   17332: 
1.1075.2.27  raeburn  17333: sub allmaps_incourse {
                   17334:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17335:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17336:         $cid = $env{'request.course.id'};
                   17337:         $cdom = $env{'course.'.$cid.'.domain'};
                   17338:         $cnum = $env{'course.'.$cid.'.num'};
                   17339:         $chome = $env{'course.'.$cid.'.home'};
                   17340:     }
                   17341:     my %allmaps = ();
                   17342:     my $lastchange =
                   17343:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17344:     if ($lastchange > $env{'request.course.tied'}) {
                   17345:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17346:         unless ($ferr) {
                   17347:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17348:         }
                   17349:     }
                   17350:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17351:     if (defined($navmap)) {
                   17352:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17353:             $allmaps{$res->src()} = 1;
                   17354:         }
                   17355:     }
                   17356:     return \%allmaps;
                   17357: }
                   17358: 
1.1075.2.11  raeburn  17359: sub parse_supplemental_title {
                   17360:     my ($title) = @_;
                   17361: 
                   17362:     my ($foldertitle,$renametitle);
                   17363:     if ($title =~ /&amp;&amp;&amp;/) {
                   17364:         $title = &HTML::Entites::decode($title);
                   17365:     }
                   17366:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17367:         $renametitle=$4;
                   17368:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17369:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17370:         my $name =  &plainname($uname,$udom);
                   17371:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17372:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17373:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17374:             $name.': <br />'.$foldertitle;
                   17375:     }
                   17376:     if (wantarray) {
                   17377:         return ($title,$foldertitle,$renametitle);
                   17378:     }
                   17379:     return $title;
                   17380: }
                   17381: 
1.1075.2.43  raeburn  17382: sub recurse_supplemental {
                   17383:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17384:     if ($suppmap) {
                   17385:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17386:         if ($fatal) {
                   17387:             $errors ++;
                   17388:         } else {
                   17389:             if ($#LONCAPA::map::resources > 0) {
                   17390:                 foreach my $res (@LONCAPA::map::resources) {
                   17391:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17392:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  17393:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17394:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  17395:                         } else {
                   17396:                             $numfiles ++;
                   17397:                         }
                   17398:                     }
                   17399:                 }
                   17400:             }
                   17401:         }
                   17402:     }
                   17403:     return ($numfiles,$errors);
                   17404: }
                   17405: 
1.1075.2.18  raeburn  17406: sub symb_to_docspath {
1.1075.2.119  raeburn  17407:     my ($symb,$navmapref) = @_;
                   17408:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  17409:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17410:     if ($resurl=~/\.(sequence|page)$/) {
                   17411:         $mapurl=$resurl;
                   17412:     } elsif ($resurl eq 'adm/navmaps') {
                   17413:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17414:     }
                   17415:     my $mapresobj;
1.1075.2.119  raeburn  17416:     unless (ref($$navmapref)) {
                   17417:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17418:     }
                   17419:     if (ref($$navmapref)) {
                   17420:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  17421:     }
                   17422:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17423:     my $type=$2;
                   17424:     my $path;
                   17425:     if (ref($mapresobj)) {
                   17426:         my $pcslist = $mapresobj->map_hierarchy();
                   17427:         if ($pcslist ne '') {
                   17428:             foreach my $pc (split(/,/,$pcslist)) {
                   17429:                 next if ($pc <= 1);
1.1075.2.119  raeburn  17430:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  17431:                 if (ref($res)) {
                   17432:                     my $thisurl = $res->src();
                   17433:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17434:                     my $thistitle = $res->title();
                   17435:                     $path .= '&'.
                   17436:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  17437:                              &escape($thistitle).
1.1075.2.18  raeburn  17438:                              ':'.$res->randompick().
                   17439:                              ':'.$res->randomout().
                   17440:                              ':'.$res->encrypted().
                   17441:                              ':'.$res->randomorder().
                   17442:                              ':'.$res->is_page();
                   17443:                 }
                   17444:             }
                   17445:         }
                   17446:         $path =~ s/^\&//;
                   17447:         my $maptitle = $mapresobj->title();
                   17448:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17449:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17450:         }
                   17451:         $path .= (($path ne '')? '&' : '').
                   17452:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17453:                  &escape($maptitle).
1.1075.2.18  raeburn  17454:                  ':'.$mapresobj->randompick().
                   17455:                  ':'.$mapresobj->randomout().
                   17456:                  ':'.$mapresobj->encrypted().
                   17457:                  ':'.$mapresobj->randomorder().
                   17458:                  ':'.$mapresobj->is_page();
                   17459:     } else {
                   17460:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17461:         my $ispage = (($type eq 'page')? 1 : '');
                   17462:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17463:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17464:         }
                   17465:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17466:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  17467:     }
                   17468:     unless ($mapurl eq 'default') {
                   17469:         $path = 'default&'.
1.1075.2.46  raeburn  17470:                 &escape('Main Content').
1.1075.2.18  raeburn  17471:                 ':::::&'.$path;
                   17472:     }
                   17473:     return $path;
                   17474: }
                   17475: 
1.1075.2.14  raeburn  17476: sub captcha_display {
1.1075.2.137  raeburn  17477:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17478:     my ($output,$error);
1.1075.2.107  raeburn  17479:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17480:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17481:     if ($captcha eq 'original') {
                   17482:         $output = &create_captcha();
                   17483:         unless ($output) {
                   17484:             $error = 'captcha';
                   17485:         }
                   17486:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17487:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17488:         unless ($output) {
                   17489:             $error = 'recaptcha';
                   17490:         }
                   17491:     }
1.1075.2.107  raeburn  17492:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17493: }
                   17494: 
                   17495: sub captcha_response {
1.1075.2.137  raeburn  17496:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17497:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17498:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17499:     if ($captcha eq 'original') {
                   17500:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17501:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17502:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17503:     } else {
                   17504:         $captcha_chk = 1;
                   17505:     }
                   17506:     return ($captcha_chk,$captcha_error);
                   17507: }
                   17508: 
                   17509: sub get_captcha_config {
1.1075.2.137  raeburn  17510:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17511:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17512:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17513:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17514:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17515:     if ($context eq 'usercreation') {
                   17516:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17517:         if (ref($domconfig{$context}) eq 'HASH') {
                   17518:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17519:             if (ref($hashtocheck) eq 'HASH') {
                   17520:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17521:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17522:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17523:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17524:                     }
                   17525:                     if ($privkey && $pubkey) {
                   17526:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17527:                         $version = $hashtocheck->{'recaptchaversion'};
                   17528:                         if ($version ne '2') {
                   17529:                             $version = 1;
                   17530:                         }
1.1075.2.14  raeburn  17531:                     } else {
                   17532:                         $captcha = 'original';
                   17533:                     }
                   17534:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17535:                     $captcha = 'original';
                   17536:                 }
                   17537:             }
                   17538:         } else {
                   17539:             $captcha = 'captcha';
                   17540:         }
                   17541:     } elsif ($context eq 'login') {
                   17542:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17543:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17544:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17545:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17546:             if ($privkey && $pubkey) {
                   17547:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17548:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17549:                 if ($version ne '2') {
                   17550:                     $version = 1;
                   17551:                 }
1.1075.2.14  raeburn  17552:             } else {
                   17553:                 $captcha = 'original';
                   17554:             }
                   17555:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17556:             $captcha = 'original';
                   17557:         }
1.1075.2.137  raeburn  17558:     } elsif ($context eq 'passwords') {
                   17559:         if ($dom_in_effect) {
                   17560:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17561:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17562:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17563:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17564:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17565:                 }
                   17566:                 if ($privkey && $pubkey) {
                   17567:                     $captcha = 'recaptcha';
                   17568:                     $version = $passwdconf{'recaptchaversion'};
                   17569:                     if ($version ne '2') {
                   17570:                         $version = 1;
                   17571:                     }
                   17572:                 } else {
                   17573:                     $captcha = 'original';
                   17574:                 }
                   17575:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17576:                 $captcha = 'original';
                   17577:             }
                   17578:         }
1.1075.2.14  raeburn  17579:     }
1.1075.2.107  raeburn  17580:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17581: }
                   17582: 
                   17583: sub create_captcha {
                   17584:     my %captcha_params = &captcha_settings();
                   17585:     my ($output,$maxtries,$tries) = ('',10,0);
                   17586:     while ($tries < $maxtries) {
                   17587:         $tries ++;
                   17588:         my $captcha = Authen::Captcha->new (
                   17589:                                            output_folder => $captcha_params{'output_dir'},
                   17590:                                            data_folder   => $captcha_params{'db_dir'},
                   17591:                                           );
                   17592:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17593: 
                   17594:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17595:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  17596:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  17597:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17598:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1075.2.158  raeburn  17599:                       '</span><br />'.
1.1075.2.66  raeburn  17600:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17601:             last;
                   17602:         }
                   17603:     }
1.1075.2.158  raeburn  17604:     if ($output eq '') {
                   17605:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   17606:     }
1.1075.2.14  raeburn  17607:     return $output;
                   17608: }
                   17609: 
                   17610: sub captcha_settings {
                   17611:     my %captcha_params = (
                   17612:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17613:                            www_output_dir => "/captchaspool",
                   17614:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17615:                            numchars       => '5',
                   17616:                          );
                   17617:     return %captcha_params;
                   17618: }
                   17619: 
                   17620: sub check_captcha {
                   17621:     my ($captcha_chk,$captcha_error);
                   17622:     my $code = $env{'form.code'};
                   17623:     my $md5sum = $env{'form.crypt'};
                   17624:     my %captcha_params = &captcha_settings();
                   17625:     my $captcha = Authen::Captcha->new(
                   17626:                       output_folder => $captcha_params{'output_dir'},
                   17627:                       data_folder   => $captcha_params{'db_dir'},
                   17628:                   );
1.1075.2.26  raeburn  17629:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17630:     my %captcha_hash = (
                   17631:                         0       => 'Code not checked (file error)',
                   17632:                        -1      => 'Failed: code expired',
                   17633:                        -2      => 'Failed: invalid code (not in database)',
                   17634:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17635:     );
                   17636:     if ($captcha_chk != 1) {
                   17637:         $captcha_error = $captcha_hash{$captcha_chk}
                   17638:     }
                   17639:     return ($captcha_chk,$captcha_error);
                   17640: }
                   17641: 
                   17642: sub create_recaptcha {
1.1075.2.107  raeburn  17643:     my ($pubkey,$version) = @_;
                   17644:     if ($version >= 2) {
1.1075.2.158  raeburn  17645:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   17646:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  17647:     } else {
                   17648:         my $use_ssl;
                   17649:         if ($ENV{'SERVER_PORT'} == 443) {
                   17650:             $use_ssl = 1;
                   17651:         }
                   17652:         my $captcha = Captcha::reCAPTCHA->new;
                   17653:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17654:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17655:                &mt('If the text is hard to read, [_1] will replace them.',
                   17656:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17657:                '<br /><br />';
                   17658:      }
1.1075.2.14  raeburn  17659: }
                   17660: 
                   17661: sub check_recaptcha {
1.1075.2.107  raeburn  17662:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17663:     my $captcha_chk;
1.1075.2.150  raeburn  17664:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  17665:     if ($version >= 2) {
                   17666:         my $ua = LWP::UserAgent->new;
                   17667:         $ua->timeout(10);
                   17668:         my %info = (
                   17669:                      secret   => $privkey,
                   17670:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  17671:                      remoteip => $ip,
1.1075.2.107  raeburn  17672:                    );
                   17673:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17674:         if ($response->is_success)  {
                   17675:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17676:             if (ref($data) eq 'HASH') {
                   17677:                 if ($data->{'success'}) {
                   17678:                     $captcha_chk = 1;
                   17679:                 }
                   17680:             }
                   17681:         }
                   17682:     } else {
                   17683:         my $captcha = Captcha::reCAPTCHA->new;
                   17684:         my $captcha_result =
                   17685:             $captcha->check_answer(
                   17686:                                     $privkey,
1.1075.2.150  raeburn  17687:                                     $ip,
1.1075.2.107  raeburn  17688:                                     $env{'form.recaptcha_challenge_field'},
                   17689:                                     $env{'form.recaptcha_response_field'},
                   17690:                                   );
                   17691:         if ($captcha_result->{is_valid}) {
                   17692:             $captcha_chk = 1;
                   17693:         }
1.1075.2.14  raeburn  17694:     }
                   17695:     return $captcha_chk;
                   17696: }
                   17697: 
1.1075.2.64  raeburn  17698: sub emailusername_info {
1.1075.2.103  raeburn  17699:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17700:     my %titles = &Apache::lonlocal::texthash (
                   17701:                      lastname      => 'Last Name',
                   17702:                      firstname     => 'First Name',
                   17703:                      institution   => 'School/college/university',
                   17704:                      location      => "School's city, state/province, country",
                   17705:                      web           => "School's web address",
                   17706:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17707:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17708:                  );
                   17709:     return (\@fields,\%titles);
                   17710: }
                   17711: 
1.1075.2.56  raeburn  17712: sub cleanup_html {
                   17713:     my ($incoming) = @_;
                   17714:     my $outgoing;
                   17715:     if ($incoming ne '') {
                   17716:         $outgoing = $incoming;
                   17717:         $outgoing =~ s/;/&#059;/g;
                   17718:         $outgoing =~ s/\#/&#035;/g;
                   17719:         $outgoing =~ s/\&/&#038;/g;
                   17720:         $outgoing =~ s/</&#060;/g;
                   17721:         $outgoing =~ s/>/&#062;/g;
                   17722:         $outgoing =~ s/\(/&#040/g;
                   17723:         $outgoing =~ s/\)/&#041;/g;
                   17724:         $outgoing =~ s/"/&#034;/g;
                   17725:         $outgoing =~ s/'/&#039;/g;
                   17726:         $outgoing =~ s/\$/&#036;/g;
                   17727:         $outgoing =~ s{/}{&#047;}g;
                   17728:         $outgoing =~ s/=/&#061;/g;
                   17729:         $outgoing =~ s/\\/&#092;/g
                   17730:     }
                   17731:     return $outgoing;
                   17732: }
                   17733: 
1.1075.2.74  raeburn  17734: # Checks for critical messages and returns a redirect url if one exists.
                   17735: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 17736:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  17737: sub critical_redirect {
1.1075.2.161.  .1(raebu 17738:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  17739:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   17740:         return ();
                   17741:     }
1.1075.2.74  raeburn  17742:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 17743:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17744:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17745:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17746:21):             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17747:21):             if ($blocked) {
                   17748:21):                 my $checkrole = "cm./$cdom/$cnum";
                   17749:21):                 if ($env{'request.course.sec'} ne '') {
                   17750:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   17751:21):                 }
                   17752:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17753:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17754:21):                     return;
                   17755:21):                 }
                   17756:21):             }
                   17757:21):         }
1.1075.2.74  raeburn  17758:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17759:                                         $env{'user.name'});
                   17760:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17761:         my $redirecturl;
                   17762:         if ($what[0]) {
1.1075.2.158  raeburn  17763:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  17764:                 $redirecturl='/adm/email?critical=display';
                   17765:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17766:                 return (1, $url);
                   17767:             }
                   17768:         }
                   17769:     }
                   17770:     return ();
                   17771: }
                   17772: 
1.1075.2.64  raeburn  17773: # Use:
                   17774: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17775: #
                   17776: ##################################################
                   17777: #          password associated functions         #
                   17778: ##################################################
                   17779: sub des_keys {
                   17780:     # Make a new key for DES encryption.
                   17781:     # Each key has two parts which are returned separately.
                   17782:     # Please note:  Each key must be passed through the &hex function
                   17783:     # before it is output to the web browser.  The hex versions cannot
                   17784:     # be used to decrypt.
                   17785:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17786:                 '8','9','a','b','c','d','e','f');
                   17787:     my $lkey='';
                   17788:     for (0..7) {
                   17789:         $lkey.=$hexstr[rand(15)];
                   17790:     }
                   17791:     my $ukey='';
                   17792:     for (0..7) {
                   17793:         $ukey.=$hexstr[rand(15)];
                   17794:     }
                   17795:     return ($lkey,$ukey);
                   17796: }
                   17797: 
                   17798: sub des_decrypt {
                   17799:     my ($key,$cyphertext) = @_;
                   17800:     my $keybin=pack("H16",$key);
                   17801:     my $cypher;
                   17802:     if ($Crypt::DES::VERSION>=2.03) {
                   17803:         $cypher=new Crypt::DES $keybin;
                   17804:     } else {
                   17805:         $cypher=new DES $keybin;
                   17806:     }
1.1075.2.106  raeburn  17807:     my $plaintext='';
                   17808:     my $cypherlength = length($cyphertext);
                   17809:     my $numchunks = int($cypherlength/32);
                   17810:     for (my $j=0; $j<$numchunks; $j++) {
                   17811:         my $start = $j*32;
                   17812:         my $cypherblock = substr($cyphertext,$start,32);
                   17813:         my $chunk =
                   17814:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17815:         $chunk .=
                   17816:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17817:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17818:         $plaintext .= $chunk;
                   17819:     }
1.1075.2.64  raeburn  17820:     return $plaintext;
                   17821: }
                   17822: 
1.1075.2.161.  .1(raebu 17823:21): sub get_requested_shorturls {
                   17824:21):     my ($cdom,$cnum,$navmap) = @_;
                   17825:21):     return unless (ref($navmap));
                   17826:21):     my ($numnew,$errors);
                   17827:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17828:21):     if (@toshorten) {
                   17829:21):         my (%maps,%resources,%titles);
                   17830:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17831:21):                                                                'shorturls',$cdom,$cnum);
                   17832:21):         if (keys(%resources)) {
                   17833:21):             my %tocreate;
                   17834:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17835:21):                 my $symb = $resources{$item};
                   17836:21):                 if ($symb) {
                   17837:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   17838:21):                 }
                   17839:21):             }
                   17840:21):             if (keys(%tocreate)) {
                   17841:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   17842:21):                                                       \%tocreate);
                   17843:21):             }
                   17844:21):         }
                   17845:21):     }
                   17846:21):     return ($numnew,$errors);
                   17847:21): }
                   17848:21): 
                   17849:21): sub make_short_symbs {
                   17850:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   17851:21):     my ($numnew,@errors);
                   17852:21):     if (ref($tocreateref) eq 'HASH') {
                   17853:21):         my %tocreate = %{$tocreateref};
                   17854:21):         if (keys(%tocreate)) {
                   17855:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17856:21):             my $su = Short::URL->new(no_vowels => 1);
                   17857:21):             my $init = '';
                   17858:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   17859:21):             # get lock on tiny db
                   17860:21):             my $now = time;
                   17861:21):             if ($lockuser eq '') {
                   17862:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   17863:21):             }
                   17864:21):             my $lockhash = {
                   17865:21):                                 "lock\0$now" => $lockuser,
                   17866:21):                             };
                   17867:21):             my $tries = 0;
                   17868:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17869:21):             my ($code,$error);
                   17870:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   17871:21):                 $tries ++;
                   17872:21):                 sleep 1;
                   17873:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17874:21):             }
                   17875:21):             if ($gotlock eq 'ok') {
                   17876:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17877:21):                                        \%addcourse,\%courseonly,\%failed);
                   17878:21):                 if (keys(%failed)) {
                   17879:21):                     my $numfailed = scalar(keys(%failed));
                   17880:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17881:21):                 }
                   17882:21):                 if (keys(%newunique)) {
                   17883:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17884:21):                     if ($putres eq 'ok') {
                   17885:21):                         $numnew = scalar(keys(%newunique));
                   17886:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17887:21):                         unless ($newputres eq 'ok') {
                   17888:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17889:21):                         }
                   17890:21):                     } else {
                   17891:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   17892:21):                     }
                   17893:21):                 }
                   17894:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   17895:21):                 unless ($dellockres eq 'ok') {
                   17896:21):                     push(@errors,&mt('error: could not release lockfile'));
                   17897:21):                 }
                   17898:21):             } else {
                   17899:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   17900:21):             }
                   17901:21):             if (keys(%courseonly)) {
                   17902:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   17903:21):                 if ($result ne 'ok') {
                   17904:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   17905:21):                 }
                   17906:21):             }
                   17907:21):         }
                   17908:21):     }
                   17909:21):     return ($numnew,\@errors);
                   17910:21): }
                   17911:21): 
                   17912:21): sub shorten_symbs {
                   17913:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   17914:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   17915:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   17916:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   17917:21):     my (%possibles,%collisions);
                   17918:21):     foreach my $key (keys(%{$tocreate})) {
                   17919:21):         my $num = String::CRC32::crc32($key);
                   17920:21):         my $tiny = $su->encode($num,$init);
                   17921:21):         if ($tiny) {
                   17922:21):             $possibles{$tiny} = $key;
                   17923:21):         }
                   17924:21):     }
                   17925:21):     if (!$init) {
                   17926:21):         $init = 1;
                   17927:21):     } else {
                   17928:21):         $init ++;
                   17929:21):     }
                   17930:21):     if (keys(%possibles)) {
                   17931:21):         my @posstiny = keys(%possibles);
                   17932:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   17933:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   17934:21):         if (keys(%currtiny)) {
                   17935:21):             foreach my $key (keys(%currtiny)) {
                   17936:21):                 next if ($currtiny{$key} eq '');
                   17937:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   17938:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   17939:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17940:21):                         $courseonly->{$tsymb} = $key;
                   17941:21):                     }
                   17942:21):                 } else {
                   17943:21):                     $collisions{$possibles{$key}} = 1;
                   17944:21):                 }
                   17945:21):                 delete($possibles{$key});
                   17946:21):             }
                   17947:21):         }
                   17948:21):         foreach my $key (keys(%possibles)) {
                   17949:21):             $newunique->{$key} = $possibles{$key};
                   17950:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   17951:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17952:21):                 $addcourse->{$tsymb} = $key;
                   17953:21):             }
                   17954:21):         }
                   17955:21):     }
                   17956:21):     if (keys(%collisions)) {
                   17957:21):         if ($init <5) {
                   17958:21):             if (!$init) {
                   17959:21):                 $init = 1;
                   17960:21):             } else {
                   17961:21):                 $init ++;
                   17962:21):             }
                   17963:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   17964:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   17965:21):         } else {
                   17966:21):             foreach my $key (keys(%collisions)) {
                   17967:21):                 $failed->{$key} = 1;
                   17968:21):                 $failed->{$key} = 1;
                   17969:21):             }
                   17970:21):         }
                   17971:21):     }
                   17972:21):     return $init;
                   17973:21): }
                   17974:21): 
1.1075.2.135  raeburn  17975: sub is_nonframeable {
                   17976:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17977:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17978:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17979: 
                   17980:     $remprotocol = lc($remprotocol);
                   17981:     $remhost = lc($remhost);
                   17982:     my $remport = 80;
                   17983:     if ($remprotocol eq 'https') {
                   17984:         $remport = 443;
                   17985:     }
                   17986:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17987:     if ($cached) {
                   17988:         unless ($nocache) {
                   17989:             if ($result) {
                   17990:                 return 1;
                   17991:             } else {
                   17992:                 return 0;
                   17993:             }
                   17994:         }
                   17995:     }
                   17996:     my $uselink;
                   17997:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  17998:     my $ua = LWP::UserAgent->new;
                   17999:     $ua->timeout(5);
                   18000:     my $response=$ua->request($request);
1.1075.2.135  raeburn  18001:     if ($response->is_success()) {
                   18002:         my $secpolicy = lc($response->header('content-security-policy'));
                   18003:         my $xframeop = lc($response->header('x-frame-options'));
                   18004:         $secpolicy =~ s/^\s+|\s+$//g;
                   18005:         $xframeop =~ s/^\s+|\s+$//g;
                   18006:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   18007:             my $remotehost = $remprotocol.'://'.$remhost;
                   18008:             my ($origin,$protocol,$port);
                   18009:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18010:                 $port = $ENV{'SERVER_PORT'};
                   18011:             } else {
                   18012:                 $port = 80;
                   18013:             }
                   18014:             if ($absolute eq '') {
                   18015:                 $protocol = 'http:';
                   18016:                 if ($port == 443) {
                   18017:                     $protocol = 'https:';
                   18018:                 }
                   18019:                 $origin = $protocol.'//'.lc($hostname);
                   18020:             } else {
                   18021:                 $origin = lc($absolute);
                   18022:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18023:             }
                   18024:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18025:                 my $framepolicy = $1;
                   18026:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18027:                 my @policies = split(/\s+/,$framepolicy);
                   18028:                 if (@policies) {
                   18029:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18030:                         $uselink = 1;
                   18031:                     } else {
                   18032:                         $uselink = 1;
                   18033:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18034:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18035:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18036:                             undef($uselink);
                   18037:                         }
                   18038:                         if ($uselink) {
                   18039:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18040:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18041:                                     undef($uselink);
                   18042:                                 }
                   18043:                             }
                   18044:                         }
                   18045:                         if ($uselink) {
                   18046:                             my @possok;
                   18047:                             if ($ip ne '') {
                   18048:                                 push(@possok,$ip);
                   18049:                             }
                   18050:                             my $hoststr = '';
                   18051:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18052:                                 if ($hoststr eq '') {
                   18053:                                     $hoststr = $part;
                   18054:                                 } else {
                   18055:                                     $hoststr = "$part.$hoststr";
                   18056:                                 }
                   18057:                                 if ($hoststr eq $hostname) {
                   18058:                                     push(@possok,$hostname);
                   18059:                                 } else {
                   18060:                                     push(@possok,"*.$hoststr");
                   18061:                                 }
                   18062:                             }
                   18063:                             if (@possok) {
                   18064:                                 foreach my $poss (@possok) {
                   18065:                                     last if (!$uselink);
                   18066:                                     foreach my $policy (@policies) {
                   18067:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18068:                                             undef($uselink);
                   18069:                                             last;
                   18070:                                         }
                   18071:                                     }
                   18072:                                 }
                   18073:                             }
                   18074:                         }
                   18075:                     }
                   18076:                 }
                   18077:             } elsif ($xframeop ne '') {
                   18078:                 $uselink = 1;
                   18079:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18080:                 if (@policies) {
                   18081:                     unless (grep(/^deny$/,@policies)) {
                   18082:                         if ($origin ne '') {
                   18083:                             if (grep(/^sameorigin$/,@policies)) {
                   18084:                                 if ($remotehost eq $origin) {
                   18085:                                     undef($uselink);
                   18086:                                 }
                   18087:                             }
                   18088:                             if ($uselink) {
                   18089:                                 foreach my $policy (@policies) {
                   18090:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18091:                                         my $allowfrom = $1;
                   18092:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18093:                                             undef($uselink);
                   18094:                                             last;
                   18095:                                         }
                   18096:                                     }
                   18097:                                 }
                   18098:                             }
                   18099:                         }
                   18100:                     }
                   18101:                 }
                   18102:             }
                   18103:         }
                   18104:     }
                   18105:     if ($nocache) {
                   18106:         if ($cached) {
                   18107:             my $devalidate;
                   18108:             if ($uselink && !$result) {
                   18109:                 $devalidate = 1;
                   18110:             } elsif (!$uselink && $result) {
                   18111:                 $devalidate = 1;
                   18112:             }
                   18113:             if ($devalidate) {
                   18114:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18115:             }
                   18116:         }
                   18117:     } else {
                   18118:         if ($uselink) {
                   18119:             $result = 1;
                   18120:         } else {
                   18121:             $result = 0;
                   18122:         }
                   18123:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18124:     }
                   18125:     return $uselink;
                   18126: }
                   18127: 
1.1075.2.161.  .1(raebu 18128:21): sub page_menu {
                   18129:21):     my ($menucolls,$menunum) = @_;
                   18130:21):     my %menu;
                   18131:21):     foreach my $item (split(/;/,$menucolls)) {
                   18132:21):         my ($num,$value) = split(/\%/,$item);
                   18133:21):         if ($num eq $menunum) {
                   18134:21):             my @entries = split(/\&/,$value);
                   18135:21):             foreach my $entry (@entries) {
                   18136:21):                 my ($name,$fields) = split(/=/,$entry);
                   18137:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   18138:21):                     $menu{$name} = $fields;
                   18139:21):                 } else {
                   18140:21):                     my @shown;
                   18141:21):                     if ($fields =~ /,/) {
                   18142:21):                         @shown = split(/,/,$fields);
                   18143:21):                     } else {
                   18144:21):                         @shown = ($fields);
                   18145:21):                     }
                   18146:21):                     if (@shown) {
                   18147:21):                         foreach my $field (@shown) {
                   18148:21):                             next if ($field eq '');
                   18149:21):                             $menu{$field} = 1;
                   18150:21):                         }
                   18151:21):                     }
                   18152:21):                 }
                   18153:21):             }
                   18154:21):         }
                   18155:21):     }
                   18156:21):     return %menu;
                   18157:21): }
                   18158:21): 
1.112     bowersj2 18159: 1;
                   18160: __END__;
1.41      ng       18161: 

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