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

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.  .31(raeb    4:-24): # $Id: loncommon.pm,v 1.1075.2.161.2.30 2024/10/06 20:12:05 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.1075.2.161.  .7(raebu   64:22): use Apache::lonnavmaps();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.161.  .13(raeb   74:-23): use LONCAPA::map();
1.1075.2.135  raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1075.2.102  raeburn    77: use DateTime::Locale;
1.1075.2.94  raeburn    78: use Encode();
1.1075.2.14  raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1075.2.64  raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    85: use File::Copy();
                     86: use File::Path();
1.1075.2.161.  .1(raebu   87:21): use String::CRC32();
                     88:21): use Short::URL();
1.117     www        89: 
1.517     raeburn    90: # ---------------------------------------------- Designs
                     91: use vars qw(%defaultdesign);
                     92: 
1.22      www        93: my $readit;
                     94: 
1.517     raeburn    95: 
1.157     matthew    96: ##
                     97: ## Global Variables
                     98: ##
1.46      matthew    99: 
1.643     foxr      100: 
                    101: # ----------------------------------------------- SSI with retries:
                    102: #
                    103: 
                    104: =pod
                    105: 
1.648     raeburn   106: =head1 Server Side include with retries:
1.643     foxr      107: 
                    108: =over 4
                    109: 
1.648     raeburn   110: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      111: 
                    112: Performs an ssi with some number of retries.  Retries continue either
                    113: until the result is ok or until the retry count supplied by the
                    114: caller is exhausted.  
                    115: 
                    116: Inputs:
1.648     raeburn   117: 
                    118: =over 4
                    119: 
1.643     foxr      120: resource   - Identifies the resource to insert.
1.648     raeburn   121: 
1.643     foxr      122: retries    - Count of the number of retries allowed.
1.648     raeburn   123: 
1.643     foxr      124: form       - Hash that identifies the rendering options.
                    125: 
1.648     raeburn   126: =back
                    127: 
                    128: Returns:
                    129: 
                    130: =over 4
                    131: 
1.643     foxr      132: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   133: 
1.643     foxr      134: response   - The response from the last attempt (which may or may not have been successful.
                    135: 
1.648     raeburn   136: =back
                    137: 
                    138: =back
                    139: 
1.643     foxr      140: =cut
                    141: 
                    142: sub ssi_with_retries {
                    143:     my ($resource, $retries, %form) = @_;
                    144: 
                    145: 
                    146:     my $ok = 0;			# True if we got a good response.
                    147:     my $content;
                    148:     my $response;
                    149: 
                    150:     # Try to get the ssi done. within the retries count:
                    151: 
                    152:     do {
                    153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    154: 	$ok      = $response->is_success;
1.650     www       155:         if (!$ok) {
                    156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    157:         }
1.643     foxr      158: 	$retries--;
                    159:     } while (!$ok && ($retries > 0));
                    160: 
                    161:     if (!$ok) {
                    162: 	$content = '';		# On error return an empty content.
                    163:     }
                    164:     return ($content, $response);
                    165: 
                    166: }
                    167: 
                    168: 
                    169: 
1.20      www       170: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  171: my %language;
1.124     www       172: my %supported_language;
1.1048    foxr      173: my %latex_language;		# For choosing hyphenation in <transl..>
                    174: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  175: my %cprtag;
1.192     taceyjo1  176: my %scprtag;
1.351     www       177: my %fe; my %fd; my %fm;
1.41      ng        178: my %category_extensions;
1.12      harris41  179: 
1.46      matthew   180: # ---------------------------------------------- Thesaurus variables
1.144     matthew   181: #
                    182: # %Keywords:
                    183: #      A hash used by &keyword to determine if a word is considered a keyword.
                    184: # $thesaurus_db_file 
                    185: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   186: 
                    187: my %Keywords;
                    188: my $thesaurus_db_file;
                    189: 
1.144     matthew   190: #
                    191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    192: # thesaurus.tab, and filecategories.tab.
                    193: #
1.18      www       194: BEGIN {
1.46      matthew   195:     # Variable initialization
                    196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    197:     #
1.22      www       198:     unless ($readit) {
1.12      harris41  199: # ------------------------------------------------------------------- languages
                    200:     {
1.158     raeburn   201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    202:                                    '/language.tab';
1.1075.2.128  raeburn   203:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  204:             while (my $line = <$fh>) {
                    205:                 next if ($line=~/^\#/);
                    206:                 chomp($line);
1.1048    foxr      207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   208:                 $language{$key}=$val.' - '.$enc;
                    209:                 if ($sup) {
                    210:                     $supported_language{$key}=$sup;
                    211:                 }
1.1048    foxr      212: 		if ($latex) {
                    213: 		    $latex_language_bykey{$key} = $latex;
                    214: 		    $latex_language{$two} = $latex;
                    215: 		}
1.158     raeburn   216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
                    220: # ------------------------------------------------------------------ copyrights
                    221:     {
1.158     raeburn   222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/copyright.tab';
1.1075.2.128  raeburn   224:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line=~/^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   229:                 $cprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
1.12      harris41  233:     }
1.351     www       234: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  235:     {
                    236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    237:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  239:             while (my $line = <$fh>) {
                    240:                 next if ($line =~ /^\#/);
                    241:                 chomp($line);
                    242:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  243:                 $scprtag{$key}=$val;
                    244:             }
                    245:             close($fh);
                    246:         }
                    247:     }
1.63      www       248: 
1.517     raeburn   249: # -------------------------------------------------------------- default domain designs
1.63      www       250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   251:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   252:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   253:         while (my $line = <$fh>) {
                    254:             next if ($line =~ /^\#/);
                    255:             chomp($line);
                    256:             my ($key,$val)=(split(/\=/,$line));
                    257:             if ($val) { $defaultdesign{$key}=$val; }
                    258:         }
                    259:         close($fh);
1.63      www       260:     }
                    261: 
1.15      harris41  262: # ------------------------------------------------------------- file categories
                    263:     {
1.158     raeburn   264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    265:                                   '/filecategories.tab';
1.1075.2.128  raeburn   266:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  267: 	    while (my $line = <$fh>) {
                    268: 		next if ($line =~ /^\#/);
                    269: 		chomp($line);
                    270:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   271:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   272:             }
                    273:             close($fh);
                    274:         }
                    275: 
1.15      harris41  276:     }
1.12      harris41  277: # ------------------------------------------------------------------ file types
                    278:     {
1.158     raeburn   279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    280:                '/filetypes.tab';
1.1075.2.128  raeburn   281:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  282:             while (my $line = <$fh>) {
                    283: 		next if ($line =~ /^\#/);
                    284: 		chomp($line);
                    285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   286:                 if ($descr ne '') {
                    287:                     $fe{$ending}=lc($emb);
                    288:                     $fd{$ending}=$descr;
1.351     www       289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   290:                 }
                    291:             }
                    292:             close($fh);
                    293:         }
1.12      harris41  294:     }
1.22      www       295:     &Apache::lonnet::logthis(
1.705     tempelho  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       297:     $readit=1;
1.46      matthew   298:     }  # end of unless($readit) 
1.32      matthew   299:     
                    300: }
1.112     bowersj2  301: 
1.42      matthew   302: ###############################################################
                    303: ##           HTML and Javascript Helper Functions            ##
                    304: ###############################################################
                    305: 
                    306: =pod 
                    307: 
1.112     bowersj2  308: =head1 HTML and Javascript Functions
1.42      matthew   309: 
1.112     bowersj2  310: =over 4
                    311: 
1.648     raeburn   312: =item * &browser_and_searcher_javascript()
1.112     bowersj2  313: 
                    314: X<browsing, javascript>X<searching, javascript>Returns a string
                    315: containing javascript with two functions, C<openbrowser> and
                    316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    317: tags.
1.42      matthew   318: 
1.648     raeburn   319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   320: 
                    321: inputs: formname, elementname, only, omit
                    322: 
                    323: formname and elementname indicate the name of the html form and name of
                    324: the element that the results of the browsing selection are to be placed in. 
                    325: 
                    326: Specifying 'only' will restrict the browser to displaying only files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
                    329: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       330: with the given extension.  Can be a comma separated list.
1.42      matthew   331: 
1.648     raeburn   332: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   333: 
                    334: Inputs: formname, elementname
                    335: 
                    336: formname and elementname specify the name of the html form and the name
                    337: of the element the selection from the search results will be placed in.
1.542     raeburn   338: 
1.42      matthew   339: =cut
                    340: 
                    341: sub browser_and_searcher_javascript {
1.199     albertel  342:     my ($mode)=@_;
                    343:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  344:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   345:     return <<END;
1.219     albertel  346: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   347:     var editbrowser = null;
1.135     albertel  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       349:         var url = '$resurl/?';
1.42      matthew   350:         if (editbrowser == null) {
                    351:             url += 'launch=1&';
                    352:         }
                    353:         url += 'catalogmode=interactive&';
1.199     albertel  354:         url += 'mode=$mode&';
1.611     albertel  355:         url += 'inhibitmenu=yes&';
1.42      matthew   356:         url += 'form=' + formname + '&';
                    357:         if (only != null) {
                    358:             url += 'only=' + only + '&';
1.217     albertel  359:         } else {
                    360:             url += 'only=&';
                    361: 	}
1.42      matthew   362:         if (omit != null) {
                    363:             url += 'omit=' + omit + '&';
1.217     albertel  364:         } else {
                    365:             url += 'omit=&';
                    366: 	}
1.135     albertel  367:         if (titleelement != null) {
                    368:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  369:         } else {
                    370: 	    url += 'titleelement=&';
                    371: 	}
1.42      matthew   372:         url += 'element=' + elementname + '';
                    373:         var title = 'Browser';
1.435     albertel  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   375:         options += ',width=700,height=600';
                    376:         editbrowser = open(url,title,options,'1');
                    377:         editbrowser.focus();
                    378:     }
                    379:     var editsearcher;
1.135     albertel  380:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   381:         var url = '/adm/searchcat?';
                    382:         if (editsearcher == null) {
                    383:             url += 'launch=1&';
                    384:         }
                    385:         url += 'catalogmode=interactive&';
1.199     albertel  386:         url += 'mode=$mode&';
1.42      matthew   387:         url += 'form=' + formname + '&';
1.135     albertel  388:         if (titleelement != null) {
                    389:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  390:         } else {
                    391: 	    url += 'titleelement=&';
                    392: 	}
1.42      matthew   393:         url += 'element=' + elementname + '';
                    394:         var title = 'Search';
1.435     albertel  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   396:         options += ',width=700,height=600';
                    397:         editsearcher = open(url,title,options,'1');
                    398:         editsearcher.focus();
                    399:     }
1.219     albertel  400: // END LON-CAPA Internal -->
1.42      matthew   401: END
1.170     www       402: }
                    403: 
                    404: sub lastresurl {
1.258     albertel  405:     if ($env{'environment.lastresurl'}) {
                    406: 	return $env{'environment.lastresurl'}
1.170     www       407:     } else {
                    408: 	return '/res';
                    409:     }
                    410: }
                    411: 
                    412: sub storeresurl {
                    413:     my $resurl=&Apache::lonnet::clutter(shift);
                    414:     unless ($resurl=~/^\/res/) { return 0; }
                    415:     $resurl=~s/\/$//;
                    416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       418:     return 1;
1.42      matthew   419: }
                    420: 
1.74      www       421: sub studentbrowser_javascript {
1.111     www       422:    unless (
1.258     albertel  423:             (($env{'request.course.id'}) && 
1.302     albertel  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    426: 					  '/'.$env{'request.course.sec'})
                    427: 	      ))
1.258     albertel  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       429:           ) { return ''; }  
1.74      www       430:    return (<<'ENDSTDBRW');
1.776     bisitz    431: <script type="text/javascript" language="Javascript">
1.824     bisitz    432: // <![CDATA[
1.74      www       433:     var stdeditbrowser;
1.1075.2.161.  .20(raeb  434:-23):     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       435:         var url = '/adm/pickstudent?';
                    436:         var filter;
1.558     albertel  437: 	if (!ignorefilter) {
                    438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    439: 	}
1.74      www       440:         if (filter != null) {
                    441:            if (filter != '') {
                    442:                url += 'filter='+filter+'&';
                    443: 	   }
                    444:         }
                    445:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       446:                                     '&udomelement='+udom+
                    447:                                     '&clicker='+clicker;
1.111     www       448: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   449:         if (courseadv == 'condition') {
                    450:             if (document.getElementById('courseadv')) {
                    451:                 courseadv = document.getElementById('courseadv').value;
                    452:             }
                    453:         }
                    454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1075.2.161.  .20(raeb  455:-23):         if (uident !== '') { url+="&identelement="+uident; }
1.102     www       456:         var title = 'Student_Browser';
1.74      www       457:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    458:         options += ',width=700,height=600';
                    459:         stdeditbrowser = open(url,title,options,'1');
                    460:         stdeditbrowser.focus();
                    461:     }
1.824     bisitz    462: // ]]>
1.74      www       463: </script>
                    464: ENDSTDBRW
                    465: }
1.42      matthew   466: 
1.1003    www       467: sub resourcebrowser_javascript {
                    468:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       469:    return (<<'ENDRESBRW');
1.1003    www       470: <script type="text/javascript" language="Javascript">
                    471: // <![CDATA[
                    472:     var reseditbrowser;
1.1004    www       473:     function openresbrowser(formname,reslink) {
1.1005    www       474:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       475:         var title = 'Resource_Browser';
                    476:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       477:         options += ',width=700,height=500';
1.1004    www       478:         reseditbrowser = open(url,title,options,'1');
                    479:         reseditbrowser.focus();
1.1003    www       480:     }
                    481: // ]]>
                    482: </script>
1.1004    www       483: ENDRESBRW
1.1003    www       484: }
                    485: 
1.74      www       486: sub selectstudent_link {
1.1075.2.161.  .20(raeb  487:-23):    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       488:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    490:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  491:    if ($env{'request.course.id'}) {  
1.302     albertel  492:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    493: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    494: 					'/'.$env{'request.course.sec'})) {
1.111     www       495: 	   return '';
                    496:        }
1.999     www       497:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   498:        if ($courseadv eq 'only') {
                    499:            $callargs .= ",'',1,'$courseadv'";
                    500:        } elsif ($courseadv eq 'none') {
                    501:            $callargs .= ",'','','$courseadv'";
                    502:        } elsif ($courseadv eq 'condition') {
                    503:            $callargs .= ",'','','$courseadv'";
1.1075.2.161.  .20(raeb  504:-23):        } elsif ($identelem ne '') {
                    505:-23):            $callargs .= ",'','',''";
                    506:-23):        }
                    507:-23):        if ($identelem ne '') {
                    508:-23):            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   509:        }
                    510:        return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    512:               &mt('Select User').'</a></span>';
1.74      www       513:    }
1.258     albertel  514:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       515:        $callargs .= ",'',1"; 
1.793     raeburn   516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.111     www       519:    }
                    520:    return '';
1.91      www       521: }
                    522: 
1.1004    www       523: sub selectresource_link {
                    524:    my ($form,$reslink,$arg)=@_;
                    525:    
                    526:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    527:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    528:    unless ($env{'request.course.id'}) { return $arg; }
                    529:    return '<span class="LC_nobreak">'.
                    530:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    531:               $arg.'</a></span>';
                    532: }
                    533: 
                    534: 
                    535: 
1.653     raeburn   536: sub authorbrowser_javascript {
                    537:     return <<"ENDAUTHORBRW";
1.776     bisitz    538: <script type="text/javascript" language="JavaScript">
1.824     bisitz    539: // <![CDATA[
1.653     raeburn   540: var stdeditbrowser;
                    541: 
                    542: function openauthorbrowser(formname,udom) {
                    543:     var url = '/adm/pickauthor?';
                    544:     url += 'form='+formname+'&roledom='+udom;
                    545:     var title = 'Author_Browser';
                    546:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    547:     options += ',width=700,height=600';
                    548:     stdeditbrowser = open(url,title,options,'1');
                    549:     stdeditbrowser.focus();
                    550: }
                    551: 
1.824     bisitz    552: // ]]>
1.653     raeburn   553: </script>
                    554: ENDAUTHORBRW
                    555: }
                    556: 
1.91      www       557: sub coursebrowser_javascript {
1.1075.2.31  raeburn   558:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   559:         $credits_element,$instcode) = @_;
1.932     raeburn   560:     my $wintitle = 'Course_Browser';
1.931     raeburn   561:     if ($crstype eq 'Community') {
1.932     raeburn   562:         $wintitle = 'Community_Browser';
1.909     raeburn   563:     }
1.876     raeburn   564:     my $id_functions = &javascript_index_functions();
                    565:     my $output = '
1.776     bisitz    566: <script type="text/javascript" language="JavaScript">
1.824     bisitz    567: // <![CDATA[
1.468     raeburn   568:     var stdeditbrowser;'."\n";
1.876     raeburn   569: 
                    570:     $output .= <<"ENDSTDBRW";
1.909     raeburn   571:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       572:         var url = '/adm/pickcourse?';
1.895     raeburn   573:         var formid = getFormIdByName(formname);
1.876     raeburn   574:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  575:         if (domainfilter != null) {
                    576:            if (domainfilter != '') {
                    577:                url += 'domainfilter='+domainfilter+'&';
                    578: 	   }
                    579:         }
1.91      www       580:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  581: 	                            '&cdomelement='+udom+
                    582:                                     '&cnameelement='+desc;
1.468     raeburn   583:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   584:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   585:                 url += '&roleelement='+extra_element;
                    586:                 if (domainfilter == null || domainfilter == '') {
                    587:                     url += '&domainfilter='+extra_element;
                    588:                 }
1.234     raeburn   589:             }
1.468     raeburn   590:             else {
                    591:                 if (formname == 'portform') {
                    592:                     url += '&setroles='+extra_element;
1.800     raeburn   593:                 } else {
                    594:                     if (formname == 'rules') {
                    595:                         url += '&fixeddom='+extra_element; 
                    596:                     }
1.468     raeburn   597:                 }
                    598:             }     
1.230     raeburn   599:         }
1.909     raeburn   600:         if (type != null && type != '') {
                    601:             url += '&type='+type;
                    602:         }
                    603:         if (type_elem != null && type_elem != '') {
                    604:             url += '&typeelement='+type_elem;
                    605:         }
1.872     raeburn   606:         if (formname == 'ccrs') {
                    607:             var ownername = document.forms[formid].ccuname.value;
                    608:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   609:             url += '&cloner='+ownername+':'+ownerdom;
                    610:             if (type == 'Course') {
                    611:                 url += '&crscode='+document.forms[formid].crscode.value;
                    612:             }
1.1075.2.95  raeburn   613:         }
                    614:         if (formname == 'requestcrs') {
                    615:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   616:         }
1.293     raeburn   617:         if (multflag !=null && multflag != '') {
                    618:             url += '&multiple='+multflag;
                    619:         }
1.909     raeburn   620:         var title = '$wintitle';
1.91      www       621:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    622:         options += ',width=700,height=600';
                    623:         stdeditbrowser = open(url,title,options,'1');
                    624:         stdeditbrowser.focus();
                    625:     }
1.876     raeburn   626: $id_functions
                    627: ENDSTDBRW
1.1075.2.31  raeburn   628:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    629:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    630:                                       $credits_element);
1.876     raeburn   631:     }
                    632:     $output .= '
                    633: // ]]>
                    634: </script>';
                    635:     return $output;
                    636: }
                    637: 
                    638: sub javascript_index_functions {
                    639:     return <<"ENDJS";
                    640: 
                    641: function getFormIdByName(formname) {
                    642:     for (var i=0;i<document.forms.length;i++) {
                    643:         if (document.forms[i].name == formname) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
                    649: 
                    650: function getIndexByName(formid,item) {
                    651:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    652:         if (document.forms[formid].elements[i].name == item) {
                    653:             return i;
                    654:         }
                    655:     }
                    656:     return -1;
                    657: }
1.468     raeburn   658: 
1.876     raeburn   659: function getDomainFromSelectbox(formname,udom) {
                    660:     var userdom;
                    661:     var formid = getFormIdByName(formname);
                    662:     if (formid > -1) {
                    663:         var domid = getIndexByName(formid,udom);
                    664:         if (domid > -1) {
                    665:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    666:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    667:             }
                    668:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    669:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   670:             }
                    671:         }
                    672:     }
1.876     raeburn   673:     return userdom;
                    674: }
                    675: 
                    676: ENDJS
1.468     raeburn   677: 
1.876     raeburn   678: }
                    679: 
1.1017    raeburn   680: sub javascript_array_indexof {
1.1018    raeburn   681:     return <<ENDJS;
1.1017    raeburn   682: <script type="text/javascript" language="JavaScript">
                    683: // <![CDATA[
                    684: 
                    685: if (!Array.prototype.indexOf) {
                    686:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    687:         "use strict";
                    688:         if (this === void 0 || this === null) {
                    689:             throw new TypeError();
                    690:         }
                    691:         var t = Object(this);
                    692:         var len = t.length >>> 0;
                    693:         if (len === 0) {
                    694:             return -1;
                    695:         }
                    696:         var n = 0;
                    697:         if (arguments.length > 0) {
                    698:             n = Number(arguments[1]);
                    699:             if (n !== n) { // shortcut for verifying if it's NaN
                    700:                 n = 0;
                    701:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    702:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    703:             }
                    704:         }
                    705:         if (n >= len) {
                    706:             return -1;
                    707:         }
                    708:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    709:         for (; k < len; k++) {
                    710:             if (k in t && t[k] === searchElement) {
                    711:                 return k;
                    712:             }
                    713:         }
                    714:         return -1;
                    715:     }
                    716: }
                    717: 
                    718: // ]]>
                    719: </script>
                    720: 
                    721: ENDJS
                    722: 
                    723: }
                    724: 
1.876     raeburn   725: sub userbrowser_javascript {
                    726:     my $id_functions = &javascript_index_functions();
                    727:     return <<"ENDUSERBRW";
                    728: 
1.888     raeburn   729: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   730:     var url = '/adm/pickuser?';
                    731:     var userdom = getDomainFromSelectbox(formname,udom);
                    732:     if (userdom != null) {
                    733:        if (userdom != '') {
                    734:            url += 'srchdom='+userdom+'&';
                    735:        }
                    736:     }
                    737:     url += 'form=' + formname + '&unameelement='+uname+
                    738:                                 '&udomelement='+udom+
                    739:                                 '&ulastelement='+ulast+
                    740:                                 '&ufirstelement='+ufirst+
                    741:                                 '&uemailelement='+uemail+
1.881     raeburn   742:                                 '&hideudomelement='+hideudom+
                    743:                                 '&coursedom='+crsdom;
1.888     raeburn   744:     if ((caller != null) && (caller != undefined)) {
                    745:         url += '&caller='+caller;
                    746:     }
1.876     raeburn   747:     var title = 'User_Browser';
                    748:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    749:     options += ',width=700,height=600';
                    750:     var stdeditbrowser = open(url,title,options,'1');
                    751:     stdeditbrowser.focus();
                    752: }
                    753: 
1.888     raeburn   754: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   755:     var formid = getFormIdByName(formname);
                    756:     if (formid > -1) {
1.888     raeburn   757:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   758:         var domid = getIndexByName(formid,udom);
                    759:         var hidedomid = getIndexByName(formid,origdom);
                    760:         if (hidedomid > -1) {
                    761:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   762:             var unameval = document.forms[formid].elements[unameid].value;
                    763:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    764:                 if (domid > -1) {
                    765:                     var slct = document.forms[formid].elements[domid];
                    766:                     if (slct.type == 'select-one') {
                    767:                         var i;
                    768:                         for (i=0;i<slct.length;i++) {
                    769:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    770:                         }
                    771:                     }
                    772:                     if (slct.type == 'hidden') {
                    773:                         slct.value = fixeddom;
1.876     raeburn   774:                     }
                    775:                 }
1.468     raeburn   776:             }
                    777:         }
                    778:     }
1.876     raeburn   779:     return;
                    780: }
                    781: 
                    782: $id_functions
                    783: ENDUSERBRW
1.468     raeburn   784: }
                    785: 
                    786: sub setsec_javascript {
1.1075.2.31  raeburn   787:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   788:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    789:         $communityrolestr);
                    790:     if ($role_element ne '') {
                    791:         my @allroles = ('st','ta','ep','in','ad');
                    792:         foreach my $crstype ('Course','Community') {
                    793:             if ($crstype eq 'Community') {
                    794:                 foreach my $role (@allroles) {
                    795:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    796:                 }
                    797:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    798:             } else {
                    799:                 foreach my $role (@allroles) {
                    800:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    801:                 }
                    802:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    803:             }
                    804:         }
                    805:         $rolestr = '"'.join('","',@allroles).'"';
                    806:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    807:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    808:     }
1.468     raeburn   809:     my $setsections = qq|
                    810: function setSect(sectionlist) {
1.629     raeburn   811:     var sectionsArray = new Array();
                    812:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    813:         sectionsArray = sectionlist.split(",");
                    814:     }
1.468     raeburn   815:     var numSections = sectionsArray.length;
                    816:     document.$formname.$sec_element.length = 0;
                    817:     if (numSections == 0) {
                    818:         document.$formname.$sec_element.multiple=false;
                    819:         document.$formname.$sec_element.size=1;
                    820:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    821:     } else {
                    822:         if (numSections == 1) {
                    823:             document.$formname.$sec_element.multiple=false;
                    824:             document.$formname.$sec_element.size=1;
                    825:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    826:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    827:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    828:         } else {
                    829:             for (var i=0; i<numSections; i++) {
                    830:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    831:             }
                    832:             document.$formname.$sec_element.multiple=true
                    833:             if (numSections < 3) {
                    834:                 document.$formname.$sec_element.size=numSections;
                    835:             } else {
                    836:                 document.$formname.$sec_element.size=3;
                    837:             }
                    838:             document.$formname.$sec_element.options[0].selected = false
                    839:         }
                    840:     }
1.91      www       841: }
1.905     raeburn   842: 
                    843: function setRole(crstype) {
1.468     raeburn   844: |;
1.905     raeburn   845:     if ($role_element eq '') {
                    846:         $setsections .= '    return;
                    847: }
                    848: ';
                    849:     } else {
                    850:         $setsections .= qq|
                    851:     var elementLength = document.$formname.$role_element.length;
                    852:     var allroles = Array($rolestr);
                    853:     var courserolenames = Array($courserolestr);
                    854:     var communityrolenames = Array($communityrolestr);
                    855:     if (elementLength != undefined) {
                    856:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    857:             if (crstype == 'Course') {
                    858:                 return;
                    859:             } else {
                    860:                 allroles[5] = 'co';
                    861:                 for (var i=0; i<6; i++) {
                    862:                     document.$formname.$role_element.options[i].value = allroles[i];
                    863:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    864:                 }
                    865:             }
                    866:         } else {
                    867:             if (crstype == 'Community') {
                    868:                 return;
                    869:             } else {
                    870:                 allroles[5] = 'cc';
                    871:                 for (var i=0; i<6; i++) {
                    872:                     document.$formname.$role_element.options[i].value = allroles[i];
                    873:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    874:                 }
                    875:             }
                    876:         }
                    877:     }
                    878:     return;
                    879: }
                    880: |;
                    881:     }
1.1075.2.31  raeburn   882:     if ($credits_element) {
                    883:         $setsections .= qq|
                    884: function setCredits(defaultcredits) {
                    885:     document.$formname.$credits_element.value = defaultcredits;
                    886:     return;
                    887: }
                    888: |;
                    889:     }
1.468     raeburn   890:     return $setsections;
                    891: }
                    892: 
1.91      www       893: sub selectcourse_link {
1.909     raeburn   894:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    895:        $typeelement) = @_;
                    896:    my $type = $selecttype;
1.871     raeburn   897:    my $linktext = &mt('Select Course');
                    898:    if ($selecttype eq 'Community') {
1.909     raeburn   899:        $linktext = &mt('Select Community');
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   935:             if (!field[i].disabled) {
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1075.2.14  raeburn   940:         if (!field.disabled) {
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1075.2.161.  .10(raeb  960:-22):    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    961:-22):    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1075.2.115  raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1075.2.102  raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1075.2.94  raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1015:                 push(@possibles,$id);
1.687     raeburn  1016:             }
                   1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1075.2.115  raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1075.2.32  raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1075.2.32  raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.648     raeburn  1052: =item * &linked_select_forms(...)
1.36      matthew  1053: 
                   1054: linked_select_forms returns a string containing a <script></script> block
                   1055: and html for two <select> menus.  The select menus will be linked in that
                   1056: changing the value of the first menu will result in new values being placed
                   1057: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1058: order unless a defined order is provided.
1.36      matthew  1059: 
                   1060: linked_select_forms takes the following ordered inputs:
                   1061: 
                   1062: =over 4
                   1063: 
1.112     bowersj2 1064: =item * $formname, the name of the <form> tag
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $firstdefault, the default value for the first menu
1.36      matthew  1069: 
1.112     bowersj2 1070: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1071: 
1.112     bowersj2 1072: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1073: 
1.112     bowersj2 1074: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1075: 
1.609     raeburn  1076: =item * $menuorder, the order of values in the first menu
                   1077: 
1.1075.2.31  raeburn  1078: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1079:         event for the first <select> tag
                   1080: 
                   1081: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1082:         event for the second <select> tag
                   1083: 
1.41      ng       1084: =back 
                   1085: 
1.36      matthew  1086: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1087: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1088: values for the first select menu.  The text that coincides with the 
1.41      ng       1089: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1090: and text for the second menu are given in the hash pointed to by 
                   1091: $menu{$choice1}->{'select2'}.  
                   1092: 
1.112     bowersj2 1093:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1094:                        default => "B3",
                   1095:                        select2 => { 
                   1096:                            B1 => "Choice B1",
                   1097:                            B2 => "Choice B2",
                   1098:                            B3 => "Choice B3",
                   1099:                            B4 => "Choice B4"
1.609     raeburn  1100:                            },
                   1101:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1102:                    },
                   1103:                A2 => { text =>"Choice A2" ,
                   1104:                        default => "C2",
                   1105:                        select2 => { 
                   1106:                            C1 => "Choice C1",
                   1107:                            C2 => "Choice C2",
                   1108:                            C3 => "Choice C3"
1.609     raeburn  1109:                            },
                   1110:                        order => ['C2','C1','C3'],
1.112     bowersj2 1111:                    },
                   1112:                A3 => { text =>"Choice A3" ,
                   1113:                        default => "D6",
                   1114:                        select2 => { 
                   1115:                            D1 => "Choice D1",
                   1116:                            D2 => "Choice D2",
                   1117:                            D3 => "Choice D3",
                   1118:                            D4 => "Choice D4",
                   1119:                            D5 => "Choice D5",
                   1120:                            D6 => "Choice D6",
                   1121:                            D7 => "Choice D7"
1.609     raeburn  1122:                            },
                   1123:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1124:                    }
                   1125:                );
1.36      matthew  1126: 
                   1127: =cut
                   1128: 
                   1129: sub linked_select_forms {
                   1130:     my ($formname,
                   1131:         $middletext,
                   1132:         $firstdefault,
                   1133:         $firstselectname,
                   1134:         $secondselectname, 
1.609     raeburn  1135:         $hashref,
                   1136:         $menuorder,
1.1075.2.31  raeburn  1137:         $onchangefirst,
                   1138:         $onchangesecond
1.36      matthew  1139:         ) = @_;
                   1140:     my $second = "document.$formname.$secondselectname";
                   1141:     my $first = "document.$formname.$firstselectname";
                   1142:     # output the javascript to do the changing
                   1143:     my $result = '';
1.776     bisitz   1144:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1145:     $result.="// <![CDATA[\n";
1.36      matthew  1146:     $result.="var select2data = new Object();\n";
                   1147:     $" = '","';
                   1148:     my $debug = '';
                   1149:     foreach my $s1 (sort(keys(%$hashref))) {
                   1150:         $result.="select2data.d_$s1 = new Object();\n";        
                   1151:         $result.="select2data.d_$s1.def = new String('".
                   1152:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1153:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1154:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1155:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1156:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1157:         }
1.36      matthew  1158:         $result.="\"@s2values\");\n";
                   1159:         $result.="select2data.d_$s1.texts = new Array(";        
                   1160:         my @s2texts;
                   1161:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1162:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1163:         }
                   1164:         $result.="\"@s2texts\");\n";
                   1165:     }
                   1166:     $"=' ';
                   1167:     $result.= <<"END";
                   1168: 
                   1169: function select1_changed() {
                   1170:     // Determine new choice
                   1171:     var newvalue = "d_" + $first.value;
                   1172:     // update select2
                   1173:     var values     = select2data[newvalue].values;
                   1174:     var texts      = select2data[newvalue].texts;
                   1175:     var select2def = select2data[newvalue].def;
                   1176:     var i;
                   1177:     // out with the old
                   1178:     for (i = 0; i < $second.options.length; i++) {
                   1179:         $second.options[i] = null;
                   1180:     }
                   1181:     // in with the nuclear
                   1182:     for (i=0;i<values.length; i++) {
                   1183:         $second.options[i] = new Option(values[i]);
1.143     matthew  1184:         $second.options[i].value = values[i];
1.36      matthew  1185:         $second.options[i].text = texts[i];
                   1186:         if (values[i] == select2def) {
                   1187:             $second.options[i].selected = true;
                   1188:         }
                   1189:     }
                   1190: }
1.824     bisitz   1191: // ]]>
1.36      matthew  1192: </script>
                   1193: END
                   1194:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1195:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1196:     my @order = sort(keys(%{$hashref}));
                   1197:     if (ref($menuorder) eq 'ARRAY') {
                   1198:         @order = @{$menuorder};
                   1199:     }
                   1200:     foreach my $value (@order) {
1.36      matthew  1201:         $result.="    <option value=\"$value\" ";
1.253     albertel 1202:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1203:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1204:     }
                   1205:     $result .= "</select>\n";
                   1206:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1207:     $result .= $middletext;
1.1075.2.31  raeburn  1208:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1209:     if ($onchangesecond) {
                   1210:         $result .= ' onchange="'.$onchangesecond.'"';
                   1211:     }
                   1212:     $result .= ">\n";
1.36      matthew  1213:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1214:     
                   1215:     my @secondorder = sort(keys(%select2));
                   1216:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1217:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1218:     }
                   1219:     foreach my $value (@secondorder) {
1.36      matthew  1220:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1221:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1222:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1223:     }
                   1224:     $result .= "</select>\n";
                   1225:     #    return $debug;
                   1226:     return $result;
                   1227: }   #  end of sub linked_select_forms {
                   1228: 
1.45      matthew  1229: =pod
1.44      bowersj2 1230: 
1.1075.2.161.  .6(raebu 1231:22): =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1232: 
1.112     bowersj2 1233: Returns a string corresponding to an HTML link to the given help
                   1234: $topic, where $topic corresponds to the name of a .tex file in
                   1235: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1236: spaces. 
                   1237: 
                   1238: $text will optionally be linked to the same topic, allowing you to
                   1239: link text in addition to the graphic. If you do not want to link
                   1240: text, but wish to specify one of the later parameters, pass an
                   1241: empty string. 
                   1242: 
                   1243: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1244: the link will not open a new window. If false, the link will open
                   1245: a new window using Javascript. (Default is false.) 
                   1246: 
                   1247: $width and $height are optional numerical parameters that will
                   1248: override the width and height of the popped up window, which may
1.973     raeburn  1249: be useful for certain help topics with big pictures included.
                   1250: 
                   1251: $imgid is the id of the img tag used for the help icon. This may be
                   1252: used in a javascript call to switch the image src.  See 
                   1253: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1254: 
1.1075.2.161.  .6(raebu 1255:22): $links_target will optionally be set to a target (_top, _parent or _self).
                   1256:22): 
1.44      bowersj2 1257: =cut
                   1258: 
                   1259: sub help_open_topic {
1.1075.2.161.  .6(raebu 1260:22):     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1261:     $text = "" if (not defined $text);
1.44      bowersj2 1262:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1263:     $width = 500 if (not defined $width);
1.44      bowersj2 1264:     $height = 400 if (not defined $height);
                   1265:     my $filename = $topic;
                   1266:     $filename =~ s/ /_/g;
                   1267: 
1.48      bowersj2 1268:     my $template = "";
                   1269:     my $link;
1.572     banghart 1270:     
1.159     www      1271:     $topic=~s/\W/\_/g;
1.44      bowersj2 1272: 
1.572     banghart 1273:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1274:         if ($env{'browser.mobile'}) {
                   1275: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1276:         } else {
                   1277:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1278:         }
1.1037    www      1279:     } elsif ($stayOnPage eq 'popup') {
                   1280:         $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 1281:     } else {
1.48      bowersj2 1282: 	$link = "/adm/help/${filename}.hlp";
                   1283:     }
                   1284: 
                   1285:     # Add the text
1.1075.2.161.  .6(raebu 1286:22):     my $target = ' target="_top"';
                   1287:22):     if ($links_target) {
                   1288:22):         $target = ' target="'.$links_target.'"';
          .17(raeb 1289:-23):     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1290:-23):              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
          .6(raebu 1291:22):         $target = '';
                   1292:22):     }
1.755     neumanie 1293:     if ($text ne "") {	
1.763     bisitz   1294: 	$template.='<span class="LC_help_open_topic">'
1.1075.2.161.  .6(raebu 1295:22):                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1296:                   .$text.'</a>';
1.48      bowersj2 1297:     }
                   1298: 
1.763     bisitz   1299:     # (Always) Add the graphic
1.179     matthew  1300:     my $title = &mt('Online Help');
1.667     raeburn  1301:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1302:     if ($imgid ne '') {
                   1303:         $imgid = ' id="'.$imgid.'"';
                   1304:     }
1.1075.2.161.  .6(raebu 1305:22):     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1306:               .'<img src="'.$helpicon.'" border="0"'
                   1307:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1308:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1309:               .' /></a>';
                   1310:     if ($text ne "") {	
                   1311:         $template.='</span>';
                   1312:     }
1.44      bowersj2 1313:     return $template;
                   1314: 
1.106     bowersj2 1315: }
                   1316: 
                   1317: # This is a quicky function for Latex cheatsheet editing, since it 
                   1318: # appears in at least four places
                   1319: sub helpLatexCheatsheet {
1.1037    www      1320:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1321:     my $out;
1.106     bowersj2 1322:     my $addOther = '';
1.732     raeburn  1323:     if ($topic) {
1.1037    www      1324: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1325:     }
                   1326:     $out = '<span>' # Start cheatsheet
                   1327: 	  .$addOther
                   1328:           .'<span>'
1.1037    www      1329: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1330: 	  .'</span> <span>'
1.1037    www      1331: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1332: 	  .'</span>';
1.732     raeburn  1333:     unless ($not_author) {
1.763     bisitz   1334:         $out .= ' <span>'
1.1037    www      1335: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1336: 	       .'</span> <span>'
1.1075.2.78  raeburn  1337:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1338:                .'</span>';
1.732     raeburn  1339:     }
1.763     bisitz   1340:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1341:     return $out;
1.172     www      1342: }
                   1343: 
1.430     albertel 1344: sub general_help {
                   1345:     my $helptopic='Student_Intro';
                   1346:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1347: 	$helptopic='Authoring_Intro';
1.907     raeburn  1348:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1349: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1350:     } elsif ($env{'request.role'}=~/^dc/) {
                   1351:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1352:     }
                   1353:     return $helptopic;
                   1354: }
                   1355: 
                   1356: sub update_help_link {
                   1357:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1358:     my $origurl = $ENV{'REQUEST_URI'};
                   1359:     $origurl=~s|^/~|/priv/|;
                   1360:     my $timestamp = time;
                   1361:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1362:         $$datum = &escape($$datum);
                   1363:     }
                   1364: 
                   1365:     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";
                   1366:     my $output .= <<"ENDOUTPUT";
                   1367: <script type="text/javascript">
1.824     bisitz   1368: // <![CDATA[
1.430     albertel 1369: banner_link = '$banner_link';
1.824     bisitz   1370: // ]]>
1.430     albertel 1371: </script>
                   1372: ENDOUTPUT
                   1373:     return $output;
                   1374: }
                   1375: 
                   1376: # now just updates the help link and generates a blue icon
1.193     raeburn  1377: sub help_open_menu {
1.1075.2.161.  .6(raebu 1378:22):     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1379: 	= @_;    
1.949     droeschl 1380:     $stayOnPage = 1;
1.430     albertel 1381:     my $output;
                   1382:     if ($component_help) {
                   1383: 	if (!$text) {
                   1384: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1075.2.161.  .6(raebu 1385:22): 				       $width,$height,'',$links_target);
1.430     albertel 1386: 	} else {
                   1387: 	    my $help_text;
                   1388: 	    $help_text=&unescape($topic);
                   1389: 	    $output='<table><tr><td>'.
                   1390: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1075.2.161.  .6(raebu 1391:22): 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1392: 	}
                   1393:     }
                   1394:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1395:     return $output.$banner_link;
                   1396: }
                   1397: 
                   1398: sub top_nav_help {
1.1075.2.158  raeburn  1399:     my ($text,$linkattr) = @_;
1.436     albertel 1400:     $text = &mt($text);
1.1075.2.60  raeburn  1401:     my $stay_on_page;
                   1402:     unless ($env{'environment.remote'} eq 'on') {
                   1403:         $stay_on_page = 1;
                   1404:     }
1.1075.2.61  raeburn  1405:     my ($link,$banner_link);
                   1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1408: 	                         : "javascript:helpMenu('open')";
                   1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1410:     }
1.201     raeburn  1411:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1412:     if ($link) {
                   1413:         return <<"END";
1.436     albertel 1414: $banner_link
1.1075.2.158  raeburn  1415: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1416: END
1.1075.2.61  raeburn  1417:     } else {
                   1418:         return '&nbsp;'.$text.'&nbsp;';
                   1419:     }
1.436     albertel 1420: }
                   1421: 
                   1422: sub help_menu_js {
1.1075.2.52  raeburn  1423:     my ($httphost) = @_;
1.949     droeschl 1424:     my $stayOnPage = 1;
1.436     albertel 1425:     my $width = 620;
                   1426:     my $height = 600;
1.430     albertel 1427:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1430:     my $start_page =
                   1431:         &Apache::loncommon::start_page('Help Menu', undef,
                   1432: 				       {'frameset'    => 1,
                   1433: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1434:                                         'use_absolute' => $httphost,
1.331     albertel 1435: 					'add_entries' => {
                   1436: 					    'border' => '0',
1.579     raeburn  1437: 					    'rows'   => "110,*",},});
1.331     albertel 1438:     my $end_page =
                   1439:         &Apache::loncommon::end_page({'frameset' => 1,
                   1440: 				      'js_ready' => 1,});
                   1441: 
1.436     albertel 1442:     my $template .= <<"ENDTEMPLATE";
                   1443: <script type="text/javascript">
1.877     bisitz   1444: // <![CDATA[
1.253     albertel 1445: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1446: var banner_link = '';
1.243     raeburn  1447: function helpMenu(target) {
                   1448:     var caller = this;
                   1449:     if (target == 'open') {
                   1450:         var newWindow = null;
                   1451:         try {
1.262     albertel 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1453:         }
                   1454:         catch(error) {
                   1455:             writeHelp(caller);
                   1456:             return;
                   1457:         }
                   1458:         if (newWindow) {
                   1459:             caller = newWindow;
                   1460:         }
1.193     raeburn  1461:     }
1.243     raeburn  1462:     writeHelp(caller);
                   1463:     return;
                   1464: }
                   1465: function writeHelp(caller) {
1.1075.2.61  raeburn  1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1468:     caller.document.close();
                   1469:     caller.focus();
1.193     raeburn  1470: }
1.877     bisitz   1471: // END LON-CAPA Internal -->
1.253     albertel 1472: // ]]>
1.436     albertel 1473: </script>
1.193     raeburn  1474: ENDTEMPLATE
                   1475:     return $template;
                   1476: }
                   1477: 
1.172     www      1478: sub help_open_bug {
                   1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1480:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1482:     $text = "" if (not defined $text);
                   1483: 	$stayOnPage=1;
1.184     albertel 1484:     $width = 600 if (not defined $width);
                   1485:     $height = 600 if (not defined $height);
1.172     www      1486: 
                   1487:     $topic=~s/\W+/\+/g;
                   1488:     my $link='';
                   1489:     my $template='';
1.379     albertel 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1492:     if (!$stayOnPage)
                   1493:     {
                   1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1495:     }
                   1496:     else
                   1497:     {
                   1498: 	$link = $url;
                   1499:     }
1.1075.2.161.  .6(raebu 1500:22): 
                   1501:22):     my $target = '_top';
                   1502:22):     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1503:22):         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1504:22):         $target = '_blank';
                   1505:22):     }
                   1506:22): 
1.172     www      1507:     # Add the text
                   1508:     if ($text ne "")
                   1509:     {
                   1510: 	$template .= 
                   1511:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1075.2.161.  .6(raebu 1512:22):   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1513:     }
                   1514: 
                   1515:     # Add the graphic
1.179     matthew  1516:     my $title = &mt('Report a Bug');
1.215     albertel 1517:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1518:     $template .= <<"ENDTEMPLATE";
1.1075.2.161.  .6(raebu 1519:22):  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1520: ENDTEMPLATE
                   1521:     if ($text ne '') { $template.='</td></tr></table>' };
                   1522:     return $template;
                   1523: 
                   1524: }
                   1525: 
                   1526: sub help_open_faq {
                   1527:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1528:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1529:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1530:     $text = "" if (not defined $text);
                   1531: 	$stayOnPage=1;
                   1532:     $width = 350 if (not defined $width);
                   1533:     $height = 400 if (not defined $height);
                   1534: 
                   1535:     $topic=~s/\W+/\+/g;
                   1536:     my $link='';
                   1537:     my $template='';
                   1538:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1539:     if (!$stayOnPage)
                   1540:     {
                   1541: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1542:     }
                   1543:     else
                   1544:     {
                   1545: 	$link = $url;
                   1546:     }
                   1547: 
                   1548:     # Add the text
                   1549:     if ($text ne "")
                   1550:     {
                   1551: 	$template .= 
1.173     www      1552:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1553:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1554:     }
                   1555: 
                   1556:     # Add the graphic
1.179     matthew  1557:     my $title = &mt('View the FAQ');
1.215     albertel 1558:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1559:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1560:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1561: ENDTEMPLATE
                   1562:     if ($text ne '') { $template.='</td></tr></table>' };
                   1563:     return $template;
                   1564: 
1.44      bowersj2 1565: }
1.37      matthew  1566: 
1.180     matthew  1567: ###############################################################
                   1568: ###############################################################
                   1569: 
1.45      matthew  1570: =pod
                   1571: 
1.648     raeburn  1572: =item * &change_content_javascript():
1.256     matthew  1573: 
                   1574: This and the next function allow you to create small sections of an
                   1575: otherwise static HTML page that you can update on the fly with
                   1576: Javascript, even in Netscape 4.
                   1577: 
                   1578: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1579: must be written to the HTML page once. It will prove the Javascript
                   1580: function "change(name, content)". Calling the change function with the
                   1581: name of the section 
                   1582: you want to update, matching the name passed to C<changable_area>, and
                   1583: the new content you want to put in there, will put the content into
                   1584: that area.
                   1585: 
                   1586: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1587: to contain room for the original contents. You need to "make space"
                   1588: for whatever changes you wish to make, and be B<sure> to check your
                   1589: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1590: it's adequate for updating a one-line status display, but little more.
                   1591: This script will set the space to 100% width, so you only need to
                   1592: worry about height in Netscape 4.
                   1593: 
                   1594: Modern browsers are much less limiting, and if you can commit to the
                   1595: user not using Netscape 4, this feature may be used freely with
                   1596: pretty much any HTML.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub change_content_javascript {
                   1601:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1602:     if ($env{'browser.type'} eq 'netscape' &&
                   1603: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1604: 	return (<<NETSCAPE4);
                   1605: 	function change(name, content) {
                   1606: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1607: 	    doc.open();
                   1608: 	    doc.write(content);
                   1609: 	    doc.close();
                   1610: 	}
                   1611: NETSCAPE4
                   1612:     } else {
                   1613: 	# Otherwise, we need to use semi-standards-compliant code
                   1614: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1615: 	# is really scary, and every useful browser supports it
                   1616: 	return (<<DOMBASED);
                   1617: 	function change(name, content) {
                   1618: 	    element = document.getElementById(name);
                   1619: 	    element.innerHTML = content;
                   1620: 	}
                   1621: DOMBASED
                   1622:     }
                   1623: }
                   1624: 
                   1625: =pod
                   1626: 
1.648     raeburn  1627: =item * &changable_area($name,$origContent):
1.256     matthew  1628: 
                   1629: This provides a "changable area" that can be modified on the fly via
                   1630: the Javascript code provided in C<change_content_javascript>. $name is
                   1631: the name you will use to reference the area later; do not repeat the
                   1632: same name on a given HTML page more then once. $origContent is what
                   1633: the area will originally contain, which can be left blank.
                   1634: 
                   1635: =cut
                   1636: 
                   1637: sub changable_area {
                   1638:     my ($name, $origContent) = @_;
                   1639: 
1.258     albertel 1640:     if ($env{'browser.type'} eq 'netscape' &&
                   1641: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1642: 	# If this is netscape 4, we need to use the Layer tag
                   1643: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1644:     } else {
                   1645: 	return "<span id='$name'>$origContent</span>";
                   1646:     }
                   1647: }
                   1648: 
                   1649: =pod
                   1650: 
1.648     raeburn  1651: =item * &viewport_geometry_js 
1.590     raeburn  1652: 
                   1653: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1654: 
                   1655: =cut
                   1656: 
                   1657: 
                   1658: sub viewport_geometry_js { 
                   1659:     return <<"GEOMETRY";
                   1660: var Geometry = {};
                   1661: function init_geometry() {
                   1662:     if (Geometry.init) { return };
                   1663:     Geometry.init=1;
                   1664:     if (window.innerHeight) {
                   1665:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1666:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1667:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1668:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1669:     }
                   1670:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1671:         Geometry.getViewportHeight =
                   1672:             function() { return document.documentElement.clientHeight; };
                   1673:         Geometry.getViewportWidth =
                   1674:             function() { return document.documentElement.clientWidth; };
                   1675: 
                   1676:         Geometry.getHorizontalScroll =
                   1677:             function() { return document.documentElement.scrollLeft; };
                   1678:         Geometry.getVerticalScroll =
                   1679:             function() { return document.documentElement.scrollTop; };
                   1680:     }
                   1681:     else if (document.body.clientHeight) {
                   1682:         Geometry.getViewportHeight =
                   1683:             function() { return document.body.clientHeight; };
                   1684:         Geometry.getViewportWidth =
                   1685:             function() { return document.body.clientWidth; };
                   1686:         Geometry.getHorizontalScroll =
                   1687:             function() { return document.body.scrollLeft; };
                   1688:         Geometry.getVerticalScroll =
                   1689:             function() { return document.body.scrollTop; };
                   1690:     }
                   1691: }
                   1692: 
                   1693: GEOMETRY
                   1694: }
                   1695: 
                   1696: =pod
                   1697: 
1.648     raeburn  1698: =item * &viewport_size_js()
1.590     raeburn  1699: 
                   1700: 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. 
                   1701: 
                   1702: =cut
                   1703: 
                   1704: sub viewport_size_js {
                   1705:     my $geometry = &viewport_geometry_js();
                   1706:     return <<"DIMS";
                   1707: 
                   1708: $geometry
                   1709: 
                   1710: function getViewportDims(width,height) {
                   1711:     init_geometry();
                   1712:     width.value = Geometry.getViewportWidth();
                   1713:     height.value = Geometry.getViewportHeight();
                   1714:     return;
                   1715: }
                   1716: 
                   1717: DIMS
                   1718: }
                   1719: 
                   1720: =pod
                   1721: 
1.648     raeburn  1722: =item * &resize_textarea_js()
1.565     albertel 1723: 
                   1724: emits the needed javascript to resize a textarea to be as big as possible
                   1725: 
                   1726: creates a function resize_textrea that takes two IDs first should be
                   1727: the id of the element to resize, second should be the id of a div that
                   1728: surrounds everything that comes after the textarea, this routine needs
                   1729: to be attached to the <body> for the onload and onresize events.
                   1730: 
                   1731: =cut
                   1732: 
                   1733: sub resize_textarea_js {
1.590     raeburn  1734:     my $geometry = &viewport_geometry_js();
1.565     albertel 1735:     return <<"RESIZE";
                   1736:     <script type="text/javascript">
1.824     bisitz   1737: // <![CDATA[
1.590     raeburn  1738: $geometry
1.565     albertel 1739: 
1.588     albertel 1740: function getX(element) {
                   1741:     var x = 0;
                   1742:     while (element) {
                   1743: 	x += element.offsetLeft;
                   1744: 	element = element.offsetParent;
                   1745:     }
                   1746:     return x;
                   1747: }
                   1748: function getY(element) {
                   1749:     var y = 0;
                   1750:     while (element) {
                   1751: 	y += element.offsetTop;
                   1752: 	element = element.offsetParent;
                   1753:     }
                   1754:     return y;
                   1755: }
                   1756: 
                   1757: 
1.565     albertel 1758: function resize_textarea(textarea_id,bottom_id) {
                   1759:     init_geometry();
                   1760:     var textarea        = document.getElementById(textarea_id);
                   1761:     //alert(textarea);
                   1762: 
1.588     albertel 1763:     var textarea_top    = getY(textarea);
1.565     albertel 1764:     var textarea_height = textarea.offsetHeight;
                   1765:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1766:     var bottom_top      = getY(bottom);
1.565     albertel 1767:     var bottom_height   = bottom.offsetHeight;
                   1768:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1769:     var fudge           = 23;
1.565     albertel 1770:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1771:     if (new_height < 300) {
                   1772: 	new_height = 300;
                   1773:     }
                   1774:     textarea.style.height=new_height+'px';
                   1775: }
1.824     bisitz   1776: // ]]>
1.565     albertel 1777: </script>
                   1778: RESIZE
                   1779: 
                   1780: }
                   1781: 
1.1075.2.112  raeburn  1782: sub colorfuleditor_js {
                   1783:     return <<"COLORFULEDIT"
                   1784: <script type="text/javascript">
                   1785: // <![CDATA[>
                   1786:     function fold_box(curDepth, lastresource){
                   1787: 
                   1788:     // we need a list because there can be several blocks you need to fold in one tag
                   1789:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1790:     // but there is only one folding button per tag
                   1791:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1792: 
                   1793:         if(block.item(0).style.display == 'none'){
                   1794: 
                   1795:             foldbutton.value = '@{[&mt("Hide")]}';
                   1796:             for (i = 0; i < block.length; i++){
                   1797:                 block.item(i).style.display = '';
                   1798:             }
                   1799:         }else{
                   1800: 
                   1801:             foldbutton.value = '@{[&mt("Show")]}';
                   1802:             for (i = 0; i < block.length; i++){
                   1803:                 // block.item(i).style.visibility = 'collapse';
                   1804:                 block.item(i).style.display = 'none';
                   1805:             }
                   1806:         };
                   1807:         saveState(lastresource);
                   1808:     }
                   1809: 
                   1810:     function saveState (lastresource) {
                   1811: 
                   1812:         var tag_list = getTagList();
                   1813:         if(tag_list != null){
                   1814:             var timestamp = new Date().getTime();
                   1815:             var key = lastresource;
                   1816: 
                   1817:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1818:             // starting with timestamp
                   1819:             var value = timestamp+';';
                   1820: 
                   1821:             // building the list of key-value pairs
                   1822:             for(var i = 0; i < tag_list.length; i++){
                   1823:                 value += tag_list[i]+',';
                   1824:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1825:             }
                   1826: 
                   1827:             // only iterate whole storage if nothing to override
                   1828:             if(localStorage.getItem(key) == null){
                   1829: 
                   1830:                 // prevent storage from growing large
                   1831:                 if(localStorage.length > 50){
                   1832:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1833:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1834:                     var oldest_key;
                   1835: 
                   1836:                     for(var i = 1; i < localStorage.length; i++){
                   1837:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1838:                             oldest_key = localStorage.key(i);
                   1839:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1840:                         }
                   1841:                     }
                   1842:                     localStorage.removeItem(oldest_key);
                   1843:                 }
                   1844:             }
                   1845:             localStorage.setItem(key,value);
                   1846:         }
                   1847:     }
                   1848: 
                   1849:     // restore folding status of blocks (on page load)
                   1850:     function restoreState (lastresource) {
                   1851:         if(localStorage.getItem(lastresource) != null){
                   1852:             var key = lastresource;
                   1853:             var value = localStorage.getItem(key);
                   1854:             var regex_delTimestamp = /^\d+;/;
                   1855: 
                   1856:             value.replace(regex_delTimestamp, '');
                   1857: 
                   1858:             var valueArr = value.split(';');
                   1859:             var pairs;
                   1860:             var elements;
                   1861:             for (var i = 0; i < valueArr.length; i++){
                   1862:                 pairs = valueArr[i].split(',');
                   1863:                 elements = document.getElementsByName(pairs[0]);
                   1864: 
                   1865:                 for (var j = 0; j < elements.length; j++){
                   1866:                     elements[j].style.display = pairs[1];
                   1867:                     if (pairs[1] == "none"){
                   1868:                         var regex_id = /([_\\d]+)\$/;
                   1869:                         regex_id.exec(pairs[0]);
                   1870:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1871:                     }
                   1872:                 }
                   1873:             }
                   1874:         }
                   1875:     }
                   1876: 
                   1877:     function getTagList () {
                   1878: 
                   1879:         var stringToSearch = document.lonhomework.innerHTML;
                   1880: 
                   1881:         var ret = new Array();
                   1882:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1883:         var tag_list = stringToSearch.match(regex_findBlock);
                   1884: 
                   1885:         if(tag_list != null){
                   1886:             for(var i = 0; i < tag_list.length; i++){
                   1887:                 ret.push(tag_list[i].replace(/"/, ''));
                   1888:             }
                   1889:         }
                   1890:         return ret;
                   1891:     }
                   1892: 
                   1893:     function saveScrollPosition (resource) {
                   1894:         var tag_list = getTagList();
                   1895: 
                   1896:         // we dont always want to jump to the first block
                   1897:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1898:         if(\$(window).scrollTop() > 170){
                   1899:             if(tag_list != null){
                   1900:                 var result;
                   1901:                 for(var i = 0; i < tag_list.length; i++){
                   1902:                     if(isElementInViewport(tag_list[i])){
                   1903:                         result += tag_list[i]+';';
                   1904:                     }
                   1905:                 }
                   1906:                 sessionStorage.setItem('anchor_'+resource, result);
                   1907:             }
                   1908:         } else {
                   1909:             // we dont need to save zero, just delete the item to leave everything tidy
                   1910:             sessionStorage.removeItem('anchor_'+resource);
                   1911:         }
                   1912:     }
                   1913: 
                   1914:     function restoreScrollPosition(resource){
                   1915: 
                   1916:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1917:         if(elem != null){
                   1918:             var tag_list = elem.split(';');
                   1919:             var elem_list;
                   1920: 
                   1921:             for(var i = 0; i < tag_list.length; i++){
                   1922:                 elem_list = document.getElementsByName(tag_list[i]);
                   1923: 
                   1924:                 if(elem_list.length > 0){
                   1925:                     elem = elem_list[0];
                   1926:                     break;
                   1927:                 }
                   1928:             }
                   1929:             elem.scrollIntoView();
                   1930:         }
                   1931:     }
                   1932: 
                   1933:     function isElementInViewport(el) {
                   1934: 
                   1935:         // change to last element instead of first
                   1936:         var elem = document.getElementsByName(el);
                   1937:         var rect = elem[0].getBoundingClientRect();
                   1938: 
                   1939:         return (
                   1940:             rect.top >= 0 &&
                   1941:             rect.left >= 0 &&
                   1942:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1943:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1944:         );
                   1945:     }
                   1946: 
                   1947:     function autosize(depth){
                   1948:         var cmInst = window['cm'+depth];
                   1949:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1950: 
                   1951:         // is fixed size, switching to dynamic
                   1952:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1953:             cmInst.setSize("","auto");
                   1954:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1955:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1956: 
                   1957:         // is dynamic size, switching to fixed
                   1958:         } else {
                   1959:             cmInst.setSize("","300px");
                   1960:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1961:             sessionStorage.removeItem("autosized_"+depth);
                   1962:         }
                   1963:     }
                   1964: 
                   1965: 
                   1966: 
                   1967: // ]]>
                   1968: </script>
                   1969: COLORFULEDIT
                   1970: }
                   1971: 
                   1972: sub xmleditor_js {
                   1973:     return <<XMLEDIT
                   1974: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1975: <script type="text/javascript">
                   1976: // <![CDATA[>
                   1977: 
                   1978:     function saveScrollPosition (resource) {
                   1979: 
                   1980:         var scrollPos = \$(window).scrollTop();
                   1981:         sessionStorage.setItem(resource,scrollPos);
                   1982:     }
                   1983: 
                   1984:     function restoreScrollPosition(resource){
                   1985: 
                   1986:         var scrollPos = sessionStorage.getItem(resource);
                   1987:         \$(window).scrollTop(scrollPos);
                   1988:     }
                   1989: 
                   1990:     // unless internet explorer
                   1991:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1992: 
                   1993:         \$(document).ready(function() {
                   1994:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1995:         });
                   1996:     }
                   1997: 
                   1998:     // inserts text at cursor position into codemirror (xml editor only)
                   1999:     function insertText(text){
                   2000:         cm.focus();
                   2001:         var curPos = cm.getCursor();
                   2002:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2003:     }
                   2004: // ]]>
                   2005: </script>
                   2006: XMLEDIT
                   2007: }
                   2008: 
                   2009: sub insert_folding_button {
                   2010:     my $curDepth = $Apache::lonxml::curdepth;
                   2011:     my $lastresource = $env{'request.ambiguous'};
                   2012: 
                   2013:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   2014:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2015: }
                   2016: 
1.1075.2.161.  .21(raeb 2017:-24): =pod
                   2018:-24): 
                   2019:-24): =item * &iframe_wrapper_headjs()
                   2020:-24): 
                   2021:-24): emits javascript containing two global vars to facilitate handling of resizing
                   2022:-24): by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2023:-24): with standard LON-CAPA menus.
                   2024:-24): 
                   2025:-24): =cut
                   2026:-24): 
                   2027:-24): #
                   2028:-24): # Where iframe is in use, if window.onload() executes before the custom resize function
                   2029:-24): # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2030:-24): # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2031:-24): # do not obscure the Functions menu.
                   2032:-24): #
                   2033:-24): 
                   2034:-24): sub iframe_wrapper_headjs {
                   2035:-24):     return <<"ENDJS";
                   2036:-24): <script type="text/javascript">
                   2037:-24): // <![CDATA[
                   2038:-24): var LCnotready = 0;
                   2039:-24): var LCresizedef = 0;
                   2040:-24): // ]]>
                   2041:-24): </script>
                   2042:-24): 
                   2043:-24): ENDJS
                   2044:-24): 
                   2045:-24): }
                   2046:-24): 
                   2047:-24): =pod
                   2048:-24): 
                   2049:-24): =item * &iframe_wrapper_resizejs()
                   2050:-24): 
                   2051:-24): emits javascript used to handle resizing for a page containing
                   2052:-24): an iframe, to ensure that the iframe does not obscure any
                   2053:-24): standard LON-CAPA menu items.
                   2054:-24): 
                   2055:-24): =back
                   2056:-24): 
                   2057:-24): =cut
                   2058:-24): 
                   2059:-24): #
                   2060:-24): # jQuery to use when iframe is in use and a page resize occurs.
                   2061:-24): # This script will ensure that the iframe does not obscure any
                   2062:-24): # standard LON-CAPA inline menus (primary, secondary, and/or
                   2063:-24): # breadcrumbs and Functions menus. Expects javascript from
                   2064:-24): # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2065:-24): # e.g., by inclusion in second arg passed to &start_page().
                   2066:-24): #
                   2067:-24): 
                   2068:-24): sub iframe_wrapper_resizejs {
                   2069:-24):     my $offset = 5;
                   2070:-24):     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2071:-24):     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2072:-24):         $offset = 0;
                   2073:-24):     }
                   2074:-24):     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2075:-24):     \$(document).ready( function() {
                   2076:-24):         \$(window).unbind('resize').resize(function(){
                   2077:-24):             var header = null;
                   2078:-24):             var offset = $offset;
                   2079:-24):             var height = 0;
                   2080:-24):             var hdrtop = 0;
                   2081:-24):             if (\$('div.LC_menus_content:first').length) {
                   2082:-24):                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2083:-24):                     header = \$('div.LC_menus_content:first');
                   2084:-24):                     offset = 12;
                   2085:-24):                 }
                   2086:-24):             } else if (\$('div.LC_head_subbox:first').length) {
                   2087:-24):                 header = \$('div.LC_head_subbox:first');
                   2088:-24):                 offset = 9;
                   2089:-24):             } else {
                   2090:-24):                 if (\$('#LC_breadcrumbs').length) {
                   2091:-24):                     header = \$('#LC_breadcrumbs');
                   2092:-24):                 }
                   2093:-24):             }
                   2094:-24):             if (header != null && header.length) {
                   2095:-24):                 height = header.height();
                   2096:-24):                 hdrtop = header.position().top;
                   2097:-24):             }
                   2098:-24):             var pos = height + hdrtop + offset;
                   2099:-24):             \$('.LC_iframecontainer').css('top', pos);
                   2100:-24):         });
                   2101:-24):         LCresizedef = 1;
                   2102:-24):         if (LCnotready == 1) {
                   2103:-24):             LCnotready = 0;
                   2104:-24):             \$(window).trigger('resize');
                   2105:-24):         }
                   2106:-24):     });
                   2107:-24):     window.onload = function(){
                   2108:-24):          if (LCresizedef) {
                   2109:-24):              LCnotready = 0;
                   2110:-24):              \$(window).trigger('resize');
                   2111:-24):          } else {
                   2112:-24):              LCnotready = 1;
                   2113:-24):          }
                   2114:-24):     };
                   2115:-24): SCRIPT
                   2116:-24): 
                   2117:-24): }
1.1075.2.112  raeburn  2118: 
1.565     albertel 2119: =pod
                   2120: 
1.256     matthew  2121: =head1 Excel and CSV file utility routines
                   2122: 
                   2123: =cut
                   2124: 
                   2125: ###############################################################
                   2126: ###############################################################
                   2127: 
                   2128: =pod
                   2129: 
1.1075.2.56  raeburn  2130: =over 4
                   2131: 
1.648     raeburn  2132: =item * &csv_translate($text) 
1.37      matthew  2133: 
1.185     www      2134: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2135: format.
                   2136: 
                   2137: =cut
                   2138: 
1.180     matthew  2139: ###############################################################
                   2140: ###############################################################
1.37      matthew  2141: sub csv_translate {
                   2142:     my $text = shift;
                   2143:     $text =~ s/\"/\"\"/g;
1.209     albertel 2144:     $text =~ s/\n/ /g;
1.37      matthew  2145:     return $text;
                   2146: }
1.180     matthew  2147: 
                   2148: ###############################################################
                   2149: ###############################################################
                   2150: 
                   2151: =pod
                   2152: 
1.648     raeburn  2153: =item * &define_excel_formats()
1.180     matthew  2154: 
                   2155: Define some commonly used Excel cell formats.
                   2156: 
                   2157: Currently supported formats:
                   2158: 
                   2159: =over 4
                   2160: 
                   2161: =item header
                   2162: 
                   2163: =item bold
                   2164: 
                   2165: =item h1
                   2166: 
                   2167: =item h2
                   2168: 
                   2169: =item h3
                   2170: 
1.256     matthew  2171: =item h4
                   2172: 
                   2173: =item i
                   2174: 
1.180     matthew  2175: =item date
                   2176: 
                   2177: =back
                   2178: 
                   2179: Inputs: $workbook
                   2180: 
                   2181: Returns: $format, a hash reference.
                   2182: 
1.1057    foxr     2183: 
1.180     matthew  2184: =cut
                   2185: 
                   2186: ###############################################################
                   2187: ###############################################################
                   2188: sub define_excel_formats {
                   2189:     my ($workbook) = @_;
                   2190:     my $format;
                   2191:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2192:                                                 bottom    => 1,
                   2193:                                                 align     => 'center');
                   2194:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2195:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2196:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2197:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2198:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2199:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2200:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2201:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2202:     return $format;
                   2203: }
                   2204: 
                   2205: ###############################################################
                   2206: ###############################################################
1.113     bowersj2 2207: 
                   2208: =pod
                   2209: 
1.648     raeburn  2210: =item * &create_workbook()
1.255     matthew  2211: 
                   2212: Create an Excel worksheet.  If it fails, output message on the
                   2213: request object and return undefs.
                   2214: 
                   2215: Inputs: Apache request object
                   2216: 
                   2217: Returns (undef) on failure, 
                   2218:     Excel worksheet object, scalar with filename, and formats 
                   2219:     from &Apache::loncommon::define_excel_formats on success
                   2220: 
                   2221: =cut
                   2222: 
                   2223: ###############################################################
                   2224: ###############################################################
                   2225: sub create_workbook {
                   2226:     my ($r) = @_;
                   2227:         #
                   2228:     # Create the excel spreadsheet
                   2229:     my $filename = '/prtspool/'.
1.258     albertel 2230:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2231:         time.'_'.rand(1000000000).'.xls';
                   2232:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2233:     if (! defined($workbook)) {
                   2234:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2235:         $r->print(
                   2236:             '<p class="LC_error">'
                   2237:            .&mt('Problems occurred in creating the new Excel file.')
                   2238:            .' '.&mt('This error has been logged.')
                   2239:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2240:            .'</p>'
                   2241:         );
1.255     matthew  2242:         return (undef);
                   2243:     }
                   2244:     #
1.1014    foxr     2245:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2246:     #
                   2247:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2248:     return ($workbook,$filename,$format);
                   2249: }
                   2250: 
                   2251: ###############################################################
                   2252: ###############################################################
                   2253: 
                   2254: =pod
                   2255: 
1.648     raeburn  2256: =item * &create_text_file()
1.113     bowersj2 2257: 
1.542     raeburn  2258: Create a file to write to and eventually make available to the user.
1.256     matthew  2259: If file creation fails, outputs an error message on the request object and 
                   2260: return undefs.
1.113     bowersj2 2261: 
1.256     matthew  2262: Inputs: Apache request object, and file suffix
1.113     bowersj2 2263: 
1.256     matthew  2264: Returns (undef) on failure, 
                   2265:     Filehandle and filename on success.
1.113     bowersj2 2266: 
                   2267: =cut
                   2268: 
1.256     matthew  2269: ###############################################################
                   2270: ###############################################################
                   2271: sub create_text_file {
                   2272:     my ($r,$suffix) = @_;
                   2273:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2274:     my $fh;
                   2275:     my $filename = '/prtspool/'.
1.258     albertel 2276:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2277:         time.'_'.rand(1000000000).'.'.$suffix;
                   2278:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2279:     if (! defined($fh)) {
                   2280:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2281:         $r->print(
                   2282:             '<p class="LC_error">'
                   2283:            .&mt('Problems occurred in creating the output file.')
                   2284:            .' '.&mt('This error has been logged.')
                   2285:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2286:            .'</p>'
                   2287:         );
1.113     bowersj2 2288:     }
1.256     matthew  2289:     return ($fh,$filename)
1.113     bowersj2 2290: }
                   2291: 
                   2292: 
1.256     matthew  2293: =pod 
1.113     bowersj2 2294: 
                   2295: =back
                   2296: 
                   2297: =cut
1.37      matthew  2298: 
                   2299: ###############################################################
1.33      matthew  2300: ##        Home server <option> list generating code          ##
                   2301: ###############################################################
1.35      matthew  2302: 
1.169     www      2303: # ------------------------------------------
                   2304: 
                   2305: sub domain_select {
                   2306:     my ($name,$value,$multiple)=@_;
                   2307:     my %domains=map { 
1.514     albertel 2308: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2309:     } &Apache::lonnet::all_domains();
1.169     www      2310:     if ($multiple) {
                   2311: 	$domains{''}=&mt('Any domain');
1.550     albertel 2312: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2313: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2314:     } else {
1.550     albertel 2315: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2316: 	return &select_form($name,$value,\%domains);
1.169     www      2317:     }
                   2318: }
                   2319: 
1.282     albertel 2320: #-------------------------------------------
                   2321: 
                   2322: =pod
                   2323: 
1.519     raeburn  2324: =head1 Routines for form select boxes
                   2325: 
                   2326: =over 4
                   2327: 
1.648     raeburn  2328: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2329: 
                   2330: Returns a string containing a <select> element int multiple mode
                   2331: 
                   2332: 
                   2333: Args:
                   2334:   $name - name of the <select> element
1.506     raeburn  2335:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2336:   $size - number of rows long the select element is
1.283     albertel 2337:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2338:           (shown text should already have been &mt())
1.506     raeburn  2339:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2340: 
1.282     albertel 2341: =cut
                   2342: 
                   2343: #-------------------------------------------
1.169     www      2344: sub multiple_select_form {
1.284     albertel 2345:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2346:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2347:     my $output='';
1.191     matthew  2348:     if (! defined($size)) {
                   2349:         $size = 4;
1.283     albertel 2350:         if (scalar(keys(%$hash))<4) {
                   2351:             $size = scalar(keys(%$hash));
1.191     matthew  2352:         }
                   2353:     }
1.734     bisitz   2354:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2355:     my @order;
1.506     raeburn  2356:     if (ref($order) eq 'ARRAY')  {
                   2357:         @order = @{$order};
                   2358:     } else {
                   2359:         @order = sort(keys(%$hash));
1.501     banghart 2360:     }
                   2361:     if (exists($$hash{'select_form_order'})) {
                   2362:         @order = @{$$hash{'select_form_order'}};
                   2363:     }
                   2364:         
1.284     albertel 2365:     foreach my $key (@order) {
1.356     albertel 2366:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2367:         $output.='selected="selected" ' if ($selected{$key});
                   2368:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2369:     }
                   2370:     $output.="</select>\n";
                   2371:     return $output;
                   2372: }
                   2373: 
1.88      www      2374: #-------------------------------------------
                   2375: 
                   2376: =pod
                   2377: 
1.1075.2.115  raeburn  2378: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2379: 
                   2380: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2381: allow a user to select options from a ref to a hash containing:
                   2382: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2383: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2384: An optional arg -- $readonly -- if true will cause the select form
                   2385: to be disabled, e.g., for the case where an instructor has a section-
                   2386: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2387: 
1.88      www      2388: See lonrights.pm for an example invocation and use.
                   2389: 
                   2390: =cut
                   2391: 
                   2392: #-------------------------------------------
                   2393: sub select_form {
1.1075.2.115  raeburn  2394:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2395:     return unless (ref($hashref) eq 'HASH');
                   2396:     if ($onchange) {
                   2397:         $onchange = ' onchange="'.$onchange.'"';
                   2398:     }
1.1075.2.129  raeburn  2399:     my $disabled;
                   2400:     if ($readonly) {
                   2401:         $disabled = ' disabled="disabled"';
                   2402:     }
                   2403:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2404:     my @keys;
1.970     raeburn  2405:     if (exists($hashref->{'select_form_order'})) {
                   2406: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2407:     } else {
1.970     raeburn  2408: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2409:     }
1.356     albertel 2410:     foreach my $key (@keys) {
                   2411:         $selectform.=
                   2412: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2413:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2414:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2415:     }
                   2416:     $selectform.="</select>";
                   2417:     return $selectform;
                   2418: }
                   2419: 
1.475     www      2420: # For display filters
                   2421: 
                   2422: sub display_filter {
1.1074    raeburn  2423:     my ($context) = @_;
1.475     www      2424:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2425:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2426:     my $phraseinput = 'hidden';
                   2427:     my $includeinput = 'hidden';
                   2428:     my ($checked,$includetypestext);
                   2429:     if ($env{'form.displayfilter'} eq 'containing') {
                   2430:         $phraseinput = 'text'; 
                   2431:         if ($context eq 'parmslog') {
                   2432:             $includeinput = 'checkbox';
                   2433:             if ($env{'form.includetypes'}) {
                   2434:                 $checked = ' checked="checked"';
                   2435:             }
                   2436:             $includetypestext = &mt('Include parameter types');
                   2437:         }
                   2438:     } else {
                   2439:         $includetypestext = '&nbsp;';
                   2440:     }
                   2441:     my ($additional,$secondid,$thirdid);
                   2442:     if ($context eq 'parmslog') {
                   2443:         $additional = 
                   2444:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2445:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2446:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2447:             '</label>';
                   2448:         $secondid = 'includetypes';
                   2449:         $thirdid = 'includetypestext';
                   2450:     }
                   2451:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2452:                                                     '$secondid','$thirdid')";
                   2453:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2454: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2455: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2456: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2457:            &mt('Filter: [_1]',
1.477     www      2458: 	   &select_form($env{'form.displayfilter'},
                   2459: 			'displayfilter',
1.970     raeburn  2460: 			{'currentfolder' => 'Current folder/page',
1.477     www      2461: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2462: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2463: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2464:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2465:                          '" />'.$additional;
                   2466: }
                   2467: 
                   2468: sub display_filter_js {
                   2469:     my $includetext = &mt('Include parameter types');
                   2470:     return <<"ENDJS";
                   2471:   
                   2472: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2473:     var firstType = 'hidden';
                   2474:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2475:         firstType = 'text';
                   2476:     }
                   2477:     firstObject = document.getElementById(firstid);
                   2478:     if (typeof(firstObject) == 'object') {
                   2479:         if (firstObject.type != firstType) {
                   2480:             changeInputType(firstObject,firstType);
                   2481:         }
                   2482:     }
                   2483:     if (context == 'parmslog') {
                   2484:         var secondType = 'hidden';
                   2485:         if (firstType == 'text') {
                   2486:             secondType = 'checkbox';
                   2487:         }
                   2488:         secondObject = document.getElementById(secondid);  
                   2489:         if (typeof(secondObject) == 'object') {
                   2490:             if (secondObject.type != secondType) {
                   2491:                 changeInputType(secondObject,secondType);
                   2492:             }
                   2493:         }
                   2494:         var textItem = document.getElementById(thirdid);
                   2495:         var currtext = textItem.innerHTML;
                   2496:         var newtext;
                   2497:         if (firstType == 'text') {
                   2498:             newtext = '$includetext';
                   2499:         } else {
                   2500:             newtext = '&nbsp;';
                   2501:         }
                   2502:         if (currtext != newtext) {
                   2503:             textItem.innerHTML = newtext;
                   2504:         }
                   2505:     }
                   2506:     return;
                   2507: }
                   2508: 
                   2509: function changeInputType(oldObject,newType) {
                   2510:     var newObject = document.createElement('input');
                   2511:     newObject.type = newType;
                   2512:     if (oldObject.size) {
                   2513:         newObject.size = oldObject.size;
                   2514:     }
                   2515:     if (oldObject.value) {
                   2516:         newObject.value = oldObject.value;
                   2517:     }
                   2518:     if (oldObject.name) {
                   2519:         newObject.name = oldObject.name;
                   2520:     }
                   2521:     if (oldObject.id) {
                   2522:         newObject.id = oldObject.id;
                   2523:     }
                   2524:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2525:     return;
                   2526: }
                   2527: 
                   2528: ENDJS
1.475     www      2529: }
                   2530: 
1.167     www      2531: sub gradeleveldescription {
                   2532:     my $gradelevel=shift;
                   2533:     my %gradelevels=(0 => 'Not specified',
                   2534: 		     1 => 'Grade 1',
                   2535: 		     2 => 'Grade 2',
                   2536: 		     3 => 'Grade 3',
                   2537: 		     4 => 'Grade 4',
                   2538: 		     5 => 'Grade 5',
                   2539: 		     6 => 'Grade 6',
                   2540: 		     7 => 'Grade 7',
                   2541: 		     8 => 'Grade 8',
                   2542: 		     9 => 'Grade 9',
                   2543: 		     10 => 'Grade 10',
                   2544: 		     11 => 'Grade 11',
                   2545: 		     12 => 'Grade 12',
                   2546: 		     13 => 'Grade 13',
                   2547: 		     14 => '100 Level',
                   2548: 		     15 => '200 Level',
                   2549: 		     16 => '300 Level',
                   2550: 		     17 => '400 Level',
                   2551: 		     18 => 'Graduate Level');
                   2552:     return &mt($gradelevels{$gradelevel});
                   2553: }
                   2554: 
1.163     www      2555: sub select_level_form {
                   2556:     my ($deflevel,$name)=@_;
                   2557:     unless ($deflevel) { $deflevel=0; }
1.167     www      2558:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2559:     for (my $i=0; $i<=18; $i++) {
                   2560:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2561:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2562:                 ">".&gradeleveldescription($i)."</option>\n";
                   2563:     }
                   2564:     $selectform.="</select>";
                   2565:     return $selectform;
1.163     www      2566: }
1.167     www      2567: 
1.35      matthew  2568: #-------------------------------------------
                   2569: 
1.45      matthew  2570: =pod
                   2571: 
1.1075.2.115  raeburn  2572: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2573: 
                   2574: Returns a string containing a <select name='$name' size='1'> form to 
                   2575: allow a user to select the domain to preform an operation in.  
                   2576: See loncreateuser.pm for an example invocation and use.
                   2577: 
1.90      www      2578: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2579: selected");
                   2580: 
1.743     raeburn  2581: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2582: 
1.910     raeburn  2583: 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.
                   2584: 
1.1075.2.36  raeburn  2585: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2586: 
1.1075.2.115  raeburn  2587: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2588: 
                   2589: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2590: 
1.35      matthew  2591: =cut
                   2592: 
                   2593: #-------------------------------------------
1.34      matthew  2594: sub select_dom_form {
1.1075.2.115  raeburn  2595:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2596:     if ($onchange) {
1.874     raeburn  2597:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2598:     }
1.1075.2.115  raeburn  2599:     if ($disabled) {
                   2600:         $disabled = ' disabled="disabled"';
                   2601:     }
1.1075.2.36  raeburn  2602:     my (@domains,%exclude);
1.910     raeburn  2603:     if (ref($incdoms) eq 'ARRAY') {
                   2604:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2605:     } else {
                   2606:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2607:     }
1.90      www      2608:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2609:     if (ref($excdoms) eq 'ARRAY') {
                   2610:         map { $exclude{$_} = 1; } @{$excdoms};
                   2611:     }
1.1075.2.115  raeburn  2612:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2613:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2614:         next if ($exclude{$dom});
1.356     albertel 2615:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2616:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2617:         if ($showdomdesc) {
                   2618:             if ($dom ne '') {
                   2619:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2620:                 if ($domdesc ne '') {
                   2621:                     $selectdomain .= ' ('.$domdesc.')';
                   2622:                 }
                   2623:             } 
                   2624:         }
                   2625:         $selectdomain .= "</option>\n";
1.34      matthew  2626:     }
                   2627:     $selectdomain.="</select>";
                   2628:     return $selectdomain;
                   2629: }
                   2630: 
1.35      matthew  2631: #-------------------------------------------
                   2632: 
1.45      matthew  2633: =pod
                   2634: 
1.648     raeburn  2635: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2636: 
1.586     raeburn  2637: input: 4 arguments (two required, two optional) - 
                   2638:     $domain - domain of new user
                   2639:     $name - name of form element
                   2640:     $default - Value of 'default' causes a default item to be first 
                   2641:                             option, and selected by default. 
                   2642:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2643:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2644: output: returns 2 items: 
1.586     raeburn  2645: (a) form element which contains either:
                   2646:    (i) <select name="$name">
                   2647:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2648:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2649:        </select>
                   2650:        form item if there are multiple library servers in $domain, or
                   2651:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2652:        if there is only one library server in $domain.
                   2653: 
                   2654: (b) number of library servers found.
                   2655: 
                   2656: See loncreateuser.pm for example of use.
1.35      matthew  2657: 
                   2658: =cut
                   2659: 
                   2660: #-------------------------------------------
1.586     raeburn  2661: sub home_server_form_item {
                   2662:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2663:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2664:     my $result;
                   2665:     my $numlib = keys(%servers);
                   2666:     if ($numlib > 1) {
                   2667:         $result .= '<select name="'.$name.'" />'."\n";
                   2668:         if ($default) {
1.804     bisitz   2669:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2670:                        '</option>'."\n";
                   2671:         }
                   2672:         foreach my $hostid (sort(keys(%servers))) {
                   2673:             $result.= '<option value="'.$hostid.'">'.
                   2674: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2675:         }
                   2676:         $result .= '</select>'."\n";
                   2677:     } elsif ($numlib == 1) {
                   2678:         my $hostid;
                   2679:         foreach my $item (keys(%servers)) {
                   2680:             $hostid = $item;
                   2681:         }
                   2682:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2683:                    $hostid.'" />';
                   2684:                    if (!$hide) {
                   2685:                        $result .= $hostid.' '.$servers{$hostid};
                   2686:                    }
                   2687:                    $result .= "\n";
                   2688:     } elsif ($default) {
                   2689:         $result .= '<input type="hidden" name="'.$name.
                   2690:                    '" value="default" />';
                   2691:                    if (!$hide) {
                   2692:                        $result .= &mt('default');
                   2693:                    }
                   2694:                    $result .= "\n";
1.33      matthew  2695:     }
1.586     raeburn  2696:     return ($result,$numlib);
1.33      matthew  2697: }
1.112     bowersj2 2698: 
                   2699: =pod
                   2700: 
1.534     albertel 2701: =back 
                   2702: 
1.112     bowersj2 2703: =cut
1.87      matthew  2704: 
                   2705: ###############################################################
1.112     bowersj2 2706: ##                  Decoding User Agent                      ##
1.87      matthew  2707: ###############################################################
                   2708: 
                   2709: =pod
                   2710: 
1.112     bowersj2 2711: =head1 Decoding the User Agent
                   2712: 
                   2713: =over 4
                   2714: 
                   2715: =item * &decode_user_agent()
1.87      matthew  2716: 
                   2717: Inputs: $r
                   2718: 
                   2719: Outputs:
                   2720: 
                   2721: =over 4
                   2722: 
1.112     bowersj2 2723: =item * $httpbrowser
1.87      matthew  2724: 
1.112     bowersj2 2725: =item * $clientbrowser
1.87      matthew  2726: 
1.112     bowersj2 2727: =item * $clientversion
1.87      matthew  2728: 
1.112     bowersj2 2729: =item * $clientmathml
1.87      matthew  2730: 
1.112     bowersj2 2731: =item * $clientunicode
1.87      matthew  2732: 
1.112     bowersj2 2733: =item * $clientos
1.87      matthew  2734: 
1.1075.2.42  raeburn  2735: =item * $clientmobile
                   2736: 
                   2737: =item * $clientinfo
                   2738: 
1.1075.2.77  raeburn  2739: =item * $clientosversion
                   2740: 
1.87      matthew  2741: =back
                   2742: 
1.157     matthew  2743: =back 
                   2744: 
1.87      matthew  2745: =cut
                   2746: 
                   2747: ###############################################################
                   2748: ###############################################################
                   2749: sub decode_user_agent {
1.247     albertel 2750:     my ($r)=@_;
1.87      matthew  2751:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2752:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2753:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2754:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2755:     my $clientbrowser='unknown';
                   2756:     my $clientversion='0';
                   2757:     my $clientmathml='';
                   2758:     my $clientunicode='0';
1.1075.2.42  raeburn  2759:     my $clientmobile=0;
1.1075.2.77  raeburn  2760:     my $clientosversion='';
1.87      matthew  2761:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2762:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2763: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2764: 	    $clientbrowser=$bname;
                   2765:             $httpbrowser=~/$vreg/i;
                   2766: 	    $clientversion=$1;
                   2767:             $clientmathml=($clientversion>=$minv);
                   2768:             $clientunicode=($clientversion>=$univ);
                   2769: 	}
                   2770:     }
                   2771:     my $clientos='unknown';
1.1075.2.42  raeburn  2772:     my $clientinfo;
1.87      matthew  2773:     if (($httpbrowser=~/linux/i) ||
                   2774:         ($httpbrowser=~/unix/i) ||
                   2775:         ($httpbrowser=~/ux/i) ||
                   2776:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2777:     if (($httpbrowser=~/vax/i) ||
                   2778:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2779:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2780:     if (($httpbrowser=~/mac/i) ||
                   2781:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2782:     if ($httpbrowser=~/win/i) {
                   2783:         $clientos='win';
                   2784:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2785:             $clientosversion = $1;
                   2786:         }
                   2787:     }
1.87      matthew  2788:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2789:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2790:         $clientmobile=lc($1);
                   2791:     }
                   2792:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2793:         $clientinfo = 'firefox-'.$1;
                   2794:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2795:         $clientinfo = 'chromeframe-'.$1;
                   2796:     }
1.87      matthew  2797:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2798:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2799:             $clientosversion);
1.87      matthew  2800: }
                   2801: 
1.32      matthew  2802: ###############################################################
                   2803: ##    Authentication changing form generation subroutines    ##
                   2804: ###############################################################
                   2805: ##
                   2806: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2807: ## hash, and have reasonable default values.
                   2808: ##
                   2809: ##    formname = the name given in the <form> tag.
1.35      matthew  2810: #-------------------------------------------
                   2811: 
1.45      matthew  2812: =pod
                   2813: 
1.112     bowersj2 2814: =head1 Authentication Routines
                   2815: 
                   2816: =over 4
                   2817: 
1.648     raeburn  2818: =item * &authform_xxxxxx()
1.35      matthew  2819: 
                   2820: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2821: handle some of the conveniences required for authentication forms.  
                   2822: This is not an optimal method, but it works.  
                   2823: 
                   2824: =over 4
                   2825: 
1.112     bowersj2 2826: =item * authform_header
1.35      matthew  2827: 
1.112     bowersj2 2828: =item * authform_authorwarning
1.35      matthew  2829: 
1.112     bowersj2 2830: =item * authform_nochange
1.35      matthew  2831: 
1.112     bowersj2 2832: =item * authform_kerberos
1.35      matthew  2833: 
1.112     bowersj2 2834: =item * authform_internal
1.35      matthew  2835: 
1.112     bowersj2 2836: =item * authform_filesystem
1.35      matthew  2837: 
1.1075.2.161.  .17(raeb 2838:-23): =item * authform_lti
                   2839:-23): 
1.35      matthew  2840: =back
                   2841: 
1.648     raeburn  2842: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2843: 
1.35      matthew  2844: =cut
                   2845: 
                   2846: #-------------------------------------------
1.32      matthew  2847: sub authform_header{  
                   2848:     my %in = (
                   2849:         formname => 'cu',
1.80      albertel 2850:         kerb_def_dom => '',
1.32      matthew  2851:         @_,
                   2852:     );
                   2853:     $in{'formname'} = 'document.' . $in{'formname'};
                   2854:     my $result='';
1.80      albertel 2855: 
                   2856: #---------------------------------------------- Code for upper case translation
                   2857:     my $Javascript_toUpperCase;
                   2858:     unless ($in{kerb_def_dom}) {
                   2859:         $Javascript_toUpperCase =<<"END";
                   2860:         switch (choice) {
                   2861:            case 'krb': currentform.elements[choicearg].value =
                   2862:                currentform.elements[choicearg].value.toUpperCase();
                   2863:                break;
                   2864:            default:
                   2865:         }
                   2866: END
                   2867:     } else {
                   2868:         $Javascript_toUpperCase = "";
                   2869:     }
                   2870: 
1.165     raeburn  2871:     my $radioval = "'nochange'";
1.591     raeburn  2872:     if (defined($in{'curr_authtype'})) {
                   2873:         if ($in{'curr_authtype'} ne '') {
                   2874:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2875:         }
1.174     matthew  2876:     }
1.165     raeburn  2877:     my $argfield = 'null';
1.591     raeburn  2878:     if (defined($in{'mode'})) {
1.165     raeburn  2879:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2880:             if (defined($in{'curr_autharg'})) {
                   2881:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2882:                     $argfield = "'$in{'curr_autharg'}'";
                   2883:                 }
                   2884:             }
                   2885:         }
                   2886:     }
                   2887: 
1.32      matthew  2888:     $result.=<<"END";
                   2889: var current = new Object();
1.165     raeburn  2890: current.radiovalue = $radioval;
                   2891: current.argfield = $argfield;
1.32      matthew  2892: 
                   2893: function changed_radio(choice,currentform) {
                   2894:     var choicearg = choice + 'arg';
                   2895:     // If a radio button in changed, we need to change the argfield
                   2896:     if (current.radiovalue != choice) {
                   2897:         current.radiovalue = choice;
                   2898:         if (current.argfield != null) {
                   2899:             currentform.elements[current.argfield].value = '';
                   2900:         }
                   2901:         if (choice == 'nochange') {
                   2902:             current.argfield = null;
                   2903:         } else {
                   2904:             current.argfield = choicearg;
                   2905:             switch(choice) {
                   2906:                 case 'krb': 
                   2907:                     currentform.elements[current.argfield].value = 
                   2908:                         "$in{'kerb_def_dom'}";
                   2909:                 break;
                   2910:               default:
                   2911:                 break;
                   2912:             }
                   2913:         }
                   2914:     }
                   2915:     return;
                   2916: }
1.22      www      2917: 
1.32      matthew  2918: function changed_text(choice,currentform) {
                   2919:     var choicearg = choice + 'arg';
                   2920:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2921:         $Javascript_toUpperCase
1.32      matthew  2922:         // clear old field
                   2923:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2924:             currentform.elements[current.argfield].value = '';
                   2925:         }
                   2926:         current.argfield = choicearg;
                   2927:     }
                   2928:     set_auth_radio_buttons(choice,currentform);
                   2929:     return;
1.20      www      2930: }
1.32      matthew  2931: 
                   2932: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2933:     var numauthchoices = currentform.login.length;
                   2934:     if (typeof numauthchoices  == "undefined") {
                   2935:         return;
                   2936:     } 
1.32      matthew  2937:     var i=0;
1.986     raeburn  2938:     while (i < numauthchoices) {
1.32      matthew  2939:         if (currentform.login[i].value == newvalue) { break; }
                   2940:         i++;
                   2941:     }
1.986     raeburn  2942:     if (i == numauthchoices) {
1.32      matthew  2943:         return;
                   2944:     }
                   2945:     current.radiovalue = newvalue;
                   2946:     currentform.login[i].checked = true;
                   2947:     return;
                   2948: }
                   2949: END
                   2950:     return $result;
                   2951: }
                   2952: 
1.1075.2.20  raeburn  2953: sub authform_authorwarning {
1.32      matthew  2954:     my $result='';
1.144     matthew  2955:     $result='<i>'.
                   2956:         &mt('As a general rule, only authors or co-authors should be '.
                   2957:             'filesystem authenticated '.
                   2958:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2959:     return $result;
                   2960: }
                   2961: 
1.1075.2.20  raeburn  2962: sub authform_nochange {
1.32      matthew  2963:     my %in = (
                   2964:               formname => 'document.cu',
                   2965:               kerb_def_dom => 'MSU.EDU',
                   2966:               @_,
                   2967:           );
1.1075.2.20  raeburn  2968:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2969:     my $result;
1.1075.2.20  raeburn  2970:     if (!$authnum) {
                   2971:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2972:     } else {
                   2973:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2974:                   '<input type="radio" name="login" value="nochange" '.
                   2975:                   'checked="checked" onclick="'.
1.281     albertel 2976:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2977: 	    '</label>';
1.586     raeburn  2978:     }
1.32      matthew  2979:     return $result;
                   2980: }
                   2981: 
1.591     raeburn  2982: sub authform_kerberos {
1.32      matthew  2983:     my %in = (
                   2984:               formname => 'document.cu',
                   2985:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2986:               kerb_def_auth => 'krb4',
1.32      matthew  2987:               @_,
                   2988:               );
1.586     raeburn  2989:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2990:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2991:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2992:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2993:        $check5 = ' checked="checked"';
1.80      albertel 2994:     } else {
1.772     bisitz   2995:        $check4 = ' checked="checked"';
1.80      albertel 2996:     }
1.1075.2.117  raeburn  2997:     if ($in{'readonly'}) {
                   2998:         $disabled = ' disabled="disabled"';
                   2999:     }
1.165     raeburn  3000:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3001:     if (defined($in{'curr_authtype'})) {
                   3002:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3003:             $krbcheck = ' checked="checked"';
1.623     raeburn  3004:             if (defined($in{'mode'})) {
                   3005:                 if ($in{'mode'} eq 'modifyuser') {
                   3006:                     $krbcheck = '';
                   3007:                 }
                   3008:             }
1.591     raeburn  3009:             if (defined($in{'curr_kerb_ver'})) {
                   3010:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3011:                     $check5 = ' checked="checked"';
1.591     raeburn  3012:                     $check4 = '';
                   3013:                 } else {
1.772     bisitz   3014:                     $check4 = ' checked="checked"';
1.591     raeburn  3015:                     $check5 = '';
                   3016:                 }
1.586     raeburn  3017:             }
1.591     raeburn  3018:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3019:                 $krbarg = $in{'curr_autharg'};
                   3020:             }
1.586     raeburn  3021:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3022:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3023:                     $result = 
                   3024:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3025:         $in{'curr_autharg'},$krbver);
                   3026:                 } else {
                   3027:                     $result =
                   3028:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3029:                 }
                   3030:                 return $result; 
                   3031:             }
                   3032:         }
                   3033:     } else {
                   3034:         if ($authnum == 1) {
1.784     bisitz   3035:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3036:         }
                   3037:     }
1.586     raeburn  3038:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3039:         return;
1.587     raeburn  3040:     } elsif ($authtype eq '') {
1.591     raeburn  3041:         if (defined($in{'mode'})) {
1.587     raeburn  3042:             if ($in{'mode'} eq 'modifycourse') {
                   3043:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3044:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3045:                 }
                   3046:             }
                   3047:         }
1.586     raeburn  3048:     }
                   3049:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3050:     if ($authtype eq '') {
                   3051:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3052:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  3053:                     $krbcheck.$disabled.' />';
1.586     raeburn  3054:     }
                   3055:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  3056:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3057:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  3058:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3059:          $in{'curr_authtype'} eq 'krb4')) {
                   3060:         $result .= &mt
1.144     matthew  3061:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3062:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3063:          '<label>'.$authtype,
1.281     albertel 3064:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3065:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3066:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3067:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3068:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3069: 	 '</label>');
1.586     raeburn  3070:     } elsif ($can_assign{'krb4'}) {
                   3071:         $result .= &mt
                   3072:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3073:          '[_3] Version 4 [_4]',
                   3074:          '<label>'.$authtype,
                   3075:          '</label><input type="text" size="10" name="krbarg" '.
                   3076:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3077:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3078:          '<label><input type="hidden" name="krbver" value="4" />',
                   3079:          '</label>');
                   3080:     } elsif ($can_assign{'krb5'}) {
                   3081:         $result .= &mt
                   3082:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3083:          '[_3] Version 5 [_4]',
                   3084:          '<label>'.$authtype,
                   3085:          '</label><input type="text" size="10" name="krbarg" '.
                   3086:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3087:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3088:          '<label><input type="hidden" name="krbver" value="5" />',
                   3089:          '</label>');
                   3090:     }
1.32      matthew  3091:     return $result;
                   3092: }
                   3093: 
1.1075.2.20  raeburn  3094: sub authform_internal {
1.586     raeburn  3095:     my %in = (
1.32      matthew  3096:                 formname => 'document.cu',
                   3097:                 kerb_def_dom => 'MSU.EDU',
                   3098:                 @_,
                   3099:                 );
1.1075.2.117  raeburn  3100:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3101:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3102:     if ($in{'readonly'}) {
                   3103:         $disabled = ' disabled="disabled"';
                   3104:     }
1.591     raeburn  3105:     if (defined($in{'curr_authtype'})) {
                   3106:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3107:             if ($can_assign{'int'}) {
1.772     bisitz   3108:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3109:                 if (defined($in{'mode'})) {
                   3110:                     if ($in{'mode'} eq 'modifyuser') {
                   3111:                         $intcheck = '';
                   3112:                     }
                   3113:                 }
1.591     raeburn  3114:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3115:                     $intarg = $in{'curr_autharg'};
                   3116:                 }
                   3117:             } else {
                   3118:                 $result = &mt('Currently internally authenticated.');
                   3119:                 return $result;
1.165     raeburn  3120:             }
                   3121:         }
1.586     raeburn  3122:     } else {
                   3123:         if ($authnum == 1) {
1.784     bisitz   3124:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3125:         }
                   3126:     }
                   3127:     if (!$can_assign{'int'}) {
                   3128:         return;
1.587     raeburn  3129:     } elsif ($authtype eq '') {
1.591     raeburn  3130:         if (defined($in{'mode'})) {
1.587     raeburn  3131:             if ($in{'mode'} eq 'modifycourse') {
                   3132:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3133:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3134:                 }
                   3135:             }
                   3136:         }
1.165     raeburn  3137:     }
1.586     raeburn  3138:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3139:     if ($authtype eq '') {
                   3140:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3141:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3142:     }
1.605     bisitz   3143:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3144:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3145:     $result = &mt
1.144     matthew  3146:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3147:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3148:     $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  3149:     return $result;
                   3150: }
                   3151: 
1.1075.2.20  raeburn  3152: sub authform_local {
1.32      matthew  3153:     my %in = (
                   3154:               formname => 'document.cu',
                   3155:               kerb_def_dom => 'MSU.EDU',
                   3156:               @_,
                   3157:               );
1.1075.2.117  raeburn  3158:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3159:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3160:     if ($in{'readonly'}) {
                   3161:         $disabled = ' disabled="disabled"';
                   3162:     }
1.591     raeburn  3163:     if (defined($in{'curr_authtype'})) {
                   3164:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3165:             if ($can_assign{'loc'}) {
1.772     bisitz   3166:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3167:                 if (defined($in{'mode'})) {
                   3168:                     if ($in{'mode'} eq 'modifyuser') {
                   3169:                         $loccheck = '';
                   3170:                     }
                   3171:                 }
1.591     raeburn  3172:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3173:                     $locarg = $in{'curr_autharg'};
                   3174:                 }
                   3175:             } else {
                   3176:                 $result = &mt('Currently using local (institutional) authentication.');
                   3177:                 return $result;
1.165     raeburn  3178:             }
                   3179:         }
1.586     raeburn  3180:     } else {
                   3181:         if ($authnum == 1) {
1.784     bisitz   3182:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3183:         }
                   3184:     }
                   3185:     if (!$can_assign{'loc'}) {
                   3186:         return;
1.587     raeburn  3187:     } elsif ($authtype eq '') {
1.591     raeburn  3188:         if (defined($in{'mode'})) {
1.587     raeburn  3189:             if ($in{'mode'} eq 'modifycourse') {
                   3190:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3191:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3192:                 }
                   3193:             }
                   3194:         }
1.165     raeburn  3195:     }
1.586     raeburn  3196:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3197:     if ($authtype eq '') {
                   3198:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3199:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3200:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3201:     }
                   3202:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3203:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3204:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3205:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3206:     return $result;
                   3207: }
                   3208: 
1.1075.2.20  raeburn  3209: sub authform_filesystem {
1.32      matthew  3210:     my %in = (
                   3211:               formname => 'document.cu',
                   3212:               kerb_def_dom => 'MSU.EDU',
                   3213:               @_,
                   3214:               );
1.1075.2.117  raeburn  3215:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3216:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3217:     if ($in{'readonly'}) {
                   3218:         $disabled = ' disabled="disabled"';
                   3219:     }
1.591     raeburn  3220:     if (defined($in{'curr_authtype'})) {
                   3221:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3222:             if ($can_assign{'fsys'}) {
1.772     bisitz   3223:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3224:                 if (defined($in{'mode'})) {
                   3225:                     if ($in{'mode'} eq 'modifyuser') {
                   3226:                         $fsyscheck = '';
                   3227:                     }
                   3228:                 }
1.586     raeburn  3229:             } else {
                   3230:                 $result = &mt('Currently Filesystem Authenticated.');
                   3231:                 return $result;
                   3232:             }           
                   3233:         }
                   3234:     } else {
                   3235:         if ($authnum == 1) {
1.784     bisitz   3236:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3237:         }
                   3238:     }
                   3239:     if (!$can_assign{'fsys'}) {
                   3240:         return;
1.587     raeburn  3241:     } elsif ($authtype eq '') {
1.591     raeburn  3242:         if (defined($in{'mode'})) {
1.587     raeburn  3243:             if ($in{'mode'} eq 'modifycourse') {
                   3244:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3245:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3246:                 }
                   3247:             }
                   3248:         }
1.586     raeburn  3249:     }
                   3250:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3251:     if ($authtype eq '') {
                   3252:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3253:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3254:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3255:     }
1.1075.2.158  raeburn  3256:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3257:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3258:     $result = &mt
1.144     matthew  3259:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3260:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3261:     return $result;
                   3262: }
                   3263: 
1.1075.2.161.  .17(raeb 3264:-23): sub authform_lti {
                   3265:-23):     my %in = (
                   3266:-23):               formname => 'document.cu',
                   3267:-23):               kerb_def_dom => 'MSU.EDU',
                   3268:-23):               @_,
                   3269:-23):               );
                   3270:-23):     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3271:-23):     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3272:-23):     if ($in{'readonly'}) {
                   3273:-23):         $disabled = ' disabled="disabled"';
                   3274:-23):     }
                   3275:-23):     if (defined($in{'curr_authtype'})) {
                   3276:-23):         if ($in{'curr_authtype'} eq 'lti') {
                   3277:-23):             if ($can_assign{'lti'}) {
                   3278:-23):                 $lticheck = 'checked="checked" ';
                   3279:-23):                 if (defined($in{'mode'})) {
                   3280:-23):                     if ($in{'mode'} eq 'modifyuser') {
                   3281:-23):                         $lticheck = '';
                   3282:-23):                     }
                   3283:-23):                 }
                   3284:-23):             } else {
                   3285:-23):                 $result = &mt('Currently LTI Authenticated.');
                   3286:-23):                 return $result;
                   3287:-23):             }
                   3288:-23):         }
                   3289:-23):     } else {
                   3290:-23):         if ($authnum == 1) {
                   3291:-23):             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3292:-23):         }
                   3293:-23):     }
                   3294:-23):     if (!$can_assign{'lti'}) {
                   3295:-23):         return;
                   3296:-23):     } elsif ($authtype eq '') {
                   3297:-23):         if (defined($in{'mode'})) {
                   3298:-23):             if ($in{'mode'} eq 'modifycourse') {
                   3299:-23):                 if ($authnum == 1) {
                   3300:-23):                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3301:-23):                 }
                   3302:-23):             }
                   3303:-23):         }
                   3304:-23):     }
                   3305:-23):     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3306:-23):     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3307:-23):         $authtype = '<input type="radio" name="login" value="lti" '.
                   3308:-23):                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3309:-23):                     $jscall.'"'.$disabled.' />';
                   3310:-23):     }
                   3311:-23):     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3312:-23):     if ($authtype) {
                   3313:-23):         $result = &mt('[_1] LTI Authenticated',
                   3314:-23):                       '<label>'.$authtype.'</label>'.$autharg);
                   3315:-23):     } else {
                   3316:-23):         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3317:-23):                   $autharg;
                   3318:-23):     }
                   3319:-23):     return $result;
                   3320:-23): }
                   3321:-23): 
1.586     raeburn  3322: sub get_assignable_auth {
                   3323:     my ($dom) = @_;
                   3324:     if ($dom eq '') {
                   3325:         $dom = $env{'request.role.domain'};
                   3326:     }
                   3327:     my %can_assign = (
                   3328:                           krb4 => 1,
                   3329:                           krb5 => 1,
                   3330:                           int  => 1,
                   3331:                           loc  => 1,
                   3332:                      );
                   3333:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3334:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3335:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3336:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3337:             my $context;
                   3338:             if ($env{'request.role'} =~ /^au/) {
                   3339:                 $context = 'author';
1.1075.2.117  raeburn  3340:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3341:                 $context = 'domain';
                   3342:             } elsif ($env{'request.course.id'}) {
                   3343:                 $context = 'course';
                   3344:             }
                   3345:             if ($context) {
                   3346:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3347:                    %can_assign = %{$authhash->{$context}}; 
                   3348:                 }
                   3349:             }
                   3350:         }
                   3351:     }
                   3352:     my $authnum = 0;
                   3353:     foreach my $key (keys(%can_assign)) {
                   3354:         if ($can_assign{$key}) {
                   3355:             $authnum ++;
                   3356:         }
                   3357:     }
                   3358:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3359:         $authnum --;
                   3360:     }
                   3361:     return ($authnum,%can_assign);
                   3362: }
                   3363: 
1.1075.2.137  raeburn  3364: sub check_passwd_rules {
                   3365:     my ($domain,$plainpass) = @_;
                   3366:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3367:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3368:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3369:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3370:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3371:             if ($passwdconf{'min'} > $min) {
                   3372:                 $min = $passwdconf{'min'};
                   3373:             }
1.1075.2.137  raeburn  3374:         }
                   3375:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3376:             $max = $passwdconf{'max'};
                   3377:         }
                   3378:         @chars = @{$passwdconf{'chars'}};
                   3379:     }
                   3380:     if (($min) && (length($plainpass) < $min)) {
                   3381:         push(@brokerule,'min');
                   3382:     }
                   3383:     if (($max) && (length($plainpass) > $max)) {
                   3384:         push(@brokerule,'max');
                   3385:     }
                   3386:     if (@chars) {
                   3387:         my %rules;
                   3388:         map { $rules{$_} = 1; } @chars;
                   3389:         if ($rules{'uc'}) {
                   3390:             unless ($plainpass =~ /[A-Z]/) {
                   3391:                 push(@brokerule,'uc');
                   3392:             }
                   3393:         }
                   3394:         if ($rules{'lc'}) {
                   3395:             unless ($plainpass =~ /[a-z]/) {
                   3396:                 push(@brokerule,'lc');
                   3397:             }
                   3398:         }
                   3399:         if ($rules{'num'}) {
                   3400:             unless ($plainpass =~ /\d/) {
                   3401:                 push(@brokerule,'num');
                   3402:             }
                   3403:         }
                   3404:         if ($rules{'spec'}) {
                   3405:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3406:                 push(@brokerule,'spec');
                   3407:             }
                   3408:         }
                   3409:     }
                   3410:     if (@brokerule) {
                   3411:         my %rulenames = &Apache::lonlocal::texthash(
                   3412:             uc   => 'At least one upper case letter',
                   3413:             lc   => 'At least one lower case letter',
                   3414:             num  => 'At least one number',
                   3415:             spec => 'At least one non-alphanumeric',
                   3416:         );
                   3417:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3418:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3419:         $rulenames{'num'} .= ': 0123456789';
                   3420:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3421:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3422:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3423:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3424:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3425:             if (grep(/^$rule$/,@brokerule)) {
                   3426:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3427:             }
                   3428:         }
                   3429:         $warning .= '</ul>';
                   3430:     }
                   3431:     if (wantarray) {
                   3432:         return @brokerule;
                   3433:     }
                   3434:     return $warning;
                   3435: }
                   3436: 
1.1075.2.161.  .5(raebu 3437:22): sub passwd_validation_js {
                   3438:22):     my ($currpasswdval,$domain,$context,$id) = @_;
                   3439:22):     my (%passwdconf,$alertmsg);
                   3440:22):     if ($context eq 'linkprot') {
                   3441:22):         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3442:22):         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3443:22):             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3444:22):                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3445:22):             }
                   3446:22):         }
                   3447:22):         if ($id eq 'add') {
                   3448:22):             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3449:22):         } elsif ($id =~ /^\d+$/) {
                   3450:22):             my $pos = $id+1;
                   3451:22):             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3452:22):         } else {
                   3453:22):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3454:22):         }
          .27(raeb 3455:-24):     } elsif ($context eq 'ltitools') {
                   3456:-24):         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3457:-24):         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3458:-24):             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3459:-24):                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3460:-24):             }
                   3461:-24):         }
                   3462:-24):         if ($id eq 'add') {
                   3463:-24):             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3464:-24):         } elsif ($id =~ /^\d+$/) {
                   3465:-24):             my $pos = $id+1;
                   3466:-24):             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3467:-24):         } else {
                   3468:-24):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3469:-24):         }
          .5(raebu 3470:22):     } else {
                   3471:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3472:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3473:22):     }
                   3474:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3475:22):     $numrules = 0;
                   3476:22):     $min = $Apache::lonnet::passwdmin;
                   3477:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3478:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3479:22):             if ($passwdconf{'min'} > $min) {
                   3480:22):                 $min = $passwdconf{'min'};
                   3481:22):             }
                   3482:22):         }
                   3483:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3484:22):             $max = $passwdconf{'max'};
                   3485:22):             $numrules ++;
                   3486:22):         }
                   3487:22):         @chars = @{$passwdconf{'chars'}};
                   3488:22):         if (@chars) {
                   3489:22):             $numrules ++;
                   3490:22):         }
                   3491:22):     }
                   3492:22):     if ($min > 0) {
                   3493:22):         $numrules ++;
                   3494:22):     }
                   3495:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3496:22):         if ($min) {
                   3497:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3498:22):         }
                   3499:22):         if ($max) {
                   3500:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3501:22):         }
                   3502:22):         my (@charalerts,@charrules);
                   3503:22):         if (@chars) {
                   3504:22):             if (grep(/^uc$/,@chars)) {
                   3505:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3506:22):                 push(@charrules,'uc');
                   3507:22):             }
                   3508:22):             if (grep(/^lc$/,@chars)) {
                   3509:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3510:22):                 push(@charrules,'lc');
                   3511:22):             }
                   3512:22):             if (grep(/^num$/,@chars)) {
                   3513:22):                 push(@charalerts,&mt('contain at least one number'));
                   3514:22):                 push(@charrules,'num');
                   3515:22):             }
                   3516:22):             if (grep(/^spec$/,@chars)) {
                   3517:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3518:22):                 push(@charrules,'spec');
                   3519:22):             }
                   3520:22):         }
                   3521:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3522:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3523:22):             if ($min) {
                   3524:22):                 $intargjs .= qq|
                   3525:22):             if (currpwval.length < $min) {
                   3526:22):                 rulesmsg += ' - $alert{min}';
                   3527:22):             }
                   3528:22): |;
                   3529:22):             }
                   3530:22):             if ($max) {
                   3531:22):                 $intargjs .= qq|
                   3532:22):             if (currpwval.length > $max) {
                   3533:22):                 rulesmsg += ' - $alert{max}';
                   3534:22):             }
                   3535:22): |;
                   3536:22):             }
                   3537:22):             if (@chars > 0) {
                   3538:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3539:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3540:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3541:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3542:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3543:22):                 my %rules;
                   3544:22):                 map { $rules{$_} = 1; } @chars;
                   3545:22):                 if ($rules{'uc'}) {
                   3546:22):                     $intargjs .= qq|
                   3547:22):             var ucRegExp = /[A-Z]/;
                   3548:22):             if (!ucRegExp.test(currpwval)) {
                   3549:22):                 brokerules.push('uc');
                   3550:22):             }
                   3551:22): |;
                   3552:22):                 }
                   3553:22):                 if ($rules{'lc'}) {
                   3554:22):                     $intargjs .= qq|
                   3555:22):             var lcRegExp = /[a-z]/;
                   3556:22):             if (!lcRegExp.test(currpwval)) {
                   3557:22):                 brokerules.push('lc');
                   3558:22):             }
                   3559:22): |;
                   3560:22):                 }
                   3561:22):                 if ($rules{'num'}) {
                   3562:22):                      $intargjs .= qq|
                   3563:22):             var numRegExp = /[0-9]/;
                   3564:22):             if (!numRegExp.test(currpwval)) {
                   3565:22):                 brokerules.push('num');
                   3566:22):             }
                   3567:22): |;
                   3568:22):                 }
                   3569:22):                 if ($rules{'spec'}) {
                   3570:22):                      $intargjs .= q|
                   3571:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3572:22):             if (!specRegExp.test(currpwval)) {
                   3573:22):                 brokerules.push('spec');
                   3574:22):             }
                   3575:22): |;
                   3576:22):                 }
                   3577:22):                 $intargjs .= qq|
                   3578:22):             if (brokerules.length > 0) {
                   3579:22):                 for (var i=0; i<brokerules.length; i++) {
                   3580:22):                     for (var j=0; j<charrules.length; j++) {
                   3581:22):                         if (brokerules[i] == charrules[j]) {
                   3582:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3583:22):                             break;
                   3584:22):                         }
                   3585:22):                     }
                   3586:22):                 }
                   3587:22):             }
                   3588:22): |;
                   3589:22):             }
                   3590:22):             $intargjs .= qq|
                   3591:22):             if (rulesmsg != '') {
                   3592:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3593:22):                 alert(rulesmsg);
                   3594:22):                 return false;
                   3595:22):             }
                   3596:22): |;
                   3597:22):     }
                   3598:22):     return ($numrules,$intargjs);
                   3599:22): }
                   3600:22): 
1.80      albertel 3601: ###############################################################
                   3602: ##    Get Kerberos Defaults for Domain                 ##
                   3603: ###############################################################
                   3604: ##
                   3605: ## Returns default kerberos version and an associated argument
                   3606: ## as listed in file domain.tab. If not listed, provides
                   3607: ## appropriate default domain and kerberos version.
                   3608: ##
                   3609: #-------------------------------------------
                   3610: 
                   3611: =pod
                   3612: 
1.648     raeburn  3613: =item * &get_kerberos_defaults()
1.80      albertel 3614: 
                   3615: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3616: version and domain. If not found, it defaults to version 4 and the 
                   3617: domain of the server.
1.80      albertel 3618: 
1.648     raeburn  3619: =over 4
                   3620: 
1.80      albertel 3621: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3622: 
1.648     raeburn  3623: =back
                   3624: 
                   3625: =back
                   3626: 
1.80      albertel 3627: =cut
                   3628: 
                   3629: #-------------------------------------------
                   3630: sub get_kerberos_defaults {
                   3631:     my $domain=shift;
1.641     raeburn  3632:     my ($krbdef,$krbdefdom);
                   3633:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3634:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3635:         $krbdef = $domdefaults{'auth_def'};
                   3636:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3637:     } else {
1.80      albertel 3638:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3639:         my $krbdefdom=$1;
                   3640:         $krbdefdom=~tr/a-z/A-Z/;
                   3641:         $krbdef = "krb4";
                   3642:     }
                   3643:     return ($krbdef,$krbdefdom);
                   3644: }
1.112     bowersj2 3645: 
1.32      matthew  3646: 
1.46      matthew  3647: ###############################################################
                   3648: ##                Thesaurus Functions                        ##
                   3649: ###############################################################
1.20      www      3650: 
1.46      matthew  3651: =pod
1.20      www      3652: 
1.112     bowersj2 3653: =head1 Thesaurus Functions
                   3654: 
                   3655: =over 4
                   3656: 
1.648     raeburn  3657: =item * &initialize_keywords()
1.46      matthew  3658: 
                   3659: Initializes the package variable %Keywords if it is empty.  Uses the
                   3660: package variable $thesaurus_db_file.
                   3661: 
                   3662: =cut
                   3663: 
                   3664: ###################################################
                   3665: 
                   3666: sub initialize_keywords {
                   3667:     return 1 if (scalar keys(%Keywords));
                   3668:     # If we are here, %Keywords is empty, so fill it up
                   3669:     #   Make sure the file we need exists...
                   3670:     if (! -e $thesaurus_db_file) {
                   3671:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3672:                                  " failed because it does not exist");
                   3673:         return 0;
                   3674:     }
                   3675:     #   Set up the hash as a database
                   3676:     my %thesaurus_db;
                   3677:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3678:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3679:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3680:                                  $thesaurus_db_file);
                   3681:         return 0;
                   3682:     } 
                   3683:     #  Get the average number of appearances of a word.
                   3684:     my $avecount = $thesaurus_db{'average.count'};
                   3685:     #  Put keywords (those that appear > average) into %Keywords
                   3686:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3687:         my ($count,undef) = split /:/,$data;
                   3688:         $Keywords{$word}++ if ($count > $avecount);
                   3689:     }
                   3690:     untie %thesaurus_db;
                   3691:     # Remove special values from %Keywords.
1.356     albertel 3692:     foreach my $value ('total.count','average.count') {
                   3693:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3694:   }
1.46      matthew  3695:     return 1;
                   3696: }
                   3697: 
                   3698: ###################################################
                   3699: 
                   3700: =pod
                   3701: 
1.648     raeburn  3702: =item * &keyword($word)
1.46      matthew  3703: 
                   3704: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3705: than the average number of times in the thesaurus database.  Calls 
                   3706: &initialize_keywords
                   3707: 
                   3708: =cut
                   3709: 
                   3710: ###################################################
1.20      www      3711: 
                   3712: sub keyword {
1.46      matthew  3713:     return if (!&initialize_keywords());
                   3714:     my $word=lc(shift());
                   3715:     $word=~s/\W//g;
                   3716:     return exists($Keywords{$word});
1.20      www      3717: }
1.46      matthew  3718: 
                   3719: ###############################################################
                   3720: 
                   3721: =pod 
1.20      www      3722: 
1.648     raeburn  3723: =item * &get_related_words()
1.46      matthew  3724: 
1.160     matthew  3725: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3726: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3727: will be returned.  The order of the words returned is determined by the
                   3728: database which holds them.
                   3729: 
                   3730: Uses global $thesaurus_db_file.
                   3731: 
1.1057    foxr     3732: 
1.46      matthew  3733: =cut
                   3734: 
                   3735: ###############################################################
                   3736: sub get_related_words {
                   3737:     my $keyword = shift;
                   3738:     my %thesaurus_db;
                   3739:     if (! -e $thesaurus_db_file) {
                   3740:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3741:                                  "failed because the file does not exist");
                   3742:         return ();
                   3743:     }
                   3744:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3745:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3746:         return ();
                   3747:     } 
                   3748:     my @Words=();
1.429     www      3749:     my $count=0;
1.46      matthew  3750:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3751: 	# The first element is the number of times
                   3752: 	# the word appears.  We do not need it now.
1.429     www      3753: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3754: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3755: 	my $threshold=$mostfrequentcount/10;
                   3756:         foreach my $possibleword (@RelatedWords) {
                   3757:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3758:             if ($wordcount>$threshold) {
                   3759: 		push(@Words,$word);
                   3760:                 $count++;
                   3761:                 if ($count>10) { last; }
                   3762: 	    }
1.20      www      3763:         }
                   3764:     }
1.46      matthew  3765:     untie %thesaurus_db;
                   3766:     return @Words;
1.14      harris41 3767: }
1.46      matthew  3768: 
1.112     bowersj2 3769: =pod
                   3770: 
                   3771: =back
                   3772: 
                   3773: =cut
1.61      www      3774: 
                   3775: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3776: =pod
                   3777: 
1.112     bowersj2 3778: =head1 User Name Functions
                   3779: 
                   3780: =over 4
                   3781: 
1.648     raeburn  3782: =item * &plainname($uname,$udom,$first)
1.81      albertel 3783: 
1.112     bowersj2 3784: Takes a users logon name and returns it as a string in
1.226     albertel 3785: "first middle last generation" form 
                   3786: if $first is set to 'lastname' then it returns it as
                   3787: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3788: 
                   3789: =cut
1.61      www      3790: 
1.295     www      3791: 
1.81      albertel 3792: ###############################################################
1.61      www      3793: sub plainname {
1.226     albertel 3794:     my ($uname,$udom,$first)=@_;
1.537     albertel 3795:     return if (!defined($uname) || !defined($udom));
1.295     www      3796:     my %names=&getnames($uname,$udom);
1.226     albertel 3797:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3798: 					  $names{'middlename'},
                   3799: 					  $names{'lastname'},
                   3800: 					  $names{'generation'},$first);
                   3801:     $name=~s/^\s+//;
1.62      www      3802:     $name=~s/\s+$//;
                   3803:     $name=~s/\s+/ /g;
1.353     albertel 3804:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3805:     return $name;
1.61      www      3806: }
1.66      www      3807: 
                   3808: # -------------------------------------------------------------------- Nickname
1.81      albertel 3809: =pod
                   3810: 
1.648     raeburn  3811: =item * &nickname($uname,$udom)
1.81      albertel 3812: 
                   3813: Gets a users name and returns it as a string as
                   3814: 
                   3815: "&quot;nickname&quot;"
1.66      www      3816: 
1.81      albertel 3817: if the user has a nickname or
                   3818: 
                   3819: "first middle last generation"
                   3820: 
                   3821: if the user does not
                   3822: 
                   3823: =cut
1.66      www      3824: 
                   3825: sub nickname {
                   3826:     my ($uname,$udom)=@_;
1.537     albertel 3827:     return if (!defined($uname) || !defined($udom));
1.295     www      3828:     my %names=&getnames($uname,$udom);
1.68      albertel 3829:     my $name=$names{'nickname'};
1.66      www      3830:     if ($name) {
                   3831:        $name='&quot;'.$name.'&quot;'; 
                   3832:     } else {
                   3833:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3834: 	     $names{'lastname'}.' '.$names{'generation'};
                   3835:        $name=~s/\s+$//;
                   3836:        $name=~s/\s+/ /g;
                   3837:     }
                   3838:     return $name;
                   3839: }
                   3840: 
1.295     www      3841: sub getnames {
                   3842:     my ($uname,$udom)=@_;
1.537     albertel 3843:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3844:     if ($udom eq 'public' && $uname eq 'public') {
                   3845: 	return ('lastname' => &mt('Public'));
                   3846:     }
1.295     www      3847:     my $id=$uname.':'.$udom;
                   3848:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3849:     if ($cached) {
                   3850: 	return %{$names};
                   3851:     } else {
                   3852: 	my %loadnames=&Apache::lonnet::get('environment',
                   3853:                     ['firstname','middlename','lastname','generation','nickname'],
                   3854: 					 $udom,$uname);
                   3855: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3856: 	return %loadnames;
                   3857:     }
                   3858: }
1.61      www      3859: 
1.542     raeburn  3860: # -------------------------------------------------------------------- getemails
1.648     raeburn  3861: 
1.542     raeburn  3862: =pod
                   3863: 
1.648     raeburn  3864: =item * &getemails($uname,$udom)
1.542     raeburn  3865: 
                   3866: Gets a user's email information and returns it as a hash with keys:
                   3867: notification, critnotification, permanentemail
                   3868: 
                   3869: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3870: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3871:  
1.648     raeburn  3872: 
1.542     raeburn  3873: =cut
                   3874: 
1.648     raeburn  3875: 
1.466     albertel 3876: sub getemails {
                   3877:     my ($uname,$udom)=@_;
                   3878:     if ($udom eq 'public' && $uname eq 'public') {
                   3879: 	return;
                   3880:     }
1.467     www      3881:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3882:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3883:     my $id=$uname.':'.$udom;
                   3884:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3885:     if ($cached) {
                   3886: 	return %{$names};
                   3887:     } else {
                   3888: 	my %loadnames=&Apache::lonnet::get('environment',
                   3889:                     			   ['notification','critnotification',
                   3890: 					    'permanentemail'],
                   3891: 					   $udom,$uname);
                   3892: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3893: 	return %loadnames;
                   3894:     }
                   3895: }
                   3896: 
1.551     albertel 3897: sub flush_email_cache {
                   3898:     my ($uname,$udom)=@_;
                   3899:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3900:     if (!$uname) { $uname=$env{'user.name'};   }
                   3901:     return if ($udom eq 'public' && $uname eq 'public');
                   3902:     my $id=$uname.':'.$udom;
                   3903:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3904: }
                   3905: 
1.728     raeburn  3906: # -------------------------------------------------------------------- getlangs
                   3907: 
                   3908: =pod
                   3909: 
                   3910: =item * &getlangs($uname,$udom)
                   3911: 
                   3912: Gets a user's language preference and returns it as a hash with key:
                   3913: language.
                   3914: 
                   3915: =cut
                   3916: 
                   3917: 
                   3918: sub getlangs {
                   3919:     my ($uname,$udom) = @_;
                   3920:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3921:     if (!$uname) { $uname=$env{'user.name'};   }
                   3922:     my $id=$uname.':'.$udom;
                   3923:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3924:     if ($cached) {
                   3925:         return %{$langs};
                   3926:     } else {
                   3927:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3928:                                            $udom,$uname);
                   3929:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3930:         return %loadlangs;
                   3931:     }
                   3932: }
                   3933: 
                   3934: sub flush_langs_cache {
                   3935:     my ($uname,$udom)=@_;
                   3936:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3937:     if (!$uname) { $uname=$env{'user.name'};   }
                   3938:     return if ($udom eq 'public' && $uname eq 'public');
                   3939:     my $id=$uname.':'.$udom;
                   3940:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3941: }
                   3942: 
1.61      www      3943: # ------------------------------------------------------------------ Screenname
1.81      albertel 3944: 
                   3945: =pod
                   3946: 
1.648     raeburn  3947: =item * &screenname($uname,$udom)
1.81      albertel 3948: 
                   3949: Gets a users screenname and returns it as a string
                   3950: 
                   3951: =cut
1.61      www      3952: 
                   3953: sub screenname {
                   3954:     my ($uname,$udom)=@_;
1.258     albertel 3955:     if ($uname eq $env{'user.name'} &&
                   3956: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3957:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3958:     return $names{'screenname'};
1.62      www      3959: }
                   3960: 
1.212     albertel 3961: 
1.802     bisitz   3962: # ------------------------------------------------------------- Confirm Wrapper
                   3963: =pod
                   3964: 
1.1075.2.42  raeburn  3965: =item * &confirmwrapper($message)
1.802     bisitz   3966: 
                   3967: Wrap messages about completion of operation in box
                   3968: 
                   3969: =cut
                   3970: 
                   3971: sub confirmwrapper {
                   3972:     my ($message)=@_;
                   3973:     if ($message) {
                   3974:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3975:                .$message."\n"
                   3976:                .'</div>'."\n";
                   3977:     } else {
                   3978:         return $message;
                   3979:     }
                   3980: }
                   3981: 
1.62      www      3982: # ------------------------------------------------------------- Message Wrapper
                   3983: 
                   3984: sub messagewrapper {
1.369     www      3985:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3986:     return 
1.441     albertel 3987:         '<a href="/adm/email?compose=individual&amp;'.
                   3988:         'recname='.$username.'&amp;recdom='.$domain.
                   3989: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3990:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3991: }
1.802     bisitz   3992: 
1.74      www      3993: # --------------------------------------------------------------- Notes Wrapper
                   3994: 
                   3995: sub noteswrapper {
                   3996:     my ($link,$un,$do)=@_;
                   3997:     return 
1.896     amueller 3998: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3999: }
1.802     bisitz   4000: 
1.62      www      4001: # ------------------------------------------------------------- Aboutme Wrapper
                   4002: 
                   4003: sub aboutmewrapper {
1.1070    raeburn  4004:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4005:     if (!defined($username)  && !defined($domain)) {
                   4006:         return;
                   4007:     }
1.1075.2.15  raeburn  4008:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4009: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4010: }
                   4011: 
                   4012: # ------------------------------------------------------------ Syllabus Wrapper
                   4013: 
                   4014: sub syllabuswrapper {
1.707     bisitz   4015:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4016:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4017: }
1.14      harris41 4018: 
1.1075.2.161.  .11(raeb 4019:-22): sub aboutme_on {
                   4020:-22):     my ($uname,$udom)=@_;
                   4021:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   4022:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4023:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4024:-22):     my $hashkey=$uname.':'.$udom;
                   4025:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4026:-22):     if ($cached) {
                   4027:-22):         return $aboutme;
                   4028:-22):     }
                   4029:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4030:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4031:-22):     return $aboutme;
                   4032:-22): }
                   4033:-22): 
                   4034:-22): sub devalidate_aboutme_cache {
                   4035:-22):     my ($uname,$udom)=@_;
                   4036:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4037:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   4038:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4039:-22):     my $id=$uname.':'.$udom;
                   4040:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4041:-22): }
                   4042:-22): 
1.802     bisitz   4043: # -----------------------------------------------------------------------------
                   4044: 
1.208     matthew  4045: sub track_student_link {
1.887     raeburn  4046:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4047:     my $link ="/adm/trackstudent?";
1.208     matthew  4048:     my $title = 'View recent activity';
                   4049:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4050:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4051:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4052:         $title .= ' of this student';
1.268     albertel 4053:     } 
1.208     matthew  4054:     if (defined($target) && $target !~ /^\s*$/) {
                   4055:         $target = qq{target="$target"};
                   4056:     } else {
                   4057:         $target = '';
                   4058:     }
1.268     albertel 4059:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4060:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4061:     $title = &mt($title);
                   4062:     $linktext = &mt($linktext);
1.448     albertel 4063:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4064: 	&help_open_topic('View_recent_activity');
1.208     matthew  4065: }
                   4066: 
1.781     raeburn  4067: sub slot_reservations_link {
                   4068:     my ($linktext,$sname,$sdom,$target) = @_;
                   4069:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4070:     my $title = 'View slot reservation history';
                   4071:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4072:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4073:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4074:         $title .= ' of this student';
                   4075:     }
                   4076:     if (defined($target) && $target !~ /^\s*$/) {
                   4077:         $target = qq{target="$target"};
                   4078:     } else {
                   4079:         $target = '';
                   4080:     }
                   4081:     $title = &mt($title);
                   4082:     $linktext = &mt($linktext);
                   4083:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4084: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4085: 
                   4086: }
                   4087: 
1.508     www      4088: # ===================================================== Display a student photo
                   4089: 
                   4090: 
1.509     albertel 4091: sub student_image_tag {
1.508     www      4092:     my ($domain,$user)=@_;
                   4093:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4094:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4095: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4096:     } else {
                   4097: 	return '';
                   4098:     }
                   4099: }
                   4100: 
1.112     bowersj2 4101: =pod
                   4102: 
                   4103: =back
                   4104: 
                   4105: =head1 Access .tab File Data
                   4106: 
                   4107: =over 4
                   4108: 
1.648     raeburn  4109: =item * &languageids() 
1.112     bowersj2 4110: 
                   4111: returns list of all language ids
                   4112: 
                   4113: =cut
                   4114: 
1.14      harris41 4115: sub languageids {
1.16      harris41 4116:     return sort(keys(%language));
1.14      harris41 4117: }
                   4118: 
1.112     bowersj2 4119: =pod
                   4120: 
1.648     raeburn  4121: =item * &languagedescription() 
1.112     bowersj2 4122: 
                   4123: returns description of a specified language id
                   4124: 
                   4125: =cut
                   4126: 
1.14      harris41 4127: sub languagedescription {
1.125     www      4128:     my $code=shift;
                   4129:     return  ($supported_language{$code}?'* ':'').
                   4130:             $language{$code}.
1.126     www      4131: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4132: }
                   4133: 
1.1048    foxr     4134: =pod
                   4135: 
                   4136: =item * &plainlanguagedescription
                   4137: 
                   4138: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4139: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4140: 
                   4141: =cut
                   4142: 
1.145     www      4143: sub plainlanguagedescription {
                   4144:     my $code=shift;
                   4145:     return $language{$code};
                   4146: }
                   4147: 
1.1048    foxr     4148: =pod
                   4149: 
                   4150: =item * &supportedlanguagecode
                   4151: 
                   4152: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4153: code.
                   4154: 
                   4155: =cut
                   4156: 
1.145     www      4157: sub supportedlanguagecode {
                   4158:     my $code=shift;
                   4159:     return $supported_language{$code};
1.97      www      4160: }
                   4161: 
1.112     bowersj2 4162: =pod
                   4163: 
1.1048    foxr     4164: =item * &latexlanguage()
                   4165: 
                   4166: Given a language key code returns the correspondnig language to use
                   4167: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4168: is no supported hyphenation for the language code.
                   4169: 
                   4170: =cut
                   4171: 
                   4172: sub latexlanguage {
                   4173:     my $code = shift;
                   4174:     return $latex_language{$code};
                   4175: }
                   4176: 
                   4177: =pod
                   4178: 
                   4179: =item * &latexhyphenation()
                   4180: 
                   4181: Same as above but what's supplied is the language as it might be stored
                   4182: in the metadata.
                   4183: 
                   4184: =cut
                   4185: 
                   4186: sub latexhyphenation {
                   4187:     my $key = shift;
                   4188:     return $latex_language_bykey{$key};
                   4189: }
                   4190: 
                   4191: =pod
                   4192: 
1.648     raeburn  4193: =item * &copyrightids() 
1.112     bowersj2 4194: 
                   4195: returns list of all copyrights
                   4196: 
                   4197: =cut
                   4198: 
                   4199: sub copyrightids {
                   4200:     return sort(keys(%cprtag));
                   4201: }
                   4202: 
                   4203: =pod
                   4204: 
1.648     raeburn  4205: =item * &copyrightdescription() 
1.112     bowersj2 4206: 
                   4207: returns description of a specified copyright id
                   4208: 
                   4209: =cut
                   4210: 
                   4211: sub copyrightdescription {
1.166     www      4212:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4213: }
1.197     matthew  4214: 
                   4215: =pod
                   4216: 
1.648     raeburn  4217: =item * &source_copyrightids() 
1.192     taceyjo1 4218: 
                   4219: returns list of all source copyrights
                   4220: 
                   4221: =cut
                   4222: 
                   4223: sub source_copyrightids {
                   4224:     return sort(keys(%scprtag));
                   4225: }
                   4226: 
                   4227: =pod
                   4228: 
1.648     raeburn  4229: =item * &source_copyrightdescription() 
1.192     taceyjo1 4230: 
                   4231: returns description of a specified source copyright id
                   4232: 
                   4233: =cut
                   4234: 
                   4235: sub source_copyrightdescription {
                   4236:     return &mt($scprtag{shift(@_)});
                   4237: }
1.112     bowersj2 4238: 
                   4239: =pod
                   4240: 
1.648     raeburn  4241: =item * &filecategories() 
1.112     bowersj2 4242: 
                   4243: returns list of all file categories
                   4244: 
                   4245: =cut
                   4246: 
                   4247: sub filecategories {
                   4248:     return sort(keys(%category_extensions));
                   4249: }
                   4250: 
                   4251: =pod
                   4252: 
1.648     raeburn  4253: =item * &filecategorytypes() 
1.112     bowersj2 4254: 
                   4255: returns list of file types belonging to a given file
                   4256: category
                   4257: 
                   4258: =cut
                   4259: 
                   4260: sub filecategorytypes {
1.356     albertel 4261:     my ($cat) = @_;
                   4262:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4263: }
                   4264: 
                   4265: =pod
                   4266: 
1.648     raeburn  4267: =item * &fileembstyle() 
1.112     bowersj2 4268: 
                   4269: returns embedding style for a specified file type
                   4270: 
                   4271: =cut
                   4272: 
                   4273: sub fileembstyle {
                   4274:     return $fe{lc(shift(@_))};
1.169     www      4275: }
                   4276: 
1.351     www      4277: sub filemimetype {
                   4278:     return $fm{lc(shift(@_))};
                   4279: }
                   4280: 
1.169     www      4281: 
                   4282: sub filecategoryselect {
                   4283:     my ($name,$value)=@_;
1.189     matthew  4284:     return &select_form($value,$name,
1.970     raeburn  4285:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4286: }
                   4287: 
                   4288: =pod
                   4289: 
1.648     raeburn  4290: =item * &filedescription() 
1.112     bowersj2 4291: 
                   4292: returns description for a specified file type
                   4293: 
                   4294: =cut
                   4295: 
                   4296: sub filedescription {
1.188     matthew  4297:     my $file_description = $fd{lc(shift())};
                   4298:     $file_description =~ s:([\[\]]):~$1:g;
                   4299:     return &mt($file_description);
1.112     bowersj2 4300: }
                   4301: 
                   4302: =pod
                   4303: 
1.648     raeburn  4304: =item * &filedescriptionex() 
1.112     bowersj2 4305: 
                   4306: returns description for a specified file type with
                   4307: extra formatting
                   4308: 
                   4309: =cut
                   4310: 
                   4311: sub filedescriptionex {
                   4312:     my $ex=shift;
1.188     matthew  4313:     my $file_description = $fd{lc($ex)};
                   4314:     $file_description =~ s:([\[\]]):~$1:g;
                   4315:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4316: }
                   4317: 
                   4318: # End of .tab access
                   4319: =pod
                   4320: 
                   4321: =back
                   4322: 
                   4323: =cut
                   4324: 
                   4325: # ------------------------------------------------------------------ File Types
                   4326: sub fileextensions {
                   4327:     return sort(keys(%fe));
                   4328: }
                   4329: 
1.97      www      4330: # ----------------------------------------------------------- Display Languages
                   4331: # returns a hash with all desired display languages
                   4332: #
                   4333: 
                   4334: sub display_languages {
                   4335:     my %languages=();
1.695     raeburn  4336:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4337: 	$languages{$lang}=1;
1.97      www      4338:     }
                   4339:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4340:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4341: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4342: 	    $languages{$lang}=1;
1.97      www      4343:         }
                   4344:     }
                   4345:     return %languages;
1.14      harris41 4346: }
                   4347: 
1.582     albertel 4348: sub languages {
                   4349:     my ($possible_langs) = @_;
1.695     raeburn  4350:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4351:     if (!ref($possible_langs)) {
                   4352: 	if( wantarray ) {
                   4353: 	    return @preferred_langs;
                   4354: 	} else {
                   4355: 	    return $preferred_langs[0];
                   4356: 	}
                   4357:     }
                   4358:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4359:     my @preferred_possibilities;
                   4360:     foreach my $preferred_lang (@preferred_langs) {
                   4361: 	if (exists($possibilities{$preferred_lang})) {
                   4362: 	    push(@preferred_possibilities, $preferred_lang);
                   4363: 	}
                   4364:     }
                   4365:     if( wantarray ) {
                   4366: 	return @preferred_possibilities;
                   4367:     }
                   4368:     return $preferred_possibilities[0];
                   4369: }
                   4370: 
1.742     raeburn  4371: sub user_lang {
                   4372:     my ($touname,$toudom,$fromcid) = @_;
                   4373:     my @userlangs;
                   4374:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4375:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4376:                     $env{'course.'.$fromcid.'.languages'}));
                   4377:     } else {
                   4378:         my %langhash = &getlangs($touname,$toudom);
                   4379:         if ($langhash{'languages'} ne '') {
                   4380:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4381:         } else {
                   4382:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4383:             if ($domdefs{'lang_def'} ne '') {
                   4384:                 @userlangs = ($domdefs{'lang_def'});
                   4385:             }
                   4386:         }
                   4387:     }
                   4388:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4389:     my $user_lh = Apache::localize->get_handle(@languages);
                   4390:     return $user_lh;
                   4391: }
                   4392: 
                   4393: 
1.112     bowersj2 4394: ###############################################################
                   4395: ##               Student Answer Attempts                     ##
                   4396: ###############################################################
                   4397: 
                   4398: =pod
                   4399: 
                   4400: =head1 Alternate Problem Views
                   4401: 
                   4402: =over 4
                   4403: 
1.648     raeburn  4404: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4405:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4406: 
                   4407: Return string with previous attempt on problem. Arguments:
                   4408: 
                   4409: =over 4
                   4410: 
                   4411: =item * $symb: Problem, including path
                   4412: 
                   4413: =item * $username: username of the desired student
                   4414: 
                   4415: =item * $domain: domain of the desired student
1.14      harris41 4416: 
1.112     bowersj2 4417: =item * $course: Course ID
1.14      harris41 4418: 
1.112     bowersj2 4419: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4420:     something
1.14      harris41 4421: 
1.112     bowersj2 4422: =item * $regexp: if string matches this regexp, the string will be
                   4423:     sent to $gradesub
1.14      harris41 4424: 
1.112     bowersj2 4425: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4426: 
1.1075.2.86  raeburn  4427: =item * $usec: section of the desired student
                   4428: 
                   4429: =item * $identifier: counter for student (multiple students one problem) or
                   4430:     problem (one student; whole sequence).
                   4431: 
1.112     bowersj2 4432: =back
1.14      harris41 4433: 
1.112     bowersj2 4434: The output string is a table containing all desired attempts, if any.
1.16      harris41 4435: 
1.112     bowersj2 4436: =cut
1.1       albertel 4437: 
                   4438: sub get_previous_attempt {
1.1075.2.86  raeburn  4439:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4440:   my $prevattempts='';
1.43      ng       4441:   no strict 'refs';
1.1       albertel 4442:   if ($symb) {
1.3       albertel 4443:     my (%returnhash)=
                   4444:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4445:     if ($returnhash{'version'}) {
                   4446:       my %lasthash=();
                   4447:       my $version;
                   4448:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4449:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4450:             if ($key =~ /\.rawrndseed$/) {
                   4451:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4452:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4453:             } else {
                   4454:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4455:             }
1.19      harris41 4456:         }
1.1       albertel 4457:       }
1.596     albertel 4458:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4459:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4460:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4461:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4462:       foreach my $key (sort(keys(%lasthash))) {
                   4463: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4464: 	if ($#parts > 0) {
1.31      albertel 4465: 	  my $data=$parts[-1];
1.989     raeburn  4466:           next if ($data eq 'foilorder');
1.31      albertel 4467: 	  pop(@parts);
1.1010    www      4468:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4469:           if ($data eq 'type') {
                   4470:               unless ($showsurv) {
                   4471:                   my $id = join(',',@parts);
                   4472:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4473:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4474:                       $lasthidden{$ign.'.'.$id} = 1;
                   4475:                   }
1.945     raeburn  4476:               }
1.1075.2.86  raeburn  4477:               if ($identifier ne '') {
                   4478:                   my $id = join(',',@parts);
                   4479:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4480:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4481:                       $hidestatus{$ign.'.'.$id} = 1;
                   4482:                   }
                   4483:               }
                   4484:           } elsif ($data eq 'regrader') {
                   4485:               if (($identifier ne '') && (@parts)) {
                   4486:                   my $id = join(',',@parts);
                   4487:                   $regraded{$ign.'.'.$id} = 1;
                   4488:               }
1.1010    www      4489:           } 
1.31      albertel 4490: 	} else {
1.41      ng       4491: 	  if ($#parts == 0) {
                   4492: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4493: 	  } else {
                   4494: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4495: 	  }
1.31      albertel 4496: 	}
1.16      harris41 4497:       }
1.596     albertel 4498:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4499:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4500:         my (%solved,%resets,%probstatus);
                   4501:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4502:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4503:                 foreach my $id (keys(%regraded)) {
                   4504:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4505:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4506:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4507:                         push(@{$resets{$id}},$version);
                   4508:                     }
                   4509:                 }
                   4510:             }
                   4511:         }
1.40      ng       4512: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4513:             my (@hidden,@unsolved);
1.945     raeburn  4514:             if (%typeparts) {
                   4515:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4516:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4517:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4518:                         push(@hidden,$id);
1.1075.2.86  raeburn  4519:                     } elsif ($identifier ne '') {
                   4520:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4521:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4522:                                 ($hidestatus{$id})) {
                   4523:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4524:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4525:                                 push(@{$solved{$id}},$version);
                   4526:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4527:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4528:                                 my $skip;
                   4529:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4530:                                     foreach my $reset (@{$resets{$id}}) {
                   4531:                                         if ($reset > $solved{$id}[-1]) {
                   4532:                                             $skip=1;
                   4533:                                             last;
                   4534:                                         }
                   4535:                                     }
                   4536:                                 }
                   4537:                                 unless ($skip) {
                   4538:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4539:                                     push(@unsolved,$partslist);
                   4540:                                 }
                   4541:                             }
                   4542:                         }
1.945     raeburn  4543:                     }
                   4544:                 }
                   4545:             }
                   4546:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4547:                            '<td>'.&mt('Transaction [_1]',$version);
                   4548:             if (@unsolved) {
                   4549:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4550:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4551:                                  &mt('Hide').'</label></span>';
                   4552:             }
                   4553:             $prevattempts .= '</td>';
1.945     raeburn  4554:             if (@hidden) {
                   4555:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4556:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4557:                     my $hide;
                   4558:                     foreach my $id (@hidden) {
                   4559:                         if ($key =~ /^\Q$id\E/) {
                   4560:                             $hide = 1;
                   4561:                             last;
                   4562:                         }
                   4563:                     }
                   4564:                     if ($hide) {
                   4565:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4566:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4567:                             my $value = &format_previous_attempt_value($key,
                   4568:                                              $returnhash{$version.':'.$key});
                   4569:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4570:                         } else {
                   4571:                             $prevattempts.='<td>&nbsp;</td>';
                   4572:                         }
                   4573:                     } else {
                   4574:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4575:                             my $value = $returnhash{$version.':'.$key};
                   4576:                             if ($key =~ /\.rndseed$/) {
                   4577:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4578:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4579:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4580:                                 }
                   4581:                             }
                   4582:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4583:                                            '&nbsp;</td>';
1.945     raeburn  4584:                         } else {
                   4585:                             $prevattempts.='<td>&nbsp;</td>';
                   4586:                         }
                   4587:                     }
                   4588:                 }
                   4589:             } else {
                   4590: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4591:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4592:                     my $value = $returnhash{$version.':'.$key};
                   4593:                     if ($key =~ /\.rndseed$/) {
                   4594:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4595:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4596:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4597:                         }
                   4598:                     }
                   4599:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4600:                                    '&nbsp;</td>';
1.945     raeburn  4601: 	        }
                   4602:             }
                   4603: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4604: 	 }
1.1       albertel 4605:       }
1.945     raeburn  4606:       my @currhidden = keys(%lasthidden);
1.596     albertel 4607:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4608:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4609:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4610:           if (%typeparts) {
                   4611:               my $hidden;
                   4612:               foreach my $id (@currhidden) {
                   4613:                   if ($key =~ /^\Q$id\E/) {
                   4614:                       $hidden = 1;
                   4615:                       last;
                   4616:                   }
                   4617:               }
                   4618:               if ($hidden) {
                   4619:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4620:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4621:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4622:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4623:                           $value = &$gradesub($value);
                   4624:                       }
                   4625:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4626:                   } else {
                   4627:                       $prevattempts.='<td>&nbsp;</td>';
                   4628:                   }
                   4629:               } else {
                   4630:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4631:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4632:                       $value = &$gradesub($value);
                   4633:                   }
                   4634:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4635:               }
                   4636:           } else {
                   4637: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4638: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4639:                   $value = &$gradesub($value);
                   4640:               }
                   4641: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4642:           }
1.16      harris41 4643:       }
1.596     albertel 4644:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4645:     } else {
1.1075.2.161.  .17(raeb 4646:-23):       my $msg;
                   4647:-23):       if ($symb =~ /ext\.tool$/) {
                   4648:-23):           $msg = &mt('No grade passed back.');
                   4649:-23):       } else {
                   4650:-23):           $msg = &mt('Nothing submitted - no attempts.');
                   4651:-23):       }
1.596     albertel 4652:       $prevattempts=
                   4653: 	  &start_data_table().&start_data_table_row().
1.1075.2.161.  .17(raeb 4654:-23): 	  '<td>'.$msg.'</td>'.
1.596     albertel 4655: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4656:     }
                   4657:   } else {
1.596     albertel 4658:     $prevattempts=
                   4659: 	  &start_data_table().&start_data_table_row().
                   4660: 	  '<td>'.&mt('No data.').'</td>'.
                   4661: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4662:   }
1.10      albertel 4663: }
                   4664: 
1.581     albertel 4665: sub format_previous_attempt_value {
                   4666:     my ($key,$value) = @_;
1.1011    www      4667:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4668: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4669:     } elsif (ref($value) eq 'ARRAY') {
                   4670: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4671:     } elsif ($key =~ /answerstring$/) {
                   4672:         my %answers = &Apache::lonnet::str2hash($value);
                   4673:         my @anskeys = sort(keys(%answers));
                   4674:         if (@anskeys == 1) {
                   4675:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4676:             if ($answer =~ m{\0}) {
                   4677:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4678:             }
                   4679:             my $tag_internal_answer_name = 'INTERNAL';
                   4680:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4681:                 $value = $answer; 
                   4682:             } else {
                   4683:                 $value = $anskeys[0].'='.$answer;
                   4684:             }
                   4685:         } else {
                   4686:             foreach my $ans (@anskeys) {
                   4687:                 my $answer = $answers{$ans};
1.1001    raeburn  4688:                 if ($answer =~ m{\0}) {
                   4689:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4690:                 }
                   4691:                 $value .=  $ans.'='.$answer.'<br />';;
                   4692:             } 
                   4693:         }
1.581     albertel 4694:     } else {
                   4695: 	$value = &unescape($value);
                   4696:     }
                   4697:     return $value;
                   4698: }
                   4699: 
                   4700: 
1.107     albertel 4701: sub relative_to_absolute {
                   4702:     my ($url,$output)=@_;
                   4703:     my $parser=HTML::TokeParser->new(\$output);
                   4704:     my $token;
                   4705:     my $thisdir=$url;
                   4706:     my @rlinks=();
                   4707:     while ($token=$parser->get_token) {
                   4708: 	if ($token->[0] eq 'S') {
                   4709: 	    if ($token->[1] eq 'a') {
                   4710: 		if ($token->[2]->{'href'}) {
                   4711: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4712: 		}
                   4713: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4714: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4715: 	    } elsif ($token->[1] eq 'base') {
                   4716: 		$thisdir=$token->[2]->{'href'};
                   4717: 	    }
                   4718: 	}
                   4719:     }
                   4720:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4721:     foreach my $link (@rlinks) {
1.726     raeburn  4722: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4723: 		($link=~/^\//) ||
                   4724: 		($link=~/^javascript:/i) ||
                   4725: 		($link=~/^mailto:/i) ||
                   4726: 		($link=~/^\#/)) {
                   4727: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4728: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4729: 	}
                   4730:     }
                   4731: # -------------------------------------------------- Deal with Applet codebases
                   4732:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4733:     return $output;
                   4734: }
                   4735: 
1.112     bowersj2 4736: =pod
                   4737: 
1.648     raeburn  4738: =item * &get_student_view()
1.112     bowersj2 4739: 
                   4740: show a snapshot of what student was looking at
                   4741: 
                   4742: =cut
                   4743: 
1.10      albertel 4744: sub get_student_view {
1.186     albertel 4745:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4746:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4747:   my (%form);
1.10      albertel 4748:   my @elements=('symb','courseid','domain','username');
                   4749:   foreach my $element (@elements) {
1.186     albertel 4750:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4751:   }
1.186     albertel 4752:   if (defined($moreenv)) {
                   4753:       %form=(%form,%{$moreenv});
                   4754:   }
1.236     albertel 4755:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4756:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4757:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4758:   $userview=~s/\<body[^\>]*\>//gi;
                   4759:   $userview=~s/\<\/body\>//gi;
                   4760:   $userview=~s/\<html\>//gi;
                   4761:   $userview=~s/\<\/html\>//gi;
                   4762:   $userview=~s/\<head\>//gi;
                   4763:   $userview=~s/\<\/head\>//gi;
                   4764:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4765:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4766:   if (wantarray) {
                   4767:      return ($userview,$response);
                   4768:   } else {
                   4769:      return $userview;
                   4770:   }
                   4771: }
                   4772: 
                   4773: sub get_student_view_with_retries {
                   4774:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4775: 
                   4776:     my $ok = 0;                 # True if we got a good response.
                   4777:     my $content;
                   4778:     my $response;
                   4779: 
                   4780:     # Try to get the student_view done. within the retries count:
                   4781:     
                   4782:     do {
                   4783:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4784:          $ok      = $response->is_success;
                   4785:          if (!$ok) {
                   4786:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4787:          }
                   4788:          $retries--;
                   4789:     } while (!$ok && ($retries > 0));
                   4790:     
                   4791:     if (!$ok) {
                   4792:        $content = '';          # On error return an empty content.
                   4793:     }
1.651     www      4794:     if (wantarray) {
                   4795:        return ($content, $response);
                   4796:     } else {
                   4797:        return $content;
                   4798:     }
1.11      albertel 4799: }
                   4800: 
1.1075.2.149  raeburn  4801: sub css_links {
                   4802:     my ($currsymb,$level) = @_;
                   4803:     my ($links,@symbs,%cssrefs,%httpref);
                   4804:     if ($level eq 'map') {
                   4805:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4806:         if (ref($navmap)) {
                   4807:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4808:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4809:             foreach my $res (@resources) {
                   4810:                 if (ref($res) && $res->symb()) {
                   4811:                     push(@symbs,$res->symb());
                   4812:                 }
                   4813:             }
                   4814:         }
                   4815:     } else {
                   4816:         @symbs = ($currsymb);
                   4817:     }
                   4818:     foreach my $symb (@symbs) {
                   4819:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4820:         if ($css_href =~ /\S/) {
                   4821:             unless ($css_href =~ m{https?://}) {
                   4822:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4823:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4824:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4825:                 unless ($css_href =~ m{^/}) {
                   4826:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4827:                 }
                   4828:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4829:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4830:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4831:                         my $thisurl = $proburl;
                   4832:                         if ($env{'httpref.'.$proburl}) {
                   4833:                             $thisurl = $env{'httpref.'.$proburl};
                   4834:                         }
                   4835:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4836:                     }
                   4837:                 }
                   4838:             }
                   4839:             $cssrefs{$css_href} = 1;
                   4840:         }
                   4841:     }
                   4842:     if (keys(%httpref)) {
                   4843:         &Apache::lonnet::appenv(\%httpref);
                   4844:     }
                   4845:     if (keys(%cssrefs)) {
                   4846:         foreach my $css_href (keys(%cssrefs)) {
                   4847:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4848:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4849:         }
                   4850:     }
                   4851:     return $links;
                   4852: }
                   4853: 
1.112     bowersj2 4854: =pod
                   4855: 
1.648     raeburn  4856: =item * &get_student_answers() 
1.112     bowersj2 4857: 
                   4858: show a snapshot of how student was answering problem
                   4859: 
                   4860: =cut
                   4861: 
1.11      albertel 4862: sub get_student_answers {
1.100     sakharuk 4863:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4864:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4865:   my (%moreenv);
1.11      albertel 4866:   my @elements=('symb','courseid','domain','username');
                   4867:   foreach my $element (@elements) {
1.186     albertel 4868:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4869:   }
1.186     albertel 4870:   $moreenv{'grade_target'}='answer';
                   4871:   %moreenv=(%form,%moreenv);
1.497     raeburn  4872:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4873:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4874:   return $userview;
1.1       albertel 4875: }
1.116     albertel 4876: 
                   4877: =pod
                   4878: 
                   4879: =item * &submlink()
                   4880: 
1.242     albertel 4881: Inputs: $text $uname $udom $symb $target
1.116     albertel 4882: 
                   4883: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4884: 
                   4885: =cut
                   4886: 
                   4887: ###############################################
                   4888: sub submlink {
1.242     albertel 4889:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4890:     if (!($uname && $udom)) {
                   4891: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4892: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4893: 	if (!$symb) { $symb=$cursymb; }
                   4894:     }
1.254     matthew  4895:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4896:     $symb=&escape($symb);
1.960     bisitz   4897:     if ($target) { $target=" target=\"$target\""; }
                   4898:     return
                   4899:         '<a href="/adm/grades?command=submission'.
                   4900:         '&amp;symb='.$symb.
                   4901:         '&amp;student='.$uname.
                   4902:         '&amp;userdom='.$udom.'"'.
                   4903:         $target.'>'.$text.'</a>';
1.242     albertel 4904: }
                   4905: ##############################################
                   4906: 
                   4907: =pod
                   4908: 
                   4909: =item * &pgrdlink()
                   4910: 
                   4911: Inputs: $text $uname $udom $symb $target
                   4912: 
                   4913: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4914: 
                   4915: =cut
                   4916: 
                   4917: ###############################################
                   4918: sub pgrdlink {
                   4919:     my $link=&submlink(@_);
                   4920:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4921:     return $link;
                   4922: }
                   4923: ##############################################
                   4924: 
                   4925: =pod
                   4926: 
                   4927: =item * &pprmlink()
                   4928: 
                   4929: Inputs: $text $uname $udom $symb $target
                   4930: 
                   4931: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4932: student and a specific resource
1.242     albertel 4933: 
                   4934: =cut
                   4935: 
                   4936: ###############################################
                   4937: sub pprmlink {
                   4938:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4939:     if (!($uname && $udom)) {
                   4940: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4941: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4942: 	if (!$symb) { $symb=$cursymb; }
                   4943:     }
1.254     matthew  4944:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4945:     $symb=&escape($symb);
1.242     albertel 4946:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4947:     return '<a href="/adm/parmset?command=set&amp;'.
                   4948: 	'symb='.$symb.'&amp;uname='.$uname.
                   4949: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4950: }
                   4951: ##############################################
1.37      matthew  4952: 
1.112     bowersj2 4953: =pod
                   4954: 
                   4955: =back
                   4956: 
                   4957: =cut
                   4958: 
1.37      matthew  4959: ###############################################
1.51      www      4960: 
                   4961: 
                   4962: sub timehash {
1.687     raeburn  4963:     my ($thistime) = @_;
                   4964:     my $timezone = &Apache::lonlocal::gettimezone();
                   4965:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4966:                      ->set_time_zone($timezone);
                   4967:     my $wday = $dt->day_of_week();
                   4968:     if ($wday == 7) { $wday = 0; }
                   4969:     return ( 'second' => $dt->second(),
                   4970:              'minute' => $dt->minute(),
                   4971:              'hour'   => $dt->hour(),
                   4972:              'day'     => $dt->day_of_month(),
                   4973:              'month'   => $dt->month(),
                   4974:              'year'    => $dt->year(),
                   4975:              'weekday' => $wday,
                   4976:              'dayyear' => $dt->day_of_year(),
                   4977:              'dlsav'   => $dt->is_dst() );
1.51      www      4978: }
                   4979: 
1.370     www      4980: sub utc_string {
                   4981:     my ($date)=@_;
1.371     www      4982:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4983: }
                   4984: 
1.51      www      4985: sub maketime {
                   4986:     my %th=@_;
1.687     raeburn  4987:     my ($epoch_time,$timezone,$dt);
                   4988:     $timezone = &Apache::lonlocal::gettimezone();
                   4989:     eval {
                   4990:         $dt = DateTime->new( year   => $th{'year'},
                   4991:                              month  => $th{'month'},
                   4992:                              day    => $th{'day'},
                   4993:                              hour   => $th{'hour'},
                   4994:                              minute => $th{'minute'},
                   4995:                              second => $th{'second'},
                   4996:                              time_zone => $timezone,
                   4997:                          );
                   4998:     };
                   4999:     if (!$@) {
                   5000:         $epoch_time = $dt->epoch;
                   5001:         if ($epoch_time) {
                   5002:             return $epoch_time;
                   5003:         }
                   5004:     }
1.51      www      5005:     return POSIX::mktime(
                   5006:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5007:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5008: }
                   5009: 
                   5010: #########################################
1.51      www      5011: 
                   5012: sub findallcourses {
1.482     raeburn  5013:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5014:     my %roles;
                   5015:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5016:     my %courses;
1.51      www      5017:     my $now=time;
1.482     raeburn  5018:     if (!defined($uname)) {
                   5019:         $uname = $env{'user.name'};
                   5020:     }
                   5021:     if (!defined($udom)) {
                   5022:         $udom = $env{'user.domain'};
                   5023:     }
                   5024:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5025:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5026:         if (!%roles) {
                   5027:             %roles = (
                   5028:                        cc => 1,
1.907     raeburn  5029:                        co => 1,
1.482     raeburn  5030:                        in => 1,
                   5031:                        ep => 1,
                   5032:                        ta => 1,
                   5033:                        cr => 1,
                   5034:                        st => 1,
                   5035:              );
                   5036:         }
                   5037:         foreach my $entry (keys(%roleshash)) {
                   5038:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5039:             if ($trole =~ /^cr/) { 
                   5040:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5041:             } else {
                   5042:                 next if (!exists($roles{$trole}));
                   5043:             }
                   5044:             if ($tend) {
                   5045:                 next if ($tend < $now);
                   5046:             }
                   5047:             if ($tstart) {
                   5048:                 next if ($tstart > $now);
                   5049:             }
1.1058    raeburn  5050:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5051:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5052:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5053:             if ($secpart eq '') {
                   5054:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5055:                 $sec = 'none';
1.1058    raeburn  5056:                 $value .= $cnum.'/';
1.482     raeburn  5057:             } else {
                   5058:                 $cnum = $cnumpart;
                   5059:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5060:                 $value .= $cnum.'/'.$sec;
                   5061:             }
                   5062:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5063:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5064:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5065:                 }
                   5066:             } else {
                   5067:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5068:             }
1.482     raeburn  5069:         }
                   5070:     } else {
                   5071:         foreach my $key (keys(%env)) {
1.483     albertel 5072: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5073:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5074: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5075: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5076: 	        next if (%roles && !exists($roles{$role}));
                   5077: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5078:                 my $active=1;
                   5079:                 if ($starttime) {
                   5080: 		    if ($now<$starttime) { $active=0; }
                   5081:                 }
                   5082:                 if ($endtime) {
                   5083:                     if ($now>$endtime) { $active=0; }
                   5084:                 }
                   5085:                 if ($active) {
1.1058    raeburn  5086:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5087:                     if ($sec eq '') {
                   5088:                         $sec = 'none';
1.1058    raeburn  5089:                     } else {
                   5090:                         $value .= $sec;
                   5091:                     }
                   5092:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5093:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5094:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5095:                         }
                   5096:                     } else {
                   5097:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5098:                     }
1.474     raeburn  5099:                 }
                   5100:             }
1.51      www      5101:         }
                   5102:     }
1.474     raeburn  5103:     return %courses;
1.51      www      5104: }
1.37      matthew  5105: 
1.54      www      5106: ###############################################
1.474     raeburn  5107: 
                   5108: sub blockcheck {
1.1075.2.158  raeburn  5109:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  5110: 
1.1075.2.161.  .4(raebu 5111:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  5112:         my ($has_evb,$check_ipaccess);
                   5113:         my $dom = $env{'user.domain'};
                   5114:         if ($env{'request.course.id'}) {
                   5115:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5116:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5117:             my $checkrole = "cm./$cdom/$cnum";
                   5118:             my $sec = $env{'request.course.sec'};
                   5119:             if ($sec ne '') {
                   5120:                 $checkrole .= "/$sec";
                   5121:             }
                   5122:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5123:                 ($env{'request.role'} !~ /^st/)) {
                   5124:                 $has_evb = 1;
                   5125:             }
                   5126:             unless ($has_evb) {
                   5127:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5128:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5129:                     if ($udom eq $cdom) {
                   5130:                         $check_ipaccess = 1;
                   5131:                     }
                   5132:                 }
                   5133:             }
1.1075.2.161.  .3(raebu 5134:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5135:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5136:22):             my $checkrole;
                   5137:22):             if ($env{'request.role.domain'} eq '') {
                   5138:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   5139:22):             } else {
                   5140:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5141:22):             }
                   5142:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5143:22):                 $has_evb = 1;
                   5144:22):             }
1.1075.2.158  raeburn  5145:         }
                   5146:         unless ($has_evb || $check_ipaccess) {
                   5147:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5148:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5149:                 $dom = $udom;
                   5150:             }
                   5151:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5152:                 $check_ipaccess = 1;
                   5153:             } else {
                   5154:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5155:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5156:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5157:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5158:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5159:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5160:                         $check_ipaccess = 1;
                   5161:                     }
                   5162:                 }
                   5163:             }
                   5164:         }
                   5165:         if ($check_ipaccess) {
                   5166:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5167:             unless (defined($cached)) {
                   5168:                 my %domconfig =
                   5169:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5170:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5171:             }
                   5172:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5173:                 foreach my $id (keys(%{$ipaccessref})) {
                   5174:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5175:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5176:                         if ($range) {
                   5177:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5178:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5179:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5180:                                         return ('','','',$id,$dom);
                   5181:                                         last;
                   5182:                                     }
                   5183:                                 }
                   5184:                             }
                   5185:                         }
                   5186:                     }
                   5187:                 }
                   5188:             }
                   5189:         }
1.1075.2.161.  .4(raebu 5190:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5191:22):             return ();
                   5192:22):         }
1.1075.2.158  raeburn  5193:     }
1.1075.2.73  raeburn  5194:     if (defined($udom) && defined($uname)) {
                   5195:         # If uname and udom are for a course, check for blocks in the course.
                   5196:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5197:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5198:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5199:             return ($startblock,$endblock,$triggerblock);
                   5200:         }
                   5201:     } else {
1.490     raeburn  5202:         $udom = $env{'user.domain'};
                   5203:         $uname = $env{'user.name'};
                   5204:     }
                   5205: 
1.502     raeburn  5206:     my $startblock = 0;
                   5207:     my $endblock = 0;
1.1062    raeburn  5208:     my $triggerblock = '';
1.1075.2.160  raeburn  5209:     my %live_courses;
                   5210:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5211:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5212:     }
1.474     raeburn  5213: 
1.490     raeburn  5214:     # If uname is for a user, and activity is course-specific, i.e.,
                   5215:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5216: 
1.490     raeburn  5217:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5218:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5219:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5220:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5221:         foreach my $key (keys(%live_courses)) {
                   5222:             if ($key ne $env{'request.course.id'}) {
                   5223:                 delete($live_courses{$key});
                   5224:             }
                   5225:         }
                   5226:     }
                   5227: 
                   5228:     my $otheruser = 0;
                   5229:     my %own_courses;
                   5230:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5231:         # Resource belongs to user other than current user.
                   5232:         $otheruser = 1;
                   5233:         # Gather courses for current user
                   5234:         %own_courses = 
                   5235:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5236:     }
                   5237: 
                   5238:     # Gather active course roles - course coordinator, instructor, 
                   5239:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5240: 
                   5241:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5242:         my ($cdom,$cnum);
                   5243:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5244:             $cdom = $env{'course.'.$course.'.domain'};
                   5245:             $cnum = $env{'course.'.$course.'.num'};
                   5246:         } else {
1.490     raeburn  5247:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5248:         }
                   5249:         my $no_ownblock = 0;
                   5250:         my $no_userblock = 0;
1.533     raeburn  5251:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5252:             # Check if current user has 'evb' priv for this
                   5253:             if (defined($own_courses{$course})) {
                   5254:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5255:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5256:                     if ($sec ne 'none') {
                   5257:                         $checkrole .= '/'.$sec;
                   5258:                     }
                   5259:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5260:                         $no_ownblock = 1;
                   5261:                         last;
                   5262:                     }
                   5263:                 }
                   5264:             }
                   5265:             # if they have 'evb' priv and are currently not playing student
                   5266:             next if (($no_ownblock) &&
                   5267:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5268:         }
1.474     raeburn  5269:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5270:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5271:             if ($sec ne 'none') {
1.482     raeburn  5272:                 $checkrole .= '/'.$sec;
1.474     raeburn  5273:             }
1.490     raeburn  5274:             if ($otheruser) {
                   5275:                 # Resource belongs to user other than current user.
                   5276:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5277:                 my (%allroles,%userroles);
                   5278:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5279:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5280:                         my ($trole,$tdom,$tnum,$tsec);
                   5281:                         if ($entry =~ /^cr/) {
                   5282:                             ($trole,$tdom,$tnum,$tsec) = 
                   5283:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5284:                         } else {
                   5285:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5286:                         }
                   5287:                         my ($spec,$area,$trest);
                   5288:                         $area = '/'.$tdom.'/'.$tnum;
                   5289:                         $trest = $tnum;
                   5290:                         if ($tsec ne '') {
                   5291:                             $area .= '/'.$tsec;
                   5292:                             $trest .= '/'.$tsec;
                   5293:                         }
                   5294:                         $spec = $trole.'.'.$area;
                   5295:                         if ($trole =~ /^cr/) {
                   5296:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5297:                                                               $tdom,$spec,$trest,$area);
                   5298:                         } else {
                   5299:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5300:                                                                 $tdom,$spec,$trest,$area);
                   5301:                         }
                   5302:                     }
1.1075.2.124  raeburn  5303:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5304:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5305:                         if ($1) {
                   5306:                             $no_userblock = 1;
                   5307:                             last;
                   5308:                         }
1.486     raeburn  5309:                     }
                   5310:                 }
1.490     raeburn  5311:             } else {
                   5312:                 # Resource belongs to current user
                   5313:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5314:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5315:                     $no_ownblock = 1;
                   5316:                     last;
                   5317:                 }
1.474     raeburn  5318:             }
                   5319:         }
                   5320:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5321:         next if (($no_ownblock) &&
1.491     albertel 5322:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5323:         next if ($no_userblock);
1.474     raeburn  5324: 
1.1075.2.128  raeburn  5325:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5326:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5327:         
1.1062    raeburn  5328:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5329:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5330:         if (($start != 0) && 
                   5331:             (($startblock == 0) || ($startblock > $start))) {
                   5332:             $startblock = $start;
1.1062    raeburn  5333:             if ($trigger ne '') {
                   5334:                 $triggerblock = $trigger;
                   5335:             }
1.502     raeburn  5336:         }
                   5337:         if (($end != 0)  &&
                   5338:             (($endblock == 0) || ($endblock < $end))) {
                   5339:             $endblock = $end;
1.1062    raeburn  5340:             if ($trigger ne '') {
                   5341:                 $triggerblock = $trigger;
                   5342:             }
1.502     raeburn  5343:         }
1.490     raeburn  5344:     }
1.1062    raeburn  5345:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5346: }
                   5347: 
                   5348: sub get_blocks {
1.1075.2.147  raeburn  5349:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5350:     my $startblock = 0;
                   5351:     my $endblock = 0;
1.1062    raeburn  5352:     my $triggerblock = '';
1.490     raeburn  5353:     my $course = $cdom.'_'.$cnum;
                   5354:     $setters->{$course} = {};
                   5355:     $setters->{$course}{'staff'} = [];
                   5356:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5357:     $setters->{$course}{'triggers'} = [];
                   5358:     my (@blockers,%triggered);
                   5359:     my $now = time;
                   5360:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5361:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5362:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5363:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5364:             $blocked = 1;
                   5365:             $nosymbcache = 1;
1.1075.2.148  raeburn  5366:             $noenccheck = 1;
1.1075.2.147  raeburn  5367:         }
1.1075.2.148  raeburn  5368:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5369:         foreach my $block (@blockers) {
                   5370:             if ($block =~ /^firstaccess____(.+)$/) {
                   5371:                 my $item = $1;
                   5372:                 my $type = 'map';
                   5373:                 my $timersymb = $item;
                   5374:                 if ($item eq 'course') {
                   5375:                     $type = 'course';
                   5376:                 } elsif ($item =~ /___\d+___/) {
                   5377:                     $type = 'resource';
                   5378:                 } else {
                   5379:                     $timersymb = &Apache::lonnet::symbread($item);
                   5380:                 }
                   5381:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5382:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5383:                 $triggered{$block} = {
                   5384:                                        start => $start,
                   5385:                                        end   => $end,
                   5386:                                        type  => $type,
                   5387:                                      };
                   5388:             }
                   5389:         }
                   5390:     } else {
                   5391:         foreach my $block (keys(%commblocks)) {
                   5392:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5393:                 my ($start,$end) = ($1,$2);
                   5394:                 if ($start <= time && $end >= time) {
                   5395:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5396:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5397:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5398:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5399:                                     push(@blockers,$block);
                   5400:                                 }
                   5401:                             }
                   5402:                         }
                   5403:                     }
                   5404:                 }
                   5405:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5406:                 my $item = $1;
                   5407:                 my $timersymb = $item; 
                   5408:                 my $type = 'map';
                   5409:                 if ($item eq 'course') {
                   5410:                     $type = 'course';
                   5411:                 } elsif ($item =~ /___\d+___/) {
                   5412:                     $type = 'resource';
                   5413:                 } else {
                   5414:                     $timersymb = &Apache::lonnet::symbread($item);
                   5415:                 }
                   5416:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5417:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5418:                 if ($start && $end) {
                   5419:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5420:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5421:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5422:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5423:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5424:                                         push(@blockers,$block);
                   5425:                                         $triggered{$block} = {
                   5426:                                                                start => $start,
                   5427:                                                                end   => $end,
                   5428:                                                                type  => $type,
                   5429:                                                              };
                   5430:                                     }
                   5431:                                 }
                   5432:                             }
1.1062    raeburn  5433:                         }
                   5434:                     }
1.490     raeburn  5435:                 }
1.1062    raeburn  5436:             }
                   5437:         }
                   5438:     }
                   5439:     foreach my $blocker (@blockers) {
                   5440:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5441:             &parse_block_record($commblocks{$blocker});
                   5442:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5443:         my ($start,$end,$triggertype);
                   5444:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5445:             ($start,$end) = ($1,$2);
                   5446:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5447:             $start = $triggered{$blocker}{'start'};
                   5448:             $end = $triggered{$blocker}{'end'};
                   5449:             $triggertype = $triggered{$blocker}{'type'};
                   5450:         }
                   5451:         if ($start) {
                   5452:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5453:             if ($triggertype) {
                   5454:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5455:             } else {
                   5456:                 push(@{$$setters{$course}{'triggers'}},0);
                   5457:             }
                   5458:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5459:                 $startblock = $start;
                   5460:                 if ($triggertype) {
                   5461:                     $triggerblock = $blocker;
1.474     raeburn  5462:                 }
                   5463:             }
1.1062    raeburn  5464:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5465:                $endblock = $end;
                   5466:                if ($triggertype) {
                   5467:                    $triggerblock = $blocker;
                   5468:                }
                   5469:             }
1.474     raeburn  5470:         }
                   5471:     }
1.1062    raeburn  5472:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5473: }
                   5474: 
                   5475: sub parse_block_record {
                   5476:     my ($record) = @_;
                   5477:     my ($setuname,$setudom,$title,$blocks);
                   5478:     if (ref($record) eq 'HASH') {
                   5479:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5480:         $title = &unescape($record->{'event'});
                   5481:         $blocks = $record->{'blocks'};
                   5482:     } else {
                   5483:         my @data = split(/:/,$record,3);
                   5484:         if (scalar(@data) eq 2) {
                   5485:             $title = $data[1];
                   5486:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5487:         } else {
                   5488:             ($setuname,$setudom,$title) = @data;
                   5489:         }
                   5490:         $blocks = { 'com' => 'on' };
                   5491:     }
                   5492:     return ($setuname,$setudom,$title,$blocks);
                   5493: }
                   5494: 
1.854     kalberla 5495: sub blocking_status {
1.1075.2.158  raeburn  5496:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5497:     my %setters;
1.890     droeschl 5498: 
1.1061    raeburn  5499: # check for active blocking
1.1075.2.158  raeburn  5500:     if ($clientip eq '') {
                   5501:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5502:     }
                   5503:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5504:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5505:     my $blocked = 0;
1.1075.2.158  raeburn  5506:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5507:         $blocked = 1;
                   5508:     }
1.890     droeschl 5509: 
1.1061    raeburn  5510: # caller just wants to know whether a block is active
                   5511:     if (!wantarray) { return $blocked; }
                   5512: 
                   5513: # build a link to a popup window containing the details
                   5514:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5515: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5516:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5517:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5518:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5519:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5520:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5521:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5522:         if ($symb) {
                   5523:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5524:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5525:         }
1.1062    raeburn  5526:     }
1.1061    raeburn  5527: 
                   5528:     my $output .= <<'END_MYBLOCK';
                   5529: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5530:     var options = "width=" + w + ",height=" + h + ",";
                   5531:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5532:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5533:     var newWin = window.open(url, wdwName, options);
                   5534:     newWin.focus();
                   5535: }
1.890     droeschl 5536: END_MYBLOCK
1.854     kalberla 5537: 
1.1061    raeburn  5538:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5539:   
1.1061    raeburn  5540:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5541:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5542:     my $class = 'LC_comblock';
1.1062    raeburn  5543:     if ($activity eq 'docs') {
                   5544:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5545:         $class = '';
1.1063    raeburn  5546:     } elsif ($activity eq 'printout') {
                   5547:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5548:     } elsif ($activity eq 'passwd') {
                   5549:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5550:     } elsif ($activity eq 'grades') {
                   5551:         $text = &mt('Gradebook Blocked');
                   5552:     } elsif ($activity eq 'search') {
                   5553:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5554:21):     } elsif ($activity eq 'alert') {
                   5555:21):         $text = &mt('Checking Critical Messages Blocked');
                   5556:21):     } elsif ($activity eq 'reinit') {
                   5557:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5558:     } elsif ($activity eq 'about') {
                   5559:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5560:     } elsif ($activity eq 'wishlist') {
                   5561:         $text = &mt('Access to Stored Links Blocked');
                   5562:     } elsif ($activity eq 'annotate') {
                   5563:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5564:     }
1.1061    raeburn  5565:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5566: <div class='$class'>
1.869     kalberla 5567:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5568:   title='$text'>
                   5569:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5570:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5571:   title='$text'>$text</a>
1.867     kalberla 5572: </div>
                   5573: 
                   5574: END_BLOCK
1.474     raeburn  5575: 
1.1061    raeburn  5576:     return ($blocked, $output);
1.854     kalberla 5577: }
1.490     raeburn  5578: 
1.60      matthew  5579: ###############################################
                   5580: 
1.682     raeburn  5581: sub check_ip_acc {
1.1075.2.105  raeburn  5582:     my ($acc,$clientip)=@_;
1.682     raeburn  5583:     &Apache::lonxml::debug("acc is $acc");
                   5584:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5585:         return 1;
                   5586:     }
                   5587:     my $allowed=0;
1.1075.2.144  raeburn  5588:     my $ip;
                   5589:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5590:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5591:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5592:     } else {
1.1075.2.150  raeburn  5593:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5594:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5595:     }
1.682     raeburn  5596: 
                   5597:     my $name;
1.1075.2.161.  .1(raebu 5598:21):     my %access = (
                   5599:21):                      allowfrom => 1,
                   5600:21):                      denyfrom  => 0,
                   5601:21):                  );
                   5602:21):     my @allows;
                   5603:21):     my @denies;
                   5604:21):     foreach my $item (split(',',$acc)) {
                   5605:21):         $item =~ s/^\s*//;
                   5606:21):         $item =~ s/\s*$//;
                   5607:21):         if ($item =~ /^\!(.+)$/) {
                   5608:21):             push(@denies,$1);
                   5609:21):         } else {
                   5610:21):             push(@allows,$item);
                   5611:21):         }
                   5612:21):     }
                   5613:21):     my $numdenies = scalar(@denies);
                   5614:21):     my $numallows = scalar(@allows);
                   5615:21):     my $count = 0;
                   5616:21):     foreach my $pattern (@denies,@allows) {
                   5617:21):         $count ++;
                   5618:21):         my $acctype = 'allowfrom';
                   5619:21):         if ($count <= $numdenies) {
                   5620:21):             $acctype = 'denyfrom';
                   5621:21):         }
1.682     raeburn  5622:         if ($pattern =~ /\*$/) {
                   5623:             #35.8.*
                   5624:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5625:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5626:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5627:             #35.8.3.[34-56]
                   5628:             my $low=$2;
                   5629:             my $high=$3;
                   5630:             $pattern=$1;
                   5631:             if ($ip =~ /^\Q$pattern\E/) {
                   5632:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5633:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5634:             }
                   5635:         } elsif ($pattern =~ /^\*/) {
                   5636:             #*.msu.edu
                   5637:             $pattern=~s/\*//;
                   5638:             if (!defined($name)) {
                   5639:                 use Socket;
                   5640:                 my $netaddr=inet_aton($ip);
                   5641:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5642:             }
1.1075.2.161.  .1(raebu 5643:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5644:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5645:             #127.0.0.1
1.1075.2.161.  .1(raebu 5646:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5647:         } else {
                   5648:             #some.name.com
                   5649:             if (!defined($name)) {
                   5650:                 use Socket;
                   5651:                 my $netaddr=inet_aton($ip);
                   5652:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5653:             }
1.1075.2.161.  .1(raebu 5654:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5655:21):         }
                   5656:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5657:21):     }
                   5658:21):     if ($allowed eq '') {
                   5659:21):         if ($numdenies && !$numallows) {
                   5660:21):             $allowed = 1;
                   5661:21):         } else {
                   5662:21):             $allowed = 0;
1.682     raeburn  5663:         }
                   5664:     }
                   5665:     return $allowed;
                   5666: }
                   5667: 
                   5668: ###############################################
                   5669: 
1.60      matthew  5670: =pod
                   5671: 
1.112     bowersj2 5672: =head1 Domain Template Functions
                   5673: 
                   5674: =over 4
                   5675: 
                   5676: =item * &determinedomain()
1.60      matthew  5677: 
                   5678: Inputs: $domain (usually will be undef)
                   5679: 
1.63      www      5680: Returns: Determines which domain should be used for designs
1.60      matthew  5681: 
                   5682: =cut
1.54      www      5683: 
1.60      matthew  5684: ###############################################
1.63      www      5685: sub determinedomain {
                   5686:     my $domain=shift;
1.531     albertel 5687:     if (! $domain) {
1.60      matthew  5688:         # Determine domain if we have not been given one
1.893     raeburn  5689:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5690:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5691:         if ($env{'request.role.domain'}) { 
                   5692:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5693:         }
                   5694:     }
1.63      www      5695:     return $domain;
                   5696: }
                   5697: ###############################################
1.517     raeburn  5698: 
1.518     albertel 5699: sub devalidate_domconfig_cache {
                   5700:     my ($udom)=@_;
                   5701:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5702: }
                   5703: 
                   5704: # ---------------------- Get domain configuration for a domain
                   5705: sub get_domainconf {
                   5706:     my ($udom) = @_;
                   5707:     my $cachetime=1800;
                   5708:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5709:     if (defined($cached)) { return %{$result}; }
                   5710: 
                   5711:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5712: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5713:     my (%designhash,%legacy);
1.518     albertel 5714:     if (keys(%domconfig) > 0) {
                   5715:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5716:             if (keys(%{$domconfig{'login'}})) {
                   5717:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5718:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5719:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5720:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5721:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5722:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5723:                                         if ($key eq 'loginvia') {
                   5724:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5725:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5726:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5727:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5728:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5729:                                                 } else {
                   5730:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5731:                                                 }
1.948     raeburn  5732:                                             }
1.1075.2.87  raeburn  5733:                                         } elsif ($key eq 'headtag') {
                   5734:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5735:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5736:                                             }
1.946     raeburn  5737:                                         }
1.1075.2.87  raeburn  5738:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5739:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5740:                                         }
1.946     raeburn  5741:                                     }
                   5742:                                 }
                   5743:                             }
1.1075.2.158  raeburn  5744:                         } elsif ($key eq 'saml') {
                   5745:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5746:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5747:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5748:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5749:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5750:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5751:                                         }
                   5752:                                     }
                   5753:                                 }
                   5754:                             }
1.946     raeburn  5755:                         } else {
                   5756:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5757:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5758:                                     $domconfig{'login'}{$key}{$img};
                   5759:                             }
1.699     raeburn  5760:                         }
                   5761:                     } else {
                   5762:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5763:                     }
1.632     raeburn  5764:                 }
                   5765:             } else {
                   5766:                 $legacy{'login'} = 1;
1.518     albertel 5767:             }
1.632     raeburn  5768:         } else {
                   5769:             $legacy{'login'} = 1;
1.518     albertel 5770:         }
                   5771:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5772:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5773:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5774:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5775:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5776:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5777:                         }
1.518     albertel 5778:                     }
                   5779:                 }
1.632     raeburn  5780:             } else {
                   5781:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5782:             }
1.632     raeburn  5783:         } else {
                   5784:             $legacy{'rolecolors'} = 1;
1.518     albertel 5785:         }
1.948     raeburn  5786:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5787:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5788:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5789:             }
                   5790:         }
1.632     raeburn  5791:         if (keys(%legacy) > 0) {
                   5792:             my %legacyhash = &get_legacy_domconf($udom);
                   5793:             foreach my $item (keys(%legacyhash)) {
                   5794:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5795:                     if ($legacy{'login'}) { 
                   5796:                         $designhash{$item} = $legacyhash{$item};
                   5797:                     }
                   5798:                 } else {
                   5799:                     if ($legacy{'rolecolors'}) {
                   5800:                         $designhash{$item} = $legacyhash{$item};
                   5801:                     }
1.518     albertel 5802:                 }
                   5803:             }
                   5804:         }
1.632     raeburn  5805:     } else {
                   5806:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5807:     }
                   5808:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5809: 				  $cachetime);
                   5810:     return %designhash;
                   5811: }
                   5812: 
1.632     raeburn  5813: sub get_legacy_domconf {
                   5814:     my ($udom) = @_;
                   5815:     my %legacyhash;
                   5816:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5817:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5818:     if (-e $designfile) {
1.1075.2.128  raeburn  5819:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5820:             while (my $line = <$fh>) {
                   5821:                 next if ($line =~ /^\#/);
                   5822:                 chomp($line);
                   5823:                 my ($key,$val)=(split(/\=/,$line));
                   5824:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5825:             }
                   5826:             close($fh);
                   5827:         }
                   5828:     }
1.1026    raeburn  5829:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5830:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5831:     }
                   5832:     return %legacyhash;
                   5833: }
                   5834: 
1.63      www      5835: =pod
                   5836: 
1.112     bowersj2 5837: =item * &domainlogo()
1.63      www      5838: 
                   5839: Inputs: $domain (usually will be undef)
                   5840: 
                   5841: Returns: A link to a domain logo, if the domain logo exists.
                   5842: If the domain logo does not exist, a description of the domain.
                   5843: 
                   5844: =cut
1.112     bowersj2 5845: 
1.63      www      5846: ###############################################
                   5847: sub domainlogo {
1.517     raeburn  5848:     my $domain = &determinedomain(shift);
1.518     albertel 5849:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5850:     # See if there is a logo
                   5851:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5852:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5853:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5854: 	    if ($imgsrc =~ m{^/res/}) {
                   5855: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5856: 		&Apache::lonnet::repcopy($local_name);
                   5857: 	    }
                   5858: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5859:22):         }
                   5860:22):         my $alttext = $domain;
                   5861:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5862:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5863:22):         }
                   5864:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5865:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5866:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5867:     } else {
1.60      matthew  5868:         return '';
1.59      www      5869:     }
                   5870: }
1.63      www      5871: ##############################################
                   5872: 
                   5873: =pod
                   5874: 
1.112     bowersj2 5875: =item * &designparm()
1.63      www      5876: 
                   5877: Inputs: $which parameter; $domain (usually will be undef)
                   5878: 
                   5879: Returns: value of designparamter $which
                   5880: 
                   5881: =cut
1.112     bowersj2 5882: 
1.397     albertel 5883: 
1.400     albertel 5884: ##############################################
1.397     albertel 5885: sub designparm {
                   5886:     my ($which,$domain)=@_;
                   5887:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5888:         return $env{'environment.color.'.$which};
1.96      www      5889:     }
1.63      www      5890:     $domain=&determinedomain($domain);
1.1016    raeburn  5891:     my %domdesign;
                   5892:     unless ($domain eq 'public') {
                   5893:         %domdesign = &get_domainconf($domain);
                   5894:     }
1.520     raeburn  5895:     my $output;
1.517     raeburn  5896:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5897:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5898:     } else {
1.520     raeburn  5899:         $output = $defaultdesign{$which};
                   5900:     }
                   5901:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5902:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5903:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5904:             if ($output =~ m{^/res/}) {
                   5905:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5906:                 &Apache::lonnet::repcopy($local_name);
                   5907:             }
1.520     raeburn  5908:             $output = &lonhttpdurl($output);
                   5909:         }
1.63      www      5910:     }
1.520     raeburn  5911:     return $output;
1.63      www      5912: }
1.59      www      5913: 
1.822     bisitz   5914: ##############################################
                   5915: =pod
                   5916: 
1.832     bisitz   5917: =item * &authorspace()
                   5918: 
1.1028    raeburn  5919: Inputs: $url (usually will be undef).
1.832     bisitz   5920: 
1.1075.2.40  raeburn  5921: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5922:          directory being viewed (or for which action is being taken). 
                   5923:          If $url is provided, and begins /priv/<domain>/<uname>
                   5924:          the path will be that portion of the $context argument.
                   5925:          Otherwise the path will be for the author space of the current
                   5926:          user when the current role is author, or for that of the 
                   5927:          co-author/assistant co-author space when the current role 
                   5928:          is co-author or assistant co-author.
1.832     bisitz   5929: 
                   5930: =cut
                   5931: 
                   5932: sub authorspace {
1.1028    raeburn  5933:     my ($url) = @_;
                   5934:     if ($url ne '') {
                   5935:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5936:            return $1;
                   5937:         }
                   5938:     }
1.832     bisitz   5939:     my $caname = '';
1.1024    www      5940:     my $cadom = '';
1.1028    raeburn  5941:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5942:         ($cadom,$caname) =
1.832     bisitz   5943:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5944:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5945:         $caname = $env{'user.name'};
1.1024    www      5946:         $cadom = $env{'user.domain'};
1.832     bisitz   5947:     }
1.1028    raeburn  5948:     if (($caname ne '') && ($cadom ne '')) {
                   5949:         return "/priv/$cadom/$caname/";
                   5950:     }
                   5951:     return;
1.832     bisitz   5952: }
                   5953: 
                   5954: ##############################################
                   5955: =pod
                   5956: 
1.822     bisitz   5957: =item * &head_subbox()
                   5958: 
                   5959: Inputs: $content (contains HTML code with page functions, etc.)
                   5960: 
                   5961: Returns: HTML div with $content
                   5962:          To be included in page header
                   5963: 
                   5964: =cut
                   5965: 
                   5966: sub head_subbox {
                   5967:     my ($content)=@_;
                   5968:     my $output =
1.993     raeburn  5969:         '<div class="LC_head_subbox">'
1.822     bisitz   5970:        .$content
                   5971:        .'</div>'
                   5972: }
                   5973: 
                   5974: ##############################################
                   5975: =pod
                   5976: 
                   5977: =item * &CSTR_pageheader()
                   5978: 
1.1026    raeburn  5979: Input: (optional) filename from which breadcrumb trail is built.
                   5980:        In most cases no input as needed, as $env{'request.filename'}
                   5981:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5982:22):        frameset flag
                   5983:22):        If page header is being requested for use in a frameset, then
                   5984:22):        the second (option) argument -- frameset will be true, and
                   5985:22):        the target attribute set for links should be target="_parent".
          .26(raeb 5986:-24):        If $title is supplied as the third arg, that will be used to
                   5987:-24):        the left of the breadcrumbs tail for the current path.
1.822     bisitz   5988: 
                   5989: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5990:          To be included on Authoring Space pages
1.822     bisitz   5991: 
                   5992: =cut
                   5993: 
                   5994: sub CSTR_pageheader {
1.1075.2.161.  .26(raeb 5995:-24):     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  5996:     if ($trailfile eq '') {
                   5997:         $trailfile = $env{'request.filename'};
                   5998:     }
                   5999: 
                   6000: # this is for resources; directories have customtitle, and crumbs
                   6001: # and select recent are created in lonpubdir.pm
                   6002: 
                   6003:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6004:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  6005:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6006:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6007:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6008: 
                   6009:     my $parentpath = '';
                   6010:     my $lastitem = '';
                   6011:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6012:         $parentpath = $1;
                   6013:         $lastitem = $2;
                   6014:     } else {
                   6015:         $lastitem = $thisdisfn;
                   6016:     }
1.921     bisitz   6017: 
1.1075.2.161.  .26(raeb 6018:-24):     if ($title eq '') {
                   6019:-24):         $title = &mt('Authoring Space');
                   6020:-24):     }
                   6021:-24): 
          .6(raebu 6022:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6023:22):     if ($frameset) {
                   6024:22):         $target = ' target="_parent"';
                   6025:22):         $crumbtarget = '_parent';
          .17(raeb 6026:-23):     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   6027:-23):         $target = '';
                   6028:-23):         $crumbtarget = '';
          .6(raebu 6029:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   6030:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6031:22):         $crumbtarget = $env{'request.deeplink.target'};
                   6032:22):     }
                   6033:22): 
1.921     bisitz   6034:     my $output =
1.822     bisitz   6035:          '<div>'
                   6036:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.161.  .26(raeb 6037:-24):         .'<b>'.$title.'</b> '
          .6(raebu 6038:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6039:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6040: 
                   6041:     if ($lastitem) {
                   6042:         $output .=
                   6043:              '<span class="LC_filename">'
                   6044:             .$lastitem
                   6045:             .'</span>';
                   6046:     }
                   6047:     $output .=
                   6048:          '<br />'
1.1075.2.161.  .6(raebu 6049:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   6050:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6051:         .'</form>'
1.1075.2.161.  .6(raebu 6052:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   6053:         .'</div>';
1.921     bisitz   6054: 
                   6055:     return $output;
1.822     bisitz   6056: }
                   6057: 
1.1075.2.161.  .21(raeb 6058:-24): ##############################################
                   6059:-24): =pod
                   6060:-24): 
                   6061:-24): =item * &nocodemirror()
                   6062:-24): 
                   6063:-24): Input: None
                   6064:-24): 
                   6065:-24): Returns: 1 if CodeMirror is deactivated based on
                   6066:-24):          user's preference, or domain default,
                   6067:-24):          if user indicated use of default.
                   6068:-24): 
                   6069:-24): =cut
                   6070:-24): 
                   6071:-24): sub nocodemirror {
                   6072:-24):     my $nocodem = $env{'environment.nocodemirror'};
                   6073:-24):     unless ($nocodem) {
                   6074:-24):         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6075:-24):         if ($domdefs{'nocodemirror'}) {
                   6076:-24):             $nocodem = 'yes';
                   6077:-24):         }
                   6078:-24):     }
                   6079:-24):     if ($nocodem eq 'yes') {
                   6080:-24):         return 1;
                   6081:-24):     }
                   6082:-24):     return;
                   6083:-24): }
                   6084:-24): 
                   6085:-24): ##############################################
                   6086:-24): =pod
                   6087:-24): 
                   6088:-24): =item * &permitted_editors()
                   6089:-24): 
                   6090:-24): Input: $uri (optional)
                   6091:-24): 
                   6092:-24): Returns: %editors hash in which keys are editors
          .25(raeb 6093:-24):          permitted in current Authoring Space,
                   6094:-24):          or in current course for web pages
                   6095:-24):          created in a course.
                   6096:-24): 
          .21(raeb 6097:-24):          Value for each key is 1. Possible keys
          .25(raeb 6098:-24):          are: edit, xml, and daxe. 
                   6099:-24): 
                   6100:-24):          For a regular Authoring Space, if no specific
          .21(raeb 6101:-24):          set of editors has been set for the Author
                   6102:-24):          who owns the Authoring Space, then the
                   6103:-24):          domain default will be used.  If no domain
                   6104:-24):          default has been set, then the keys will be
                   6105:-24):          edit and xml.
                   6106:-24): 
          .25(raeb 6107:-24):          For a course author, or for web pages created
                   6108:-24):          in a course, if no specific set of editors has
                   6109:-24):          been set for the course, then the domain
                   6110:-24):          course default will be used. If no domain
                   6111:-24):          course default has been set, then the keys
                   6112:-24):          will be edit and xml.
                   6113:-24): 
          .21(raeb 6114:-24): =cut
                   6115:-24): 
                   6116:-24): sub permitted_editors {
                   6117:-24):     my ($uri) = @_;
          .25(raeb 6118:-24):     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
          .21(raeb 6119:-24):     if ($env{'request.role'} =~ m{^au\./}) {
                   6120:-24):         $is_author = 1;
                   6121:-24):     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6122:-24):         ($audom,$auname) = ($1,$2);
                   6123:-24):         if (($audom ne '') && ($auname ne '')) {
                   6124:-24):             if (($env{'user.domain'} eq $audom) &&
                   6125:-24):                 ($env{'user.name'} eq $auname)) {
                   6126:-24):                 $is_author = 1;
                   6127:-24):             } else {
                   6128:-24):                 $is_coauthor = 1;
                   6129:-24):             }
                   6130:-24):         }
                   6131:-24):     } elsif ($env{'request.course.id'}) {
          .25(raeb 6132:-24):         my ($cdom,$cnum);
                   6133:-24):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6134:-24):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6135:-24):         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
                   6136:-24):             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6137:-24):             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
                   6138:-24):             $is_course = 1;
                   6139:-24):         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
          .21(raeb 6140:-24):             ($audom,$auname) = ($1,$2);
                   6141:-24):         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6142:-24):             ($audom,$auname) = ($1,$2);
                   6143:-24):         } elsif (($uri eq '/daxesave') &&
          .25(raeb 6144:-24):                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6145:-24):                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6146:-24):             $is_course = 1;
                   6147:-24):         } elsif (($uri eq '/daxesave') &&
          .21(raeb 6148:-24):                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6149:-24):             ($audom,$auname) = ($1,$2);
                   6150:-24):         }
          .25(raeb 6151:-24):         unless ($is_course) {
                   6152:-24):             if (($audom ne '') && ($auname ne '')) {
                   6153:-24):                 if (($env{'user.domain'} eq $audom) &&
                   6154:-24):                     ($env{'user.name'} eq $auname)) {
                   6155:-24):                     $is_author = 1;
                   6156:-24):                 } else {
                   6157:-24):                     $is_coauthor = 1;
                   6158:-24):                 }
          .21(raeb 6159:-24):             }
                   6160:-24):         }
                   6161:-24):     }
                   6162:-24):     if ($is_author) {
                   6163:-24):         if (exists($env{'environment.editors'})) {
                   6164:-24):             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6165:-24):         } else {
                   6166:-24):             %editors = ( edit => 1,
                   6167:-24):                          xml => 1,
                   6168:-24):                        );
                   6169:-24):         }
                   6170:-24):     } elsif ($is_coauthor) {
                   6171:-24):         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6172:-24):             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6173:-24):         } else {
                   6174:-24):             %editors = ( edit => 1,
                   6175:-24):                          xml => 1,
                   6176:-24):                        );
                   6177:-24):         }
          .25(raeb 6178:-24):     } elsif ($is_course) {
                   6179:-24):         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6180:-24):             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6181:-24):         } else {
                   6182:-24):             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6183:-24):             if (exists($domdefaults{'crseditors'})) {
                   6184:-24):                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6185:-24):             } else {
                   6186:-24):                 %editors = ( edit => 1,
                   6187:-24):                              xml => 1,
                   6188:-24):                            );
                   6189:-24):             }
                   6190:-24):         }
          .21(raeb 6191:-24):     } else {
                   6192:-24):         %editors = ( edit => 1,
                   6193:-24):                      xml => 1,
                   6194:-24):                    );
                   6195:-24):     }
                   6196:-24):     return %editors;
                   6197:-24): }
                   6198:-24): 
1.60      matthew  6199: ###############################################
                   6200: ###############################################
                   6201: 
                   6202: =pod
                   6203: 
1.112     bowersj2 6204: =back
                   6205: 
1.549     albertel 6206: =head1 HTML Helpers
1.112     bowersj2 6207: 
                   6208: =over 4
                   6209: 
                   6210: =item * &bodytag()
1.60      matthew  6211: 
                   6212: Returns a uniform header for LON-CAPA web pages.
                   6213: 
                   6214: Inputs: 
                   6215: 
1.112     bowersj2 6216: =over 4
                   6217: 
                   6218: =item * $title, A title to be displayed on the page.
                   6219: 
                   6220: =item * $function, the current role (can be undef).
                   6221: 
                   6222: =item * $addentries, extra parameters for the <body> tag.
                   6223: 
                   6224: =item * $bodyonly, if defined, only return the <body> tag.
                   6225: 
                   6226: =item * $domain, if defined, force a given domain.
                   6227: 
                   6228: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6229:             text interface only)
1.60      matthew  6230: 
1.814     bisitz   6231: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6232:                      navigational links
1.317     albertel 6233: 
1.338     albertel 6234: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6235: 
1.1075.2.12  raeburn  6236: =item * $no_inline_link, if true and in remote mode, don't show the
                   6237:          'Switch To Inline Menu' link
                   6238: 
1.460     albertel 6239: =item * $args, optional argument valid values are
                   6240:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  6241:             use_absolute     -> for external resource or syllabus, this will
                   6242:                                 contain https://<hostname> if server uses
                   6243:                                 https (as per hosts.tab), but request is for http
                   6244:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6245: 
1.1075.2.15  raeburn  6246: =item * $advtoolsref, optional argument, ref to an array containing
                   6247:             inlineremote items to be added in "Functions" menu below
                   6248:             breadcrumbs.
                   6249: 
1.1075.2.161.  .1(raebu 6250:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   6251:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   6252:21):             the scope of use, i.e., launch was for access to a single, a map
                   6253:21):             or the entire course.
                   6254:21): 
                   6255:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6256:21):             context, this will contain the URL for the landing item in
                   6257:21):             the course, after launch from an LTI Consumer
                   6258:21): 
                   6259:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6260:21):             context, this will contain a reference to hash of items
                   6261:21):             to be included in the page header and/or inline menu.
                   6262:21): 
          .8(raebu 6263:22): =item * $menucoll, optional argument, if specific menu collection is in
                   6264:22):             effect, either set as the default for the course, or set for
                   6265:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   6266:22):             then $menucoll will be the number of that collection.
                   6267:22): 
                   6268:22): =item * $menuref, optional argument, reference to a hash, containing the
                   6269:22):             menu options included for the menu in effect, based on the
                   6270:22):             configuration for the numbered menu collection in use.
                   6271:22): 
                   6272:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6273:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6274:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   6275:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6276:22):             being called a second time.
                   6277:22): 
1.112     bowersj2 6278: =back
                   6279: 
1.60      matthew  6280: Returns: A uniform header for LON-CAPA web pages.  
                   6281: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6282: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6283: other decorations will be returned.
                   6284: 
                   6285: =cut
                   6286: 
1.54      www      6287: sub bodytag {
1.831     bisitz   6288:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 6289:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 6290:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6291: 
1.954     raeburn  6292:     my $public;
                   6293:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6294:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6295:         $public = 1;
                   6296:     }
1.460     albertel 6297:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  6298:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  6299:     my $hostname = $args->{'hostname'};
1.339     albertel 6300: 
1.183     matthew  6301:     $function = &get_users_function() if (!$function);
1.339     albertel 6302:     my $img =    &designparm($function.'.img',$domain);
                   6303:     my $font =   &designparm($function.'.font',$domain);
                   6304:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6305: 
1.803     bisitz   6306:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6307: 		   'bgcolor' => $pgbg,
1.339     albertel 6308: 		   'text'    => $font,
                   6309:                    'alink'   => &designparm($function.'.alink',$domain),
                   6310: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6311: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6312:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6313: 
1.63      www      6314:  # role and realm
1.1075.2.68  raeburn  6315:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6316:     if ($realm) {
                   6317:         $realm = '/'.$realm;
                   6318:     }
1.1075.2.159  raeburn  6319:     if ($role eq 'ca') {
1.479     albertel 6320:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6321:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6322:     } 
1.55      www      6323: # realm
1.1075.2.158  raeburn  6324:     my ($cid,$sec);
1.258     albertel 6325:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  6326:         $cid = $env{'request.course.id'};
                   6327:         if ($env{'request.course.sec'}) {
                   6328:             $sec = $env{'request.course.sec'};
                   6329:         }
                   6330:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6331:         if (&Apache::lonnet::is_course($1,$2)) {
                   6332:             $cid = $1.'_'.$2;
                   6333:             $sec = $3;
                   6334:         }
                   6335:     }
                   6336:     if ($cid) {
1.378     raeburn  6337:         if ($env{'request.role'} !~ /^cr/) {
                   6338:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6339:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6340:             if ($env{'request.role.desc'}) {
                   6341:                 $role = $env{'request.role.desc'};
                   6342:             } else {
                   6343:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6344:             }
1.1075.2.115  raeburn  6345:         } else {
                   6346:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6347:         }
1.1075.2.158  raeburn  6348:         if ($sec) {
                   6349:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6350:         }   
1.1075.2.158  raeburn  6351: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6352:     } else {
                   6353:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6354:     }
1.433     albertel 6355: 
1.359     albertel 6356:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6357: 
1.438     albertel 6358:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6359: 
1.101     www      6360: # construct main body tag
1.359     albertel 6361:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6362: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6363: 
1.1075.2.38  raeburn  6364:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6365: 
                   6366:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6367:         return $bodytag;
1.1075.2.38  raeburn  6368:     }
1.359     albertel 6369: 
1.954     raeburn  6370:     if ($public) {
1.433     albertel 6371: 	undef($role);
                   6372:     }
1.1075.2.158  raeburn  6373: 
1.1075.2.161.  .1(raebu 6374:21):     my $showcrstitle = 1;
                   6375:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6376:21):         if (ref($ltimenu) eq 'HASH') {
                   6377:21):             unless ($ltimenu->{'role'}) {
                   6378:21):                 undef($role);
                   6379:21):             }
                   6380:21):             unless ($ltimenu->{'coursetitle'}) {
                   6381:21):                 $realm='&nbsp;';
                   6382:21):                 $showcrstitle = 0;
                   6383:21):             }
                   6384:21):         }
                   6385:21):     } elsif (($cid) && ($menucoll)) {
                   6386:21):         if (ref($menuref) eq 'HASH') {
                   6387:21):             unless ($menuref->{'role'}) {
                   6388:21):                 undef($role);
                   6389:21):             }
                   6390:21):             unless ($menuref->{'crs'}) {
                   6391:21):                 $realm='&nbsp;';
                   6392:21):                 $showcrstitle = 0;
                   6393:21):             }
                   6394:21):         }
                   6395:21):     }
                   6396:21): 
1.762     bisitz   6397:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6398:     #
                   6399:     # Extra info if you are the DC
                   6400:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6401:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6402:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6403:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6404:         $dc_info =~ s/\s+$//;
1.359     albertel 6405:     }
                   6406: 
1.1075.2.161.  .1(raebu 6407:21):     my $crstype;
                   6408:21):     if ($cid) {
                   6409:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6410:21):     } elsif ($args->{'crstype'}) {
                   6411:21):         $crstype = $args->{'crstype'};
                   6412:21):     }
                   6413:21): 
1.1075.2.108  raeburn  6414:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6415: 
1.1075.2.13  raeburn  6416:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6417: 
1.1075.2.38  raeburn  6418: 
                   6419: 
1.1075.2.21  raeburn  6420:     my $funclist;
                   6421:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.161.  .31(raeb 6422:-24):         unless ($args->{'switchserver'}) {
                   6423:-24):             $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
                   6424:-24):                         Apache::lonmenu::serverform();
                   6425:-24):             my $forbodytag;
                   6426:-24):             &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6427:-24):                                                 $forcereg,$args->{'group'},
                   6428:-24):                                                 $args->{'bread_crumbs'},
                   6429:-24):                                                 $advtoolsref,'','',\$forbodytag);
                   6430:-24):             unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6431:-24):                 $funclist = $forbodytag;
                   6432:-24):             }
                   6433:-24):             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
1.1075.2.21  raeburn  6434:         }
                   6435:     } else {
1.903     droeschl 6436: 
                   6437:         #    if ($env{'request.state'} eq 'construct') {
                   6438:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6439:         #    }
                   6440: 
1.1075.2.161.  .31(raeb 6441:-24):         my $need_endlcint;
                   6442:-24):         unless ($args->{'switchserver'}) {
                   6443:-24):             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   6444:-24):                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   6445:-24):             $need_endlcint = 1;
                   6446:-24):         }
1.359     albertel 6447: 
1.1075.2.161.  .23(raeb 6448:-24):         my $collapsible;
          .21(raeb 6449:-24):         if ($args->{'collapsible_header'} ne '') {
          .23(raeb 6450:-24):             $collapsible = 1;
                   6451:-24):             my ($menustate,$tiptext,$divclass);
                   6452:-24):             if ($args->{'start_collapsed'}) {
                   6453:-24):                 $menustate = 'collapsed';
                   6454:-24):                 $tiptext = 'display';
                   6455:-24):                 $divclass = 'hidden';
                   6456:-24):             } else {
                   6457:-24):                 $menustate = 'expanded';
                   6458:-24):                 $tiptext = 'hide';
                   6459:-24):                 $divclass = 'shown';
                   6460:-24):             }
                   6461:-24):             my $alttext = &mt('menu state: '.$menustate);
                   6462:-24):             my $tooltip = &mt($tiptext.' standard menus');
          .21(raeb 6463:-24):             $bodytag .= <<"END";
                   6464:-24): <div id="LC_expandingContainer" style="display:inline;">
                   6465:-24): <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
          .23(raeb 6466:-24): <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   6467:-24): <div class="LC_menus_content $divclass">
          .21(raeb 6468:-24): END
                   6469:-24):         }
          .30(raeb 6470:-24):         if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} eq 'construct')) {
                   6471:-24):             unless ($env{'form.inhibitmenu'}) {
                   6472:-24):                 $bodytag .= &inline_for_remote($public,$role,$realm,$dc_info,$no_inline_link);
                   6473:-24):             }
                   6474:-24):         } elsif (!$args->{'no_primary_menu'}) {
          .4(raebu 6475:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6476:22):                                                               $args->{'links_disabled'},
          .21(raeb 6477:-24):                                                               $args->{'links_target'},
          .23(raeb 6478:-24):                                                               $collapsible);
          .1(raebu 6479:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6480:21):                 if ($dc_info) {
                   6481:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6482:21):                 }
                   6483:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6484:21):                                <em>$realm</em> $dc_info</div>|;
          .31(raeb 6485:-24):                 if ($need_endlcint) {
                   6486:-24):                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6487:-24):                 }
          .1(raebu 6488:21):                 return $bodytag;
1.1075.2.1  raeburn  6489:             }
1.894     droeschl 6490: 
1.1075.2.161.  .1(raebu 6491:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6492:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6493:21):             }
1.916     droeschl 6494: 
1.1075.2.161.  .1(raebu 6495:21):             $bodytag .= $right;
1.852     droeschl 6496: 
1.1075.2.161.  .1(raebu 6497:21):             if ($dc_info) {
                   6498:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6499:21):             }
                   6500:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6501:         }
1.916     droeschl 6502: 
1.1075.2.61  raeburn  6503:         #if directed to not display the secondary menu, don't.
                   6504:         if ($args->{'no_secondary_menu'}) {
1.1075.2.161.  .31(raeb 6505:-24):             if ($need_endlcint) {
                   6506:-24):                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6507:-24):             }
1.1075.2.61  raeburn  6508:             return $bodytag;
                   6509:         }
1.903     droeschl 6510:         #don't show menus for public users
1.954     raeburn  6511:         if (!$public){
1.1075.2.161.  .30(raeb 6512:-24):             unless (($args->{'no_inline_menu'}) ||
                   6513:-24):                     (($env{'environment.remote'} eq 'on') &&
                   6514:-24):                      ($env{'request.state'} eq 'construct'))) {
          .1(raebu 6515:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6516:21):                                                             $args->{'no_primary_menu'},
                   6517:21):                                                             $menucoll,$menuref,
          .6(raebu 6518:22):                                                             $args->{'links_disabled'},
                   6519:22):                                                             $args->{'links_target'});
          .1(raebu 6520:21):             }
1.903     droeschl 6521:             $bodytag .= Apache::lonmenu::serverform();
1.1075.2.161.  .31(raeb 6522:-24):             if ($need_endlcint) {
                   6523:-24):                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6524:-24):             }
1.920     raeburn  6525:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6526:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6527:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6528:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6529:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6530:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6531:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6532:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6533:             } else {
1.1075.2.21  raeburn  6534:                 my $forbodytag;
                   6535:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6536:                                                     $forcereg,$args->{'group'},
                   6537:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6538:                                                     $advtoolsref,'',$hostname,
                   6539:                                                     \$forbodytag);
1.1075.2.21  raeburn  6540:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6541:                     $bodytag .= $forbodytag;
                   6542:                 }
1.920     raeburn  6543:             }
1.1075.2.161.  .31(raeb 6544:-24):         } else {
                   6545:-24):             # this is to separate menu from content when there's no secondary
1.903     droeschl 6546:             # menu. Especially needed for public accessible ressources.
                   6547:             $bodytag .= '<hr style="clear:both" />';
1.1075.2.161.  .31(raeb 6548:-24):             if ($need_endlcint) {
                   6549:-24):                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6550:-24):             }
1.235     raeburn  6551:         }
1.1075.2.161.  .21(raeb 6552:-24):         if ($args->{'collapsible_header'} ne '') {
                   6553:-24):             $bodytag .= $args->{'collapsible_header'}.
                   6554:-24):                         '<div id="LC_collapsible_separator"></div>'.
                   6555:-24):                         '</div></div>';
                   6556:-24):         }
1.235     raeburn  6557:         return $bodytag;
1.1075.2.12  raeburn  6558:     }
                   6559: 
                   6560: #
                   6561: # Top frame rendering, Remote is up
                   6562: #
                   6563: 
1.1075.2.161.  .31(raeb 6564:-24):     my $linkattr;
                   6565:-24):     if ($args->{'links_disabled'}) {
                   6566:-24):         $linkattr = 'class="LCisDisabled" aria-disabled="true"';
                   6567:-24):     }
                   6568:-24): 
1.1075.2.60  raeburn  6569:     my $help=($no_inline_link?''
1.1075.2.161.  .31(raeb 6570:-24):               :&top_nav_help('Help',$linkattr));
1.1075.2.60  raeburn  6571: 
1.1075.2.12  raeburn  6572:     # Explicit link to get inline menu
                   6573:     my $menu= ($no_inline_link?''
1.1075.2.161.  .31(raeb 6574:-24):                :'<a href="/adm/remote?action=collapse" $linkattr target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
1.1075.2.12  raeburn  6575: 
                   6576:     if ($dc_info) {
                   6577:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6578:     }
                   6579: 
1.1075.2.38  raeburn  6580:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6581:     unless ($public) {
1.1075.2.161.  .31(raeb 6582:-24):         my $class = 'LC_menubuttons_link';
                   6583:-24):         if ($args->{'links_disabled'}) {
                   6584:-24):             $class .= ' LCisDisabled';
                   6585:-24):         }
1.1075.2.38  raeburn  6586:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
1.1075.2.161.  .31(raeb 6587:-24):                                 undef,$class);
1.1075.2.38  raeburn  6588:     }
                   6589: 
1.1075.2.12  raeburn  6590:     unless ($env{'form.inhibitmenu'}) {
1.1075.2.161.  .30(raeb 6591:-24):         $bodytag .= &inline_for_remote($public,$role,$realm,$dc_info,$no_inline_link);
1.1075.2.13  raeburn  6592:     }
1.1075.2.21  raeburn  6593:     return $bodytag."\n".$funclist;
1.182     matthew  6594: }
                   6595: 
1.1075.2.161.  .30(raeb 6596:-24): sub inline_for_remote {
                   6597:-24):     my ($public,$role,$realm,$dc_info,$no_inline_link) = @_;
                   6598:-24):     my $help=($no_inline_link?''
                   6599:-24):               :&Apache::loncommon::top_nav_help('Help'));
                   6600:-24): 
                   6601:-24):     # Explicit link to get inline menu
                   6602:-24):     my $menu= ($no_inline_link?''
                   6603:-24):                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6604:-24): 
                   6605:-24):     if ($dc_info) {
                   6606:-24):         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6607:-24):     }
                   6608:-24): 
                   6609:-24):     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6610:-24):     unless ($public) {
                   6611:-24):         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6612:-24):                                 undef,'LC_menubuttons_link');
                   6613:-24):     }
                   6614:-24): 
                   6615:-24):     return qq|<div id="LC_nav_bar">$name $role</div>
                   6616:-24):               <ol class="LC_primary_menu LC_floatright LC_right">
                   6617:-24):               <li>$help</li>
                   6618:-24):               <li>$menu</li>
                   6619:-24):               </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6620:-24): }
                   6621:-24): 
1.917     raeburn  6622: sub dc_courseid_toggle {
                   6623:     my ($dc_info) = @_;
1.980     raeburn  6624:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6625:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6626:            &mt('(More ...)').'</a></span>'.
                   6627:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6628: }
                   6629: 
1.330     albertel 6630: sub make_attr_string {
                   6631:     my ($register,$attr_ref) = @_;
                   6632: 
                   6633:     if ($attr_ref && !ref($attr_ref)) {
                   6634: 	die("addentries Must be a hash ref ".
                   6635: 	    join(':',caller(1))." ".
                   6636: 	    join(':',caller(0))." ");
                   6637:     }
                   6638: 
                   6639:     if ($register) {
1.339     albertel 6640: 	my ($on_load,$on_unload);
                   6641: 	foreach my $key (keys(%{$attr_ref})) {
                   6642: 	    if      (lc($key) eq 'onload') {
                   6643: 		$on_load.=$attr_ref->{$key}.';';
                   6644: 		delete($attr_ref->{$key});
                   6645: 
                   6646: 	    } elsif (lc($key) eq 'onunload') {
                   6647: 		$on_unload.=$attr_ref->{$key}.';';
                   6648: 		delete($attr_ref->{$key});
                   6649: 	    }
                   6650: 	}
1.1075.2.12  raeburn  6651:         if ($env{'environment.remote'} eq 'on') {
                   6652:             $attr_ref->{'onload'}  =
                   6653:                 &Apache::lonmenu::loadevents().  $on_load;
                   6654:             $attr_ref->{'onunload'}=
                   6655:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6656:         } else {  
                   6657: 	    $attr_ref->{'onload'}  = $on_load;
                   6658: 	    $attr_ref->{'onunload'}= $on_unload;
                   6659:         }
1.330     albertel 6660:     }
1.339     albertel 6661: 
1.330     albertel 6662:     my $attr_string;
1.1075.2.56  raeburn  6663:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6664: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6665:     }
                   6666:     return $attr_string;
                   6667: }
                   6668: 
                   6669: 
1.182     matthew  6670: ###############################################
1.251     albertel 6671: ###############################################
                   6672: 
                   6673: =pod
                   6674: 
                   6675: =item * &endbodytag()
                   6676: 
                   6677: Returns a uniform footer for LON-CAPA web pages.
                   6678: 
1.635     raeburn  6679: Inputs: 1 - optional reference to an args hash
                   6680: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6681: a 'Continue' link is not displayed if the page contains an
                   6682: internal redirect in the <head></head> section,
                   6683: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6684: 
                   6685: =cut
                   6686: 
                   6687: sub endbodytag {
1.635     raeburn  6688:     my ($args) = @_;
1.1075.2.6  raeburn  6689:     my $endbodytag;
                   6690:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6691:         $endbodytag='</body>';
                   6692:     }
1.315     albertel 6693:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6694:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6695:22):             my ($endbodyjs,$idattr);
                   6696:22):             if ($env{'internal.head.to_opener'}) {
                   6697:22):                 my $linkid = 'LC_continue_link';
                   6698:22):                 $idattr = ' id="'.$linkid.'"';
                   6699:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6700:22):                 $endbodyjs=<<ENDJS;
                   6701:22): <script type="text/javascript">
                   6702:22): // <![CDATA[
                   6703:22): function ebFunction(evt) {
                   6704:22):     evt.preventDefault();
                   6705:22):     var dest = '$redirect_for_js';
                   6706:22):     if (window.opener != null && !window.opener.closed) {
                   6707:22):         window.opener.location.href=dest;
                   6708:22):         window.close();
                   6709:22):     } else {
                   6710:22):         window.location.href=dest;
                   6711:22):     }
                   6712:22):     return false;
                   6713:22): }
                   6714:22): 
                   6715:22): \$(document).ready(function () {
                   6716:22):   if (document.getElementById('$linkid')) {
                   6717:22):     var clickelem = document.getElementById('$linkid');
                   6718:22):     clickelem.addEventListener('click',ebFunction,false);
                   6719:22):   }
                   6720:22): });
                   6721:22): // ]]>
                   6722:22): </script>
                   6723:22): ENDJS
                   6724:22):             }
1.635     raeburn  6725: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6726:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6727: 	        &mt('Continue').'</a>'.
                   6728: 	        $endbodytag;
                   6729:         }
1.315     albertel 6730:     }
1.1075.2.161.  .19(raeb 6731:-23):     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   6732:-23):         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   6733:-23):     }
1.251     albertel 6734:     return $endbodytag;
                   6735: }
                   6736: 
1.352     albertel 6737: =pod
                   6738: 
                   6739: =item * &standard_css()
                   6740: 
                   6741: Returns a style sheet
                   6742: 
                   6743: Inputs: (all optional)
                   6744:             domain         -> force to color decorate a page for a specific
                   6745:                                domain
                   6746:             function       -> force usage of a specific rolish color scheme
                   6747:             bgcolor        -> override the default page bgcolor
                   6748: 
                   6749: =cut
                   6750: 
1.343     albertel 6751: sub standard_css {
1.345     albertel 6752:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6753:     $function  = &get_users_function() if (!$function);
                   6754:     my $img    = &designparm($function.'.img',   $domain);
                   6755:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6756:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6757:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6758: #second colour for later usage
1.345     albertel 6759:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6760:     my $pgbg_or_bgcolor =
                   6761: 	         $bgcolor ||
1.352     albertel 6762: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6763:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6764:     my $alink  = &designparm($function.'.alink', $domain);
                   6765:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6766:     my $link   = &designparm($function.'.link',  $domain);
                   6767: 
1.602     albertel 6768:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6769:     my $mono                 = 'monospace';
1.850     bisitz   6770:     my $data_table_head      = $sidebg;
                   6771:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6772:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6773:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6774:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6775:     my $mail_new             = '#FFBB77';
                   6776:     my $mail_new_hover       = '#DD9955';
                   6777:     my $mail_read            = '#BBBB77';
                   6778:     my $mail_read_hover      = '#999944';
                   6779:     my $mail_replied         = '#AAAA88';
                   6780:     my $mail_replied_hover   = '#888855';
                   6781:     my $mail_other           = '#99BBBB';
                   6782:     my $mail_other_hover     = '#669999';
1.391     albertel 6783:     my $table_header         = '#DDDDDD';
1.489     raeburn  6784:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6785:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6786:     my $button_hover         = '#BF2317';
1.392     albertel 6787: 
1.608     albertel 6788:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6789:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6790:                                              : '0 3px 0 4px';
1.448     albertel 6791: 
1.523     albertel 6792: 
1.343     albertel 6793:     return <<END;
1.947     droeschl 6794: 
                   6795: /* needed for iframe to allow 100% height in FF */
                   6796: body, html { 
                   6797:     margin: 0;
                   6798:     padding: 0 0.5%;
                   6799:     height: 99%; /* to avoid scrollbars */
                   6800: }
                   6801: 
1.795     www      6802: body {
1.911     bisitz   6803:   font-family: $sans;
                   6804:   line-height:130%;
                   6805:   font-size:0.83em;
                   6806:   color:$font;
1.795     www      6807: }
                   6808: 
1.959     onken    6809: a:focus,
                   6810: a:focus img {
1.795     www      6811:   color: red;
                   6812: }
1.698     harmsja  6813: 
1.911     bisitz   6814: form, .inline {
                   6815:   display: inline;
1.795     www      6816: }
1.721     harmsja  6817: 
1.1075.2.161.  .21(raeb 6818:-24): .LC_menus_content.shown{
          .24(raeb 6819:-24):   display: block;
          .21(raeb 6820:-24): }
                   6821:-24): 
                   6822:-24): .LC_menus_content.hidden {
                   6823:-24):   display: none;
                   6824:-24): }
                   6825:-24): 
1.795     www      6826: .LC_right {
1.911     bisitz   6827:   text-align:right;
1.795     www      6828: }
                   6829: 
                   6830: .LC_middle {
1.911     bisitz   6831:   vertical-align:middle;
1.795     www      6832: }
1.721     harmsja  6833: 
1.1075.2.38  raeburn  6834: .LC_floatleft {
                   6835:   float: left;
                   6836: }
                   6837: 
                   6838: .LC_floatright {
                   6839:   float: right;
                   6840: }
                   6841: 
1.911     bisitz   6842: .LC_400Box {
                   6843:   width:400px;
                   6844: }
1.721     harmsja  6845: 
1.1075.2.161.  .21(raeb 6846:-24): #LC_collapsible_separator {
                   6847:-24):     border: 1px solid black;
                   6848:-24):     width: 99.9%;
                   6849:-24):     height: 0px;
                   6850:-24): }
                   6851:-24): 
1.947     droeschl 6852: .LC_iframecontainer {
                   6853:     width: 98%;
                   6854:     margin: 0;
                   6855:     position: fixed;
                   6856:     top: 8.5em;
                   6857:     bottom: 0;
                   6858: }
                   6859: 
                   6860: .LC_iframecontainer iframe{
                   6861:     border: none;
                   6862:     width: 100%;
                   6863:     height: 100%;
                   6864: }
                   6865: 
1.778     bisitz   6866: .LC_filename {
                   6867:   font-family: $mono;
                   6868:   white-space:pre;
1.921     bisitz   6869:   font-size: 120%;
1.778     bisitz   6870: }
                   6871: 
                   6872: .LC_fileicon {
                   6873:   border: none;
                   6874:   height: 1.3em;
                   6875:   vertical-align: text-bottom;
                   6876:   margin-right: 0.3em;
                   6877:   text-decoration:none;
                   6878: }
                   6879: 
1.1008    www      6880: .LC_setting {
                   6881:   text-decoration:underline;
                   6882: }
                   6883: 
1.350     albertel 6884: .LC_error {
                   6885:   color: red;
                   6886: }
1.795     www      6887: 
1.1075.2.15  raeburn  6888: .LC_warning {
                   6889:   color: darkorange;
                   6890: }
                   6891: 
1.457     albertel 6892: .LC_diff_removed {
1.733     bisitz   6893:   color: red;
1.394     albertel 6894: }
1.532     albertel 6895: 
                   6896: .LC_info,
1.457     albertel 6897: .LC_success,
                   6898: .LC_diff_added {
1.350     albertel 6899:   color: green;
                   6900: }
1.795     www      6901: 
1.802     bisitz   6902: div.LC_confirm_box {
                   6903:   background-color: #FAFAFA;
                   6904:   border: 1px solid $lg_border_color;
                   6905:   margin-right: 0;
                   6906:   padding: 5px;
                   6907: }
                   6908: 
                   6909: div.LC_confirm_box .LC_error img,
                   6910: div.LC_confirm_box .LC_success img {
                   6911:   vertical-align: middle;
                   6912: }
                   6913: 
1.1075.2.108  raeburn  6914: .LC_maxwidth {
                   6915:   max-width: 100%;
                   6916:   height: auto;
                   6917: }
                   6918: 
                   6919: .LC_textsize_mobile {
                   6920:   \@media only screen and (max-device-width: 480px) {
                   6921:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6922:   }
                   6923: }
                   6924: 
1.440     albertel 6925: .LC_icon {
1.771     droeschl 6926:   border: none;
1.790     droeschl 6927:   vertical-align: middle;
1.771     droeschl 6928: }
                   6929: 
1.543     albertel 6930: .LC_docs_spacer {
                   6931:   width: 25px;
                   6932:   height: 1px;
1.771     droeschl 6933:   border: none;
1.543     albertel 6934: }
1.346     albertel 6935: 
1.532     albertel 6936: .LC_internal_info {
1.735     bisitz   6937:   color: #999999;
1.532     albertel 6938: }
                   6939: 
1.794     www      6940: .LC_discussion {
1.1050    www      6941:   background: $data_table_dark;
1.911     bisitz   6942:   border: 1px solid black;
                   6943:   margin: 2px;
1.794     www      6944: }
                   6945: 
                   6946: .LC_disc_action_left {
1.1050    www      6947:   background: $sidebg;
1.911     bisitz   6948:   text-align: left;
1.1050    www      6949:   padding: 4px;
                   6950:   margin: 2px;
1.794     www      6951: }
                   6952: 
                   6953: .LC_disc_action_right {
1.1050    www      6954:   background: $sidebg;
1.911     bisitz   6955:   text-align: right;
1.1050    www      6956:   padding: 4px;
                   6957:   margin: 2px;
1.794     www      6958: }
                   6959: 
                   6960: .LC_disc_new_item {
1.911     bisitz   6961:   background: white;
                   6962:   border: 2px solid red;
1.1050    www      6963:   margin: 4px;
                   6964:   padding: 4px;
1.794     www      6965: }
                   6966: 
                   6967: .LC_disc_old_item {
1.911     bisitz   6968:   background: white;
1.1050    www      6969:   margin: 4px;
                   6970:   padding: 4px;
1.794     www      6971: }
                   6972: 
1.458     albertel 6973: table.LC_pastsubmission {
                   6974:   border: 1px solid black;
                   6975:   margin: 2px;
                   6976: }
                   6977: 
1.924     bisitz   6978: table#LC_menubuttons {
1.345     albertel 6979:   width: 100%;
                   6980:   background: $pgbg;
1.392     albertel 6981:   border: 2px;
1.402     albertel 6982:   border-collapse: separate;
1.803     bisitz   6983:   padding: 0;
1.345     albertel 6984: }
1.392     albertel 6985: 
1.801     tempelho 6986: table#LC_title_bar a {
                   6987:   color: $fontmenu;
                   6988: }
1.836     bisitz   6989: 
1.807     droeschl 6990: table#LC_title_bar {
1.819     tempelho 6991:   clear: both;
1.836     bisitz   6992:   display: none;
1.807     droeschl 6993: }
                   6994: 
1.795     www      6995: table#LC_title_bar,
1.933     droeschl 6996: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6997: table#LC_title_bar.LC_with_remote {
1.359     albertel 6998:   width: 100%;
1.392     albertel 6999:   border-color: $pgbg;
                   7000:   border-style: solid;
                   7001:   border-width: $border;
1.379     albertel 7002:   background: $pgbg;
1.801     tempelho 7003:   color: $fontmenu;
1.392     albertel 7004:   border-collapse: collapse;
1.803     bisitz   7005:   padding: 0;
1.819     tempelho 7006:   margin: 0;
1.359     albertel 7007: }
1.795     www      7008: 
1.933     droeschl 7009: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7010:     margin: 0;
                   7011:     padding: 0;
1.933     droeschl 7012:     position: relative;
                   7013:     list-style: none;
1.913     droeschl 7014: }
1.933     droeschl 7015: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7016:     display: inline;
                   7017: }
1.933     droeschl 7018: 
                   7019: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7020:     padding: 0;
1.933     droeschl 7021:     margin: 0;
                   7022:     float: left;
1.913     droeschl 7023: }
1.933     droeschl 7024: .LC_breadcrumb_tools_tools {
                   7025:     padding: 0;
                   7026:     margin: 0;
1.913     droeschl 7027:     float: right;
                   7028: }
                   7029: 
1.359     albertel 7030: table#LC_title_bar td {
                   7031:   background: $tabbg;
                   7032: }
1.795     www      7033: 
1.911     bisitz   7034: table#LC_menubuttons img {
1.803     bisitz   7035:   border: none;
1.346     albertel 7036: }
1.795     www      7037: 
1.842     droeschl 7038: .LC_breadcrumbs_component {
1.911     bisitz   7039:   float: right;
                   7040:   margin: 0 1em;
1.357     albertel 7041: }
1.842     droeschl 7042: .LC_breadcrumbs_component img {
1.911     bisitz   7043:   vertical-align: middle;
1.777     tempelho 7044: }
1.795     www      7045: 
1.1075.2.108  raeburn  7046: .LC_breadcrumbs_hoverable {
                   7047:   background: $sidebg;
                   7048: }
                   7049: 
1.383     albertel 7050: td.LC_table_cell_checkbox {
                   7051:   text-align: center;
                   7052: }
1.795     www      7053: 
                   7054: .LC_fontsize_small {
1.911     bisitz   7055:   font-size: 70%;
1.705     tempelho 7056: }
                   7057: 
1.844     bisitz   7058: #LC_breadcrumbs {
1.911     bisitz   7059:   clear:both;
                   7060:   background: $sidebg;
                   7061:   border-bottom: 1px solid $lg_border_color;
                   7062:   line-height: 2.5em;
1.933     droeschl 7063:   overflow: hidden;
1.911     bisitz   7064:   margin: 0;
                   7065:   padding: 0;
1.995     raeburn  7066:   text-align: left;
1.819     tempelho 7067: }
1.862     bisitz   7068: 
1.1075.2.16  raeburn  7069: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7070:   clear:both;
                   7071:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7072:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  7073:   margin: 0 0 10px 0;
1.966     bisitz   7074:   padding: 3px;
1.995     raeburn  7075:   text-align: left;
1.822     bisitz   7076: }
                   7077: 
1.795     www      7078: .LC_fontsize_medium {
1.911     bisitz   7079:   font-size: 85%;
1.705     tempelho 7080: }
                   7081: 
1.795     www      7082: .LC_fontsize_large {
1.911     bisitz   7083:   font-size: 120%;
1.705     tempelho 7084: }
                   7085: 
1.346     albertel 7086: .LC_menubuttons_inline_text {
                   7087:   color: $font;
1.698     harmsja  7088:   font-size: 90%;
1.701     harmsja  7089:   padding-left:3px;
1.346     albertel 7090: }
                   7091: 
1.934     droeschl 7092: .LC_menubuttons_inline_text img{
                   7093:   vertical-align: middle;
                   7094: }
                   7095: 
1.1051    www      7096: li.LC_menubuttons_inline_text img {
1.951     onken    7097:   cursor:pointer;
1.1002    droeschl 7098:   text-decoration: none;
1.951     onken    7099: }
                   7100: 
1.526     www      7101: .LC_menubuttons_link {
                   7102:   text-decoration: none;
                   7103: }
1.795     www      7104: 
1.522     albertel 7105: .LC_menubuttons_category {
1.521     www      7106:   color: $font;
1.526     www      7107:   background: $pgbg;
1.521     www      7108:   font-size: larger;
                   7109:   font-weight: bold;
                   7110: }
                   7111: 
1.346     albertel 7112: td.LC_menubuttons_text {
1.911     bisitz   7113:   color: $font;
1.346     albertel 7114: }
1.706     harmsja  7115: 
1.346     albertel 7116: .LC_current_location {
                   7117:   background: $tabbg;
                   7118: }
1.795     www      7119: 
1.1075.2.134  raeburn  7120: td.LC_zero_height {
                   7121:   line-height: 0;
                   7122:   cellpadding: 0;
                   7123: }
                   7124: 
1.938     bisitz   7125: table.LC_data_table {
1.347     albertel 7126:   border: 1px solid #000000;
1.402     albertel 7127:   border-collapse: separate;
1.426     albertel 7128:   border-spacing: 1px;
1.610     albertel 7129:   background: $pgbg;
1.347     albertel 7130: }
1.795     www      7131: 
1.422     albertel 7132: .LC_data_table_dense {
                   7133:   font-size: small;
                   7134: }
1.795     www      7135: 
1.507     raeburn  7136: table.LC_nested_outer {
                   7137:   border: 1px solid #000000;
1.589     raeburn  7138:   border-collapse: collapse;
1.803     bisitz   7139:   border-spacing: 0;
1.507     raeburn  7140:   width: 100%;
                   7141: }
1.795     www      7142: 
1.879     raeburn  7143: table.LC_innerpickbox,
1.507     raeburn  7144: table.LC_nested {
1.803     bisitz   7145:   border: none;
1.589     raeburn  7146:   border-collapse: collapse;
1.803     bisitz   7147:   border-spacing: 0;
1.507     raeburn  7148:   width: 100%;
                   7149: }
1.795     www      7150: 
1.911     bisitz   7151: table.LC_data_table tr th,
                   7152: table.LC_calendar tr th,
1.879     raeburn  7153: table.LC_prior_tries tr th,
                   7154: table.LC_innerpickbox tr th {
1.349     albertel 7155:   font-weight: bold;
                   7156:   background-color: $data_table_head;
1.801     tempelho 7157:   color:$fontmenu;
1.701     harmsja  7158:   font-size:90%;
1.347     albertel 7159: }
1.795     www      7160: 
1.879     raeburn  7161: table.LC_innerpickbox tr th,
                   7162: table.LC_innerpickbox tr td {
                   7163:   vertical-align: top;
                   7164: }
                   7165: 
1.711     raeburn  7166: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7167:   background-color: #CCCCCC;
1.711     raeburn  7168:   font-weight: bold;
                   7169:   text-align: left;
                   7170: }
1.795     www      7171: 
1.912     bisitz   7172: table.LC_data_table tr.LC_odd_row > td {
                   7173:   background-color: $data_table_light;
                   7174:   padding: 2px;
                   7175:   vertical-align: top;
                   7176: }
                   7177: 
1.809     bisitz   7178: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7179:   background-color: $data_table_light;
1.912     bisitz   7180:   vertical-align: top;
                   7181: }
                   7182: 
                   7183: table.LC_data_table tr.LC_even_row > td {
                   7184:   background-color: $data_table_dark;
1.425     albertel 7185:   padding: 2px;
1.900     bisitz   7186:   vertical-align: top;
1.347     albertel 7187: }
1.795     www      7188: 
1.809     bisitz   7189: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7190:   background-color: $data_table_dark;
1.900     bisitz   7191:   vertical-align: top;
1.347     albertel 7192: }
1.795     www      7193: 
1.425     albertel 7194: table.LC_data_table tr.LC_data_table_highlight td {
                   7195:   background-color: $data_table_darker;
                   7196: }
1.795     www      7197: 
1.639     raeburn  7198: table.LC_data_table tr td.LC_leftcol_header {
                   7199:   background-color: $data_table_head;
                   7200:   font-weight: bold;
                   7201: }
1.795     www      7202: 
1.451     albertel 7203: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7204: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7205:   font-weight: bold;
                   7206:   font-style: italic;
                   7207:   text-align: center;
                   7208:   padding: 8px;
1.347     albertel 7209: }
1.795     www      7210: 
1.1075.2.30  raeburn  7211: table.LC_data_table tr.LC_empty_row td,
                   7212: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7213:   background-color: $sidebg;
                   7214: }
                   7215: 
                   7216: table.LC_nested tr.LC_empty_row td {
                   7217:   background-color: #FFFFFF;
                   7218: }
                   7219: 
1.890     droeschl 7220: table.LC_caption {
                   7221: }
                   7222: 
1.507     raeburn  7223: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7224:   padding: 4ex
                   7225: }
1.795     www      7226: 
1.507     raeburn  7227: table.LC_nested_outer tr th {
                   7228:   font-weight: bold;
1.801     tempelho 7229:   color:$fontmenu;
1.507     raeburn  7230:   background-color: $data_table_head;
1.701     harmsja  7231:   font-size: small;
1.507     raeburn  7232:   border-bottom: 1px solid #000000;
                   7233: }
1.795     www      7234: 
1.507     raeburn  7235: table.LC_nested_outer tr td.LC_subheader {
                   7236:   background-color: $data_table_head;
                   7237:   font-weight: bold;
                   7238:   font-size: small;
                   7239:   border-bottom: 1px solid #000000;
                   7240:   text-align: right;
1.451     albertel 7241: }
1.795     www      7242: 
1.507     raeburn  7243: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7244:   background-color: #CCCCCC;
1.451     albertel 7245:   font-weight: bold;
                   7246:   font-size: small;
1.507     raeburn  7247:   text-align: center;
                   7248: }
1.795     www      7249: 
1.589     raeburn  7250: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7251: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7252:   text-align: left;
1.451     albertel 7253: }
1.795     www      7254: 
1.507     raeburn  7255: table.LC_nested td {
1.735     bisitz   7256:   background-color: #FFFFFF;
1.451     albertel 7257:   font-size: small;
1.507     raeburn  7258: }
1.795     www      7259: 
1.507     raeburn  7260: table.LC_nested_outer tr th.LC_right_item,
                   7261: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7262: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7263: table.LC_nested tr td.LC_right_item {
1.451     albertel 7264:   text-align: right;
                   7265: }
                   7266: 
1.507     raeburn  7267: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7268:   background-color: #EEEEEE;
1.451     albertel 7269: }
                   7270: 
1.473     raeburn  7271: table.LC_createuser {
                   7272: }
                   7273: 
                   7274: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7275:   font-size: small;
1.473     raeburn  7276: }
                   7277: 
                   7278: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7279:   background-color: #CCCCCC;
1.473     raeburn  7280:   font-weight: bold;
                   7281:   text-align: center;
                   7282: }
                   7283: 
1.349     albertel 7284: table.LC_calendar {
                   7285:   border: 1px solid #000000;
                   7286:   border-collapse: collapse;
1.917     raeburn  7287:   width: 98%;
1.349     albertel 7288: }
1.795     www      7289: 
1.349     albertel 7290: table.LC_calendar_pickdate {
                   7291:   font-size: xx-small;
                   7292: }
1.795     www      7293: 
1.349     albertel 7294: table.LC_calendar tr td {
                   7295:   border: 1px solid #000000;
                   7296:   vertical-align: top;
1.917     raeburn  7297:   width: 14%;
1.349     albertel 7298: }
1.795     www      7299: 
1.349     albertel 7300: table.LC_calendar tr td.LC_calendar_day_empty {
                   7301:   background-color: $data_table_dark;
                   7302: }
1.795     www      7303: 
1.779     bisitz   7304: table.LC_calendar tr td.LC_calendar_day_current {
                   7305:   background-color: $data_table_highlight;
1.777     tempelho 7306: }
1.795     www      7307: 
1.938     bisitz   7308: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7309:   background-color: $mail_new;
                   7310: }
1.795     www      7311: 
1.938     bisitz   7312: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7313:   background-color: $mail_new_hover;
                   7314: }
1.795     www      7315: 
1.938     bisitz   7316: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7317:   background-color: $mail_read;
                   7318: }
1.795     www      7319: 
1.938     bisitz   7320: /*
                   7321: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7322:   background-color: $mail_read_hover;
                   7323: }
1.938     bisitz   7324: */
1.795     www      7325: 
1.938     bisitz   7326: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7327:   background-color: $mail_replied;
                   7328: }
1.795     www      7329: 
1.938     bisitz   7330: /*
                   7331: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7332:   background-color: $mail_replied_hover;
                   7333: }
1.938     bisitz   7334: */
1.795     www      7335: 
1.938     bisitz   7336: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7337:   background-color: $mail_other;
                   7338: }
1.795     www      7339: 
1.938     bisitz   7340: /*
                   7341: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7342:   background-color: $mail_other_hover;
                   7343: }
1.938     bisitz   7344: */
1.494     raeburn  7345: 
1.777     tempelho 7346: table.LC_data_table tr > td.LC_browser_file,
                   7347: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7348:   background: #AAEE77;
1.389     albertel 7349: }
1.795     www      7350: 
1.777     tempelho 7351: table.LC_data_table tr > td.LC_browser_file_locked,
                   7352: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7353:   background: #FFAA99;
1.387     albertel 7354: }
1.795     www      7355: 
1.777     tempelho 7356: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7357:   background: #888888;
1.779     bisitz   7358: }
1.795     www      7359: 
1.777     tempelho 7360: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7361: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7362:   background: #F8F866;
1.777     tempelho 7363: }
1.795     www      7364: 
1.696     bisitz   7365: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7366:   background: #E0E8FF;
1.387     albertel 7367: }
1.696     bisitz   7368: 
1.707     bisitz   7369: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7370:   /* background: #77FF77; */
1.707     bisitz   7371: }
1.795     www      7372: 
1.707     bisitz   7373: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7374:   border-right: 8px solid #FFFF77;
1.707     bisitz   7375: }
1.795     www      7376: 
1.707     bisitz   7377: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7378:   border-right: 8px solid #FFAA77;
1.707     bisitz   7379: }
1.795     www      7380: 
1.707     bisitz   7381: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7382:   border-right: 8px solid #FF7777;
1.707     bisitz   7383: }
1.795     www      7384: 
1.707     bisitz   7385: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7386:   border-right: 8px solid #AAFF77;
1.707     bisitz   7387: }
1.795     www      7388: 
1.707     bisitz   7389: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7390:   border-right: 8px solid #11CC55;
1.707     bisitz   7391: }
                   7392: 
1.388     albertel 7393: span.LC_current_location {
1.701     harmsja  7394:   font-size:larger;
1.388     albertel 7395:   background: $pgbg;
                   7396: }
1.387     albertel 7397: 
1.1029    www      7398: span.LC_current_nav_location {
                   7399:   font-weight:bold;
                   7400:   background: $sidebg;
                   7401: }
                   7402: 
1.395     albertel 7403: span.LC_parm_menu_item {
                   7404:   font-size: larger;
                   7405: }
1.795     www      7406: 
1.395     albertel 7407: span.LC_parm_scope_all {
                   7408:   color: red;
                   7409: }
1.795     www      7410: 
1.395     albertel 7411: span.LC_parm_scope_folder {
                   7412:   color: green;
                   7413: }
1.795     www      7414: 
1.395     albertel 7415: span.LC_parm_scope_resource {
                   7416:   color: orange;
                   7417: }
1.795     www      7418: 
1.395     albertel 7419: span.LC_parm_part {
                   7420:   color: blue;
                   7421: }
1.795     www      7422: 
1.911     bisitz   7423: span.LC_parm_folder,
                   7424: span.LC_parm_symb {
1.395     albertel 7425:   font-size: x-small;
                   7426:   font-family: $mono;
                   7427:   color: #AAAAAA;
                   7428: }
                   7429: 
1.977     bisitz   7430: ul.LC_parm_parmlist li {
                   7431:   display: inline-block;
                   7432:   padding: 0.3em 0.8em;
                   7433:   vertical-align: top;
                   7434:   width: 150px;
                   7435:   border-top:1px solid $lg_border_color;
                   7436: }
                   7437: 
1.795     www      7438: td.LC_parm_overview_level_menu,
                   7439: td.LC_parm_overview_map_menu,
                   7440: td.LC_parm_overview_parm_selectors,
                   7441: td.LC_parm_overview_restrictions  {
1.396     albertel 7442:   border: 1px solid black;
                   7443:   border-collapse: collapse;
                   7444: }
1.795     www      7445: 
1.396     albertel 7446: table.LC_parm_overview_restrictions td {
                   7447:   border-width: 1px 4px 1px 4px;
                   7448:   border-style: solid;
                   7449:   border-color: $pgbg;
                   7450:   text-align: center;
                   7451: }
1.795     www      7452: 
1.396     albertel 7453: table.LC_parm_overview_restrictions th {
                   7454:   background: $tabbg;
                   7455:   border-width: 1px 4px 1px 4px;
                   7456:   border-style: solid;
                   7457:   border-color: $pgbg;
                   7458: }
1.795     www      7459: 
1.398     albertel 7460: table#LC_helpmenu {
1.803     bisitz   7461:   border: none;
1.398     albertel 7462:   height: 55px;
1.803     bisitz   7463:   border-spacing: 0;
1.398     albertel 7464: }
                   7465: 
                   7466: table#LC_helpmenu fieldset legend {
                   7467:   font-size: larger;
                   7468: }
1.795     www      7469: 
1.397     albertel 7470: table#LC_helpmenu_links {
                   7471:   width: 100%;
                   7472:   border: 1px solid black;
                   7473:   background: $pgbg;
1.803     bisitz   7474:   padding: 0;
1.397     albertel 7475:   border-spacing: 1px;
                   7476: }
1.795     www      7477: 
1.397     albertel 7478: table#LC_helpmenu_links tr td {
                   7479:   padding: 1px;
                   7480:   background: $tabbg;
1.399     albertel 7481:   text-align: center;
                   7482:   font-weight: bold;
1.397     albertel 7483: }
1.396     albertel 7484: 
1.795     www      7485: table#LC_helpmenu_links a:link,
                   7486: table#LC_helpmenu_links a:visited,
1.397     albertel 7487: table#LC_helpmenu_links a:active {
                   7488:   text-decoration: none;
                   7489:   color: $font;
                   7490: }
1.795     www      7491: 
1.397     albertel 7492: table#LC_helpmenu_links a:hover {
                   7493:   text-decoration: underline;
                   7494:   color: $vlink;
                   7495: }
1.396     albertel 7496: 
1.417     albertel 7497: .LC_chrt_popup_exists {
                   7498:   border: 1px solid #339933;
                   7499:   margin: -1px;
                   7500: }
1.795     www      7501: 
1.417     albertel 7502: .LC_chrt_popup_up {
                   7503:   border: 1px solid yellow;
                   7504:   margin: -1px;
                   7505: }
1.795     www      7506: 
1.417     albertel 7507: .LC_chrt_popup {
                   7508:   border: 1px solid #8888FF;
                   7509:   background: #CCCCFF;
                   7510: }
1.795     www      7511: 
1.421     albertel 7512: table.LC_pick_box {
                   7513:   border-collapse: separate;
                   7514:   background: white;
                   7515:   border: 1px solid black;
                   7516:   border-spacing: 1px;
                   7517: }
1.795     www      7518: 
1.421     albertel 7519: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7520:   background: $sidebg;
1.421     albertel 7521:   font-weight: bold;
1.900     bisitz   7522:   text-align: left;
1.740     bisitz   7523:   vertical-align: top;
1.421     albertel 7524:   width: 184px;
                   7525:   padding: 8px;
                   7526: }
1.795     www      7527: 
1.579     raeburn  7528: table.LC_pick_box td.LC_pick_box_value {
                   7529:   text-align: left;
                   7530:   padding: 8px;
                   7531: }
1.795     www      7532: 
1.579     raeburn  7533: table.LC_pick_box td.LC_pick_box_select {
                   7534:   text-align: left;
                   7535:   padding: 8px;
                   7536: }
1.795     www      7537: 
1.424     albertel 7538: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7539:   padding: 0;
1.421     albertel 7540:   height: 1px;
                   7541:   background: black;
                   7542: }
1.795     www      7543: 
1.421     albertel 7544: table.LC_pick_box td.LC_pick_box_submit {
                   7545:   text-align: right;
                   7546: }
1.795     www      7547: 
1.579     raeburn  7548: table.LC_pick_box td.LC_evenrow_value {
                   7549:   text-align: left;
                   7550:   padding: 8px;
                   7551:   background-color: $data_table_light;
                   7552: }
1.795     www      7553: 
1.579     raeburn  7554: table.LC_pick_box td.LC_oddrow_value {
                   7555:   text-align: left;
                   7556:   padding: 8px;
                   7557:   background-color: $data_table_light;
                   7558: }
1.795     www      7559: 
1.579     raeburn  7560: span.LC_helpform_receipt_cat {
                   7561:   font-weight: bold;
                   7562: }
1.795     www      7563: 
1.424     albertel 7564: table.LC_group_priv_box {
                   7565:   background: white;
                   7566:   border: 1px solid black;
                   7567:   border-spacing: 1px;
                   7568: }
1.795     www      7569: 
1.424     albertel 7570: table.LC_group_priv_box td.LC_pick_box_title {
                   7571:   background: $tabbg;
                   7572:   font-weight: bold;
                   7573:   text-align: right;
                   7574:   width: 184px;
                   7575: }
1.795     www      7576: 
1.424     albertel 7577: table.LC_group_priv_box td.LC_groups_fixed {
                   7578:   background: $data_table_light;
                   7579:   text-align: center;
                   7580: }
1.795     www      7581: 
1.424     albertel 7582: table.LC_group_priv_box td.LC_groups_optional {
                   7583:   background: $data_table_dark;
                   7584:   text-align: center;
                   7585: }
1.795     www      7586: 
1.424     albertel 7587: table.LC_group_priv_box td.LC_groups_functionality {
                   7588:   background: $data_table_darker;
                   7589:   text-align: center;
                   7590:   font-weight: bold;
                   7591: }
1.795     www      7592: 
1.424     albertel 7593: table.LC_group_priv td {
                   7594:   text-align: left;
1.803     bisitz   7595:   padding: 0;
1.424     albertel 7596: }
                   7597: 
                   7598: .LC_navbuttons {
                   7599:   margin: 2ex 0ex 2ex 0ex;
                   7600: }
1.795     www      7601: 
1.423     albertel 7602: .LC_topic_bar {
                   7603:   font-weight: bold;
                   7604:   background: $tabbg;
1.918     wenzelju 7605:   margin: 1em 0em 1em 2em;
1.805     bisitz   7606:   padding: 3px;
1.918     wenzelju 7607:   font-size: 1.2em;
1.423     albertel 7608: }
1.795     www      7609: 
1.423     albertel 7610: .LC_topic_bar span {
1.918     wenzelju 7611:   left: 0.5em;
                   7612:   position: absolute;
1.423     albertel 7613:   vertical-align: middle;
1.918     wenzelju 7614:   font-size: 1.2em;
1.423     albertel 7615: }
1.795     www      7616: 
1.423     albertel 7617: table.LC_course_group_status {
                   7618:   margin: 20px;
                   7619: }
1.795     www      7620: 
1.423     albertel 7621: table.LC_status_selector td {
                   7622:   vertical-align: top;
                   7623:   text-align: center;
1.424     albertel 7624:   padding: 4px;
                   7625: }
1.795     www      7626: 
1.599     albertel 7627: div.LC_feedback_link {
1.616     albertel 7628:   clear: both;
1.829     kalberla 7629:   background: $sidebg;
1.779     bisitz   7630:   width: 100%;
1.829     kalberla 7631:   padding-bottom: 10px;
                   7632:   border: 1px $tabbg solid;
1.833     kalberla 7633:   height: 22px;
                   7634:   line-height: 22px;
                   7635:   padding-top: 5px;
                   7636: }
                   7637: 
                   7638: div.LC_feedback_link img {
                   7639:   height: 22px;
1.867     kalberla 7640:   vertical-align:middle;
1.829     kalberla 7641: }
                   7642: 
1.911     bisitz   7643: div.LC_feedback_link a {
1.829     kalberla 7644:   text-decoration: none;
1.489     raeburn  7645: }
1.795     www      7646: 
1.867     kalberla 7647: div.LC_comblock {
1.911     bisitz   7648:   display:inline;
1.867     kalberla 7649:   color:$font;
                   7650:   font-size:90%;
                   7651: }
                   7652: 
                   7653: div.LC_feedback_link div.LC_comblock {
                   7654:   padding-left:5px;
                   7655: }
                   7656: 
                   7657: div.LC_feedback_link div.LC_comblock a {
                   7658:   color:$font;
                   7659: }
                   7660: 
1.489     raeburn  7661: span.LC_feedback_link {
1.858     bisitz   7662:   /* background: $feedback_link_bg; */
1.599     albertel 7663:   font-size: larger;
                   7664: }
1.795     www      7665: 
1.599     albertel 7666: span.LC_message_link {
1.858     bisitz   7667:   /* background: $feedback_link_bg; */
1.599     albertel 7668:   font-size: larger;
                   7669:   position: absolute;
                   7670:   right: 1em;
1.489     raeburn  7671: }
1.421     albertel 7672: 
1.515     albertel 7673: table.LC_prior_tries {
1.524     albertel 7674:   border: 1px solid #000000;
                   7675:   border-collapse: separate;
                   7676:   border-spacing: 1px;
1.515     albertel 7677: }
1.523     albertel 7678: 
1.515     albertel 7679: table.LC_prior_tries td {
1.524     albertel 7680:   padding: 2px;
1.515     albertel 7681: }
1.523     albertel 7682: 
                   7683: .LC_answer_correct {
1.795     www      7684:   background: lightgreen;
                   7685:   color: darkgreen;
                   7686:   padding: 6px;
1.523     albertel 7687: }
1.795     www      7688: 
1.523     albertel 7689: .LC_answer_charged_try {
1.797     www      7690:   background: #FFAAAA;
1.795     www      7691:   color: darkred;
                   7692:   padding: 6px;
1.523     albertel 7693: }
1.795     www      7694: 
1.779     bisitz   7695: .LC_answer_not_charged_try,
1.523     albertel 7696: .LC_answer_no_grade,
                   7697: .LC_answer_late {
1.795     www      7698:   background: lightyellow;
1.523     albertel 7699:   color: black;
1.795     www      7700:   padding: 6px;
1.523     albertel 7701: }
1.795     www      7702: 
1.523     albertel 7703: .LC_answer_previous {
1.795     www      7704:   background: lightblue;
                   7705:   color: darkblue;
                   7706:   padding: 6px;
1.523     albertel 7707: }
1.795     www      7708: 
1.779     bisitz   7709: .LC_answer_no_message {
1.777     tempelho 7710:   background: #FFFFFF;
                   7711:   color: black;
1.795     www      7712:   padding: 6px;
1.779     bisitz   7713: }
1.795     www      7714: 
1.1075.2.140  raeburn  7715: .LC_answer_unknown,
                   7716: .LC_answer_warning {
1.779     bisitz   7717:   background: orange;
                   7718:   color: black;
1.795     www      7719:   padding: 6px;
1.777     tempelho 7720: }
1.795     www      7721: 
1.529     albertel 7722: span.LC_prior_numerical,
                   7723: span.LC_prior_string,
                   7724: span.LC_prior_custom,
                   7725: span.LC_prior_reaction,
                   7726: span.LC_prior_math {
1.925     bisitz   7727:   font-family: $mono;
1.523     albertel 7728:   white-space: pre;
                   7729: }
                   7730: 
1.525     albertel 7731: span.LC_prior_string {
1.925     bisitz   7732:   font-family: $mono;
1.525     albertel 7733:   white-space: pre;
                   7734: }
                   7735: 
1.523     albertel 7736: table.LC_prior_option {
                   7737:   width: 100%;
                   7738:   border-collapse: collapse;
                   7739: }
1.795     www      7740: 
1.911     bisitz   7741: table.LC_prior_rank,
1.795     www      7742: table.LC_prior_match {
1.528     albertel 7743:   border-collapse: collapse;
                   7744: }
1.795     www      7745: 
1.528     albertel 7746: table.LC_prior_option tr td,
                   7747: table.LC_prior_rank tr td,
                   7748: table.LC_prior_match tr td {
1.524     albertel 7749:   border: 1px solid #000000;
1.515     albertel 7750: }
                   7751: 
1.855     bisitz   7752: .LC_nobreak {
1.544     albertel 7753:   white-space: nowrap;
1.519     raeburn  7754: }
                   7755: 
1.576     raeburn  7756: span.LC_cusr_emph {
                   7757:   font-style: italic;
                   7758: }
                   7759: 
1.633     raeburn  7760: span.LC_cusr_subheading {
                   7761:   font-weight: normal;
                   7762:   font-size: 85%;
                   7763: }
                   7764: 
1.861     bisitz   7765: div.LC_docs_entry_move {
1.859     bisitz   7766:   border: 1px solid #BBBBBB;
1.545     albertel 7767:   background: #DDDDDD;
1.861     bisitz   7768:   width: 22px;
1.859     bisitz   7769:   padding: 1px;
                   7770:   margin: 0;
1.545     albertel 7771: }
                   7772: 
1.861     bisitz   7773: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7774: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7775:   font-size: x-small;
                   7776: }
1.795     www      7777: 
1.861     bisitz   7778: .LC_docs_entry_parameter {
                   7779:   white-space: nowrap;
                   7780: }
                   7781: 
1.544     albertel 7782: .LC_docs_copy {
1.545     albertel 7783:   color: #000099;
1.544     albertel 7784: }
1.795     www      7785: 
1.544     albertel 7786: .LC_docs_cut {
1.545     albertel 7787:   color: #550044;
1.544     albertel 7788: }
1.795     www      7789: 
1.544     albertel 7790: .LC_docs_rename {
1.545     albertel 7791:   color: #009900;
1.544     albertel 7792: }
1.795     www      7793: 
1.544     albertel 7794: .LC_docs_remove {
1.545     albertel 7795:   color: #990000;
                   7796: }
                   7797: 
1.1075.2.134  raeburn  7798: .LC_domprefs_email,
1.547     albertel 7799: .LC_docs_reinit_warn,
                   7800: .LC_docs_ext_edit {
                   7801:   font-size: x-small;
                   7802: }
                   7803: 
1.545     albertel 7804: table.LC_docs_adddocs td,
                   7805: table.LC_docs_adddocs th {
                   7806:   border: 1px solid #BBBBBB;
                   7807:   padding: 4px;
                   7808:   background: #DDDDDD;
1.543     albertel 7809: }
                   7810: 
1.584     albertel 7811: table.LC_sty_begin {
                   7812:   background: #BBFFBB;
                   7813: }
1.795     www      7814: 
1.584     albertel 7815: table.LC_sty_end {
                   7816:   background: #FFBBBB;
                   7817: }
                   7818: 
1.589     raeburn  7819: table.LC_double_column {
1.803     bisitz   7820:   border-width: 0;
1.589     raeburn  7821:   border-collapse: collapse;
                   7822:   width: 100%;
                   7823:   padding: 2px;
                   7824: }
                   7825: 
                   7826: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7827:   top: 2px;
1.589     raeburn  7828:   left: 2px;
                   7829:   width: 47%;
                   7830:   vertical-align: top;
                   7831: }
                   7832: 
                   7833: table.LC_double_column tr td.LC_right_col {
                   7834:   top: 2px;
1.779     bisitz   7835:   right: 2px;
1.589     raeburn  7836:   width: 47%;
                   7837:   vertical-align: top;
                   7838: }
                   7839: 
1.591     raeburn  7840: div.LC_left_float {
                   7841:   float: left;
                   7842:   padding-right: 5%;
1.597     albertel 7843:   padding-bottom: 4px;
1.591     raeburn  7844: }
                   7845: 
                   7846: div.LC_clear_float_header {
1.597     albertel 7847:   padding-bottom: 2px;
1.591     raeburn  7848: }
                   7849: 
                   7850: div.LC_clear_float_footer {
1.597     albertel 7851:   padding-top: 10px;
1.591     raeburn  7852:   clear: both;
                   7853: }
                   7854: 
1.597     albertel 7855: div.LC_grade_show_user {
1.941     bisitz   7856: /*  border-left: 5px solid $sidebg; */
                   7857:   border-top: 5px solid #000000;
                   7858:   margin: 50px 0 0 0;
1.936     bisitz   7859:   padding: 15px 0 5px 10px;
1.597     albertel 7860: }
1.795     www      7861: 
1.936     bisitz   7862: div.LC_grade_show_user_odd_row {
1.941     bisitz   7863: /*  border-left: 5px solid #000000; */
                   7864: }
                   7865: 
                   7866: div.LC_grade_show_user div.LC_Box {
                   7867:   margin-right: 50px;
1.597     albertel 7868: }
                   7869: 
                   7870: div.LC_grade_submissions,
                   7871: div.LC_grade_message_center,
1.936     bisitz   7872: div.LC_grade_info_links {
1.597     albertel 7873:   margin: 5px;
                   7874:   width: 99%;
                   7875:   background: #FFFFFF;
                   7876: }
1.795     www      7877: 
1.597     albertel 7878: div.LC_grade_submissions_header,
1.936     bisitz   7879: div.LC_grade_message_center_header {
1.705     tempelho 7880:   font-weight: bold;
                   7881:   font-size: large;
1.597     albertel 7882: }
1.795     www      7883: 
1.597     albertel 7884: div.LC_grade_submissions_body,
1.936     bisitz   7885: div.LC_grade_message_center_body {
1.597     albertel 7886:   border: 1px solid black;
                   7887:   width: 99%;
                   7888:   background: #FFFFFF;
                   7889: }
1.795     www      7890: 
1.613     albertel 7891: table.LC_scantron_action {
                   7892:   width: 100%;
                   7893: }
1.795     www      7894: 
1.613     albertel 7895: table.LC_scantron_action tr th {
1.698     harmsja  7896:   font-weight:bold;
                   7897:   font-style:normal;
1.613     albertel 7898: }
1.795     www      7899: 
1.779     bisitz   7900: .LC_edit_problem_header,
1.614     albertel 7901: div.LC_edit_problem_footer {
1.705     tempelho 7902:   font-weight: normal;
                   7903:   font-size:  medium;
1.602     albertel 7904:   margin: 2px;
1.1060    bisitz   7905:   background-color: $sidebg;
1.600     albertel 7906: }
1.795     www      7907: 
1.600     albertel 7908: div.LC_edit_problem_header,
1.602     albertel 7909: div.LC_edit_problem_header div,
1.614     albertel 7910: div.LC_edit_problem_footer,
                   7911: div.LC_edit_problem_footer div,
1.602     albertel 7912: div.LC_edit_problem_editxml_header,
                   7913: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7914:   z-index: 100;
1.600     albertel 7915: }
1.795     www      7916: 
1.600     albertel 7917: div.LC_edit_problem_header_title {
1.705     tempelho 7918:   font-weight: bold;
                   7919:   font-size: larger;
1.602     albertel 7920:   background: $tabbg;
                   7921:   padding: 3px;
1.1060    bisitz   7922:   margin: 0 0 5px 0;
1.602     albertel 7923: }
1.795     www      7924: 
1.602     albertel 7925: table.LC_edit_problem_header_title {
                   7926:   width: 100%;
1.600     albertel 7927:   background: $tabbg;
1.602     albertel 7928: }
                   7929: 
1.1075.2.112  raeburn  7930: div.LC_edit_actionbar {
                   7931:     background-color: $sidebg;
                   7932:     margin: 0;
                   7933:     padding: 0;
                   7934:     line-height: 200%;
1.602     albertel 7935: }
1.795     www      7936: 
1.1075.2.112  raeburn  7937: div.LC_edit_actionbar div{
                   7938:     padding: 0;
                   7939:     margin: 0;
                   7940:     display: inline-block;
1.600     albertel 7941: }
1.795     www      7942: 
1.1075.2.34  raeburn  7943: .LC_edit_opt {
                   7944:   padding-left: 1em;
                   7945:   white-space: nowrap;
                   7946: }
                   7947: 
1.1075.2.57  raeburn  7948: .LC_edit_problem_latexhelper{
                   7949:     text-align: right;
                   7950: }
                   7951: 
                   7952: #LC_edit_problem_colorful div{
                   7953:     margin-left: 40px;
                   7954: }
                   7955: 
1.1075.2.112  raeburn  7956: #LC_edit_problem_codemirror div{
                   7957:     margin-left: 0px;
                   7958: }
                   7959: 
1.911     bisitz   7960: img.stift {
1.803     bisitz   7961:   border-width: 0;
                   7962:   vertical-align: middle;
1.677     riegler  7963: }
1.680     riegler  7964: 
1.923     bisitz   7965: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7966:   vertical-align: top;
1.777     tempelho 7967: }
1.795     www      7968: 
1.716     raeburn  7969: div.LC_createcourse {
1.911     bisitz   7970:   margin: 10px 10px 10px 10px;
1.716     raeburn  7971: }
                   7972: 
1.917     raeburn  7973: .LC_dccid {
1.1075.2.38  raeburn  7974:   float: right;
1.917     raeburn  7975:   margin: 0.2em 0 0 0;
                   7976:   padding: 0;
                   7977:   font-size: 90%;
                   7978:   display:none;
                   7979: }
                   7980: 
1.897     wenzelju 7981: ol.LC_primary_menu a:hover,
1.721     harmsja  7982: ol#LC_MenuBreadcrumbs a:hover,
                   7983: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7984: ul#LC_secondary_menu a:hover,
1.721     harmsja  7985: .LC_FormSectionClearButton input:hover
1.795     www      7986: ul.LC_TabContent   li:hover a {
1.952     onken    7987:   color:$button_hover;
1.911     bisitz   7988:   text-decoration:none;
1.693     droeschl 7989: }
                   7990: 
1.779     bisitz   7991: h1 {
1.911     bisitz   7992:   padding: 0;
                   7993:   line-height:130%;
1.693     droeschl 7994: }
1.698     harmsja  7995: 
1.911     bisitz   7996: h2,
                   7997: h3,
                   7998: h4,
                   7999: h5,
                   8000: h6 {
                   8001:   margin: 5px 0 5px 0;
                   8002:   padding: 0;
                   8003:   line-height:130%;
1.693     droeschl 8004: }
1.795     www      8005: 
                   8006: .LC_hcell {
1.911     bisitz   8007:   padding:3px 15px 3px 15px;
                   8008:   margin: 0;
                   8009:   background-color:$tabbg;
                   8010:   color:$fontmenu;
                   8011:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8012: }
1.795     www      8013: 
1.840     bisitz   8014: .LC_Box > .LC_hcell {
1.911     bisitz   8015:   margin: 0 -10px 10px -10px;
1.835     bisitz   8016: }
                   8017: 
1.721     harmsja  8018: .LC_noBorder {
1.911     bisitz   8019:   border: 0;
1.698     harmsja  8020: }
1.693     droeschl 8021: 
1.721     harmsja  8022: .LC_FormSectionClearButton input {
1.911     bisitz   8023:   background-color:transparent;
                   8024:   border: none;
                   8025:   cursor:pointer;
                   8026:   text-decoration:underline;
1.693     droeschl 8027: }
1.763     bisitz   8028: 
                   8029: .LC_help_open_topic {
1.911     bisitz   8030:   color: #FFFFFF;
                   8031:   background-color: #EEEEFF;
                   8032:   margin: 1px;
                   8033:   padding: 4px;
                   8034:   border: 1px solid #000033;
                   8035:   white-space: nowrap;
                   8036:   /* vertical-align: middle; */
1.759     neumanie 8037: }
1.693     droeschl 8038: 
1.911     bisitz   8039: dl,
                   8040: ul,
                   8041: div,
                   8042: fieldset {
                   8043:   margin: 10px 10px 10px 0;
                   8044:   /* overflow: hidden; */
1.693     droeschl 8045: }
1.795     www      8046: 
1.1075.2.161.  .18(raeb 8047:-23): fieldset#LC_selectuser {
                   8048:-23):     margin: 0;
                   8049:-23):     padding: 0;
                   8050:-23): }
                   8051:-23): 
1.1075.2.90  raeburn  8052: article.geogebraweb div {
                   8053:     margin: 0;
                   8054: }
                   8055: 
1.838     bisitz   8056: fieldset > legend {
1.911     bisitz   8057:   font-weight: bold;
                   8058:   padding: 0 5px 0 5px;
1.838     bisitz   8059: }
                   8060: 
1.813     bisitz   8061: #LC_nav_bar {
1.911     bisitz   8062:   float: left;
1.995     raeburn  8063:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8064:   margin: 0 0 2px 0;
1.807     droeschl 8065: }
                   8066: 
1.916     droeschl 8067: #LC_realm {
                   8068:   margin: 0.2em 0 0 0;
                   8069:   padding: 0;
                   8070:   font-weight: bold;
                   8071:   text-align: center;
1.995     raeburn  8072:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8073: }
                   8074: 
1.911     bisitz   8075: #LC_nav_bar em {
                   8076:   font-weight: bold;
                   8077:   font-style: normal;
1.807     droeschl 8078: }
                   8079: 
1.897     wenzelju 8080: ol.LC_primary_menu {
1.934     droeschl 8081:   margin: 0;
1.1075.2.2  raeburn  8082:   padding: 0;
1.807     droeschl 8083: }
                   8084: 
1.852     droeschl 8085: ol#LC_PathBreadcrumbs {
1.911     bisitz   8086:   margin: 0;
1.693     droeschl 8087: }
                   8088: 
1.897     wenzelju 8089: ol.LC_primary_menu li {
1.1075.2.2  raeburn  8090:   color: RGB(80, 80, 80);
                   8091:   vertical-align: middle;
                   8092:   text-align: left;
                   8093:   list-style: none;
1.1075.2.112  raeburn  8094:   position: relative;
1.1075.2.2  raeburn  8095:   float: left;
1.1075.2.112  raeburn  8096:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8097:   line-height: 1.5em;
1.1075.2.2  raeburn  8098: }
                   8099: 
1.1075.2.113  raeburn  8100: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  8101: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  8102:   display: block;
                   8103:   margin: 0;
                   8104:   padding: 0 5px 0 10px;
                   8105:   text-decoration: none;
                   8106: }
                   8107: 
1.1075.2.112  raeburn  8108: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8109:   display: inline-block;
                   8110:   width: 95%;
                   8111:   text-align: left;
                   8112: }
                   8113: 
                   8114: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8115:   display: inline-block;
                   8116:   width: 5%;
                   8117:   float: right;
                   8118:   text-align: right;
                   8119:   font-size: 70%;
                   8120: }
                   8121: 
                   8122: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  8123:   display: none;
1.1075.2.112  raeburn  8124:   width: 15em;
1.1075.2.2  raeburn  8125:   background-color: $data_table_light;
1.1075.2.112  raeburn  8126:   position: absolute;
                   8127:   top: 100%;
                   8128: }
                   8129: 
                   8130: ol.LC_primary_menu ul ul {
                   8131:   left: 100%;
                   8132:   top: 0;
1.1075.2.2  raeburn  8133: }
                   8134: 
1.1075.2.112  raeburn  8135: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  8136:   display: block;
                   8137:   position: absolute;
                   8138:   margin: 0;
                   8139:   padding: 0;
1.1075.2.5  raeburn  8140:   z-index: 2;
1.1075.2.2  raeburn  8141: }
                   8142: 
                   8143: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  8144: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  8145:   font-size: 90%;
1.911     bisitz   8146:   vertical-align: top;
1.1075.2.2  raeburn  8147:   float: none;
1.1075.2.5  raeburn  8148:   border-left: 1px solid black;
                   8149:   border-right: 1px solid black;
1.1075.2.112  raeburn  8150: /* A dark bottom border to visualize different menu options;
                   8151: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8152:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  8153: }
                   8154: 
1.1075.2.112  raeburn  8155: ol.LC_primary_menu li li p:hover {
                   8156:   color:$button_hover;
                   8157:   text-decoration:none;
                   8158:   background-color:$data_table_dark;
1.1075.2.2  raeburn  8159: }
                   8160: 
                   8161: ol.LC_primary_menu li li a:hover {
                   8162:    color:$button_hover;
                   8163:    background-color:$data_table_dark;
1.693     droeschl 8164: }
                   8165: 
1.1075.2.112  raeburn  8166: /* Font-size equal to the size of the predecessors*/
                   8167: ol.LC_primary_menu li:hover li li {
                   8168:   font-size: 100%;
                   8169: }
                   8170: 
1.897     wenzelju 8171: ol.LC_primary_menu li img {
1.911     bisitz   8172:   vertical-align: bottom;
1.934     droeschl 8173:   height: 1.1em;
1.1075.2.3  raeburn  8174:   margin: 0.2em 0 0 0;
1.693     droeschl 8175: }
                   8176: 
1.897     wenzelju 8177: ol.LC_primary_menu a {
1.911     bisitz   8178:   color: RGB(80, 80, 80);
                   8179:   text-decoration: none;
1.693     droeschl 8180: }
1.795     www      8181: 
1.949     droeschl 8182: ol.LC_primary_menu a.LC_new_message {
                   8183:   font-weight:bold;
                   8184:   color: darkred;
                   8185: }
                   8186: 
1.975     raeburn  8187: ol.LC_docs_parameters {
                   8188:   margin-left: 0;
                   8189:   padding: 0;
                   8190:   list-style: none;
                   8191: }
                   8192: 
                   8193: ol.LC_docs_parameters li {
                   8194:   margin: 0;
                   8195:   padding-right: 20px;
                   8196:   display: inline;
                   8197: }
                   8198: 
1.976     raeburn  8199: ol.LC_docs_parameters li:before {
                   8200:   content: "\\002022 \\0020";
                   8201: }
                   8202: 
                   8203: li.LC_docs_parameters_title {
                   8204:   font-weight: bold;
                   8205: }
                   8206: 
                   8207: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8208:   content: "";
                   8209: }
                   8210: 
1.897     wenzelju 8211: ul#LC_secondary_menu {
1.1075.2.23  raeburn  8212:   clear: right;
1.911     bisitz   8213:   color: $fontmenu;
                   8214:   background: $tabbg;
                   8215:   list-style: none;
                   8216:   padding: 0;
                   8217:   margin: 0;
                   8218:   width: 100%;
1.995     raeburn  8219:   text-align: left;
1.1075.2.4  raeburn  8220:   float: left;
1.808     droeschl 8221: }
                   8222: 
1.897     wenzelju 8223: ul#LC_secondary_menu li {
1.911     bisitz   8224:   font-weight: bold;
                   8225:   line-height: 1.8em;
                   8226:   border-right: 1px solid black;
1.1075.2.4  raeburn  8227:   float: left;
                   8228: }
                   8229: 
                   8230: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8231:   background-color: $data_table_light;
                   8232: }
                   8233: 
                   8234: ul#LC_secondary_menu li a {
                   8235:   padding: 0 0.8em;
                   8236: }
                   8237: 
                   8238: ul#LC_secondary_menu li ul {
                   8239:   display: none;
                   8240: }
                   8241: 
                   8242: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8243:   display: block;
                   8244:   position: absolute;
                   8245:   margin: 0;
                   8246:   padding: 0;
                   8247:   list-style:none;
                   8248:   float: none;
                   8249:   background-color: $data_table_light;
1.1075.2.5  raeburn  8250:   z-index: 2;
1.1075.2.10  raeburn  8251:   margin-left: -1px;
1.1075.2.4  raeburn  8252: }
                   8253: 
                   8254: ul#LC_secondary_menu li ul li {
                   8255:   font-size: 90%;
                   8256:   vertical-align: top;
                   8257:   border-left: 1px solid black;
                   8258:   border-right: 1px solid black;
1.1075.2.33  raeburn  8259:   background-color: $data_table_light;
1.1075.2.4  raeburn  8260:   list-style:none;
                   8261:   float: none;
                   8262: }
                   8263: 
                   8264: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8265:   background-color: $data_table_dark;
1.807     droeschl 8266: }
                   8267: 
1.847     tempelho 8268: ul.LC_TabContent {
1.911     bisitz   8269:   display:block;
                   8270:   background: $sidebg;
                   8271:   border-bottom: solid 1px $lg_border_color;
                   8272:   list-style:none;
1.1020    raeburn  8273:   margin: -1px -10px 0 -10px;
1.911     bisitz   8274:   padding: 0;
1.693     droeschl 8275: }
                   8276: 
1.795     www      8277: ul.LC_TabContent li,
                   8278: ul.LC_TabContentBigger li {
1.911     bisitz   8279:   float:left;
1.741     harmsja  8280: }
1.795     www      8281: 
1.897     wenzelju 8282: ul#LC_secondary_menu li a {
1.911     bisitz   8283:   color: $fontmenu;
                   8284:   text-decoration: none;
1.693     droeschl 8285: }
1.795     www      8286: 
1.721     harmsja  8287: ul.LC_TabContent {
1.952     onken    8288:   min-height:20px;
1.721     harmsja  8289: }
1.795     www      8290: 
                   8291: ul.LC_TabContent li {
1.911     bisitz   8292:   vertical-align:middle;
1.959     onken    8293:   padding: 0 16px 0 10px;
1.911     bisitz   8294:   background-color:$tabbg;
                   8295:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8296:   border-left: solid 1px $font;
1.721     harmsja  8297: }
1.795     www      8298: 
1.847     tempelho 8299: ul.LC_TabContent .right {
1.911     bisitz   8300:   float:right;
1.847     tempelho 8301: }
                   8302: 
1.911     bisitz   8303: ul.LC_TabContent li a,
                   8304: ul.LC_TabContent li {
                   8305:   color:rgb(47,47,47);
                   8306:   text-decoration:none;
                   8307:   font-size:95%;
                   8308:   font-weight:bold;
1.952     onken    8309:   min-height:20px;
                   8310: }
                   8311: 
1.959     onken    8312: ul.LC_TabContent li a:hover,
                   8313: ul.LC_TabContent li a:focus {
1.952     onken    8314:   color: $button_hover;
1.959     onken    8315:   background:none;
                   8316:   outline:none;
1.952     onken    8317: }
                   8318: 
                   8319: ul.LC_TabContent li:hover {
                   8320:   color: $button_hover;
                   8321:   cursor:pointer;
1.721     harmsja  8322: }
1.795     www      8323: 
1.911     bisitz   8324: ul.LC_TabContent li.active {
1.952     onken    8325:   color: $font;
1.911     bisitz   8326:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8327:   border-bottom:solid 1px #FFFFFF;
                   8328:   cursor: default;
1.744     ehlerst  8329: }
1.795     www      8330: 
1.959     onken    8331: ul.LC_TabContent li.active a {
                   8332:   color:$font;
                   8333:   background:#FFFFFF;
                   8334:   outline: none;
                   8335: }
1.1047    raeburn  8336: 
                   8337: ul.LC_TabContent li.goback {
                   8338:   float: left;
                   8339:   border-left: none;
                   8340: }
                   8341: 
1.870     tempelho 8342: #maincoursedoc {
1.911     bisitz   8343:   clear:both;
1.870     tempelho 8344: }
                   8345: 
                   8346: ul.LC_TabContentBigger {
1.911     bisitz   8347:   display:block;
                   8348:   list-style:none;
                   8349:   padding: 0;
1.870     tempelho 8350: }
                   8351: 
1.795     www      8352: ul.LC_TabContentBigger li {
1.911     bisitz   8353:   vertical-align:bottom;
                   8354:   height: 30px;
                   8355:   font-size:110%;
                   8356:   font-weight:bold;
                   8357:   color: #737373;
1.841     tempelho 8358: }
                   8359: 
1.957     onken    8360: ul.LC_TabContentBigger li.active {
                   8361:   position: relative;
                   8362:   top: 1px;
                   8363: }
                   8364: 
1.870     tempelho 8365: ul.LC_TabContentBigger li a {
1.911     bisitz   8366:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8367:   height: 30px;
                   8368:   line-height: 30px;
                   8369:   text-align: center;
                   8370:   display: block;
                   8371:   text-decoration: none;
1.958     onken    8372:   outline: none;  
1.741     harmsja  8373: }
1.795     www      8374: 
1.870     tempelho 8375: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8376:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8377:   color:$font;
1.744     ehlerst  8378: }
1.795     www      8379: 
1.870     tempelho 8380: ul.LC_TabContentBigger li b {
1.911     bisitz   8381:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8382:   display: block;
                   8383:   float: left;
                   8384:   padding: 0 30px;
1.957     onken    8385:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8386: }
                   8387: 
1.956     onken    8388: ul.LC_TabContentBigger li:hover b {
                   8389:   color:$button_hover;
                   8390: }
                   8391: 
1.870     tempelho 8392: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8393:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8394:   color:$font;
1.957     onken    8395:   border: 0;
1.741     harmsja  8396: }
1.693     droeschl 8397: 
1.870     tempelho 8398: 
1.862     bisitz   8399: ul.LC_CourseBreadcrumbs {
                   8400:   background: $sidebg;
1.1020    raeburn  8401:   height: 2em;
1.862     bisitz   8402:   padding-left: 10px;
1.1020    raeburn  8403:   margin: 0;
1.862     bisitz   8404:   list-style-position: inside;
                   8405: }
                   8406: 
1.911     bisitz   8407: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8408: ol#LC_PathBreadcrumbs {
1.911     bisitz   8409:   padding-left: 10px;
                   8410:   margin: 0;
1.933     droeschl 8411:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8412: }
                   8413: 
1.911     bisitz   8414: ol#LC_MenuBreadcrumbs li,
                   8415: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8416: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8417:   display: inline;
1.933     droeschl 8418:   white-space: normal;  
1.693     droeschl 8419: }
                   8420: 
1.823     bisitz   8421: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8422: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8423:   text-decoration: none;
                   8424:   font-size:90%;
1.693     droeschl 8425: }
1.795     www      8426: 
1.969     droeschl 8427: ol#LC_MenuBreadcrumbs h1 {
                   8428:   display: inline;
                   8429:   font-size: 90%;
                   8430:   line-height: 2.5em;
                   8431:   margin: 0;
                   8432:   padding: 0;
                   8433: }
                   8434: 
1.795     www      8435: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8436:   text-decoration:none;
                   8437:   font-size:100%;
                   8438:   font-weight:bold;
1.693     droeschl 8439: }
1.795     www      8440: 
1.840     bisitz   8441: .LC_Box {
1.911     bisitz   8442:   border: solid 1px $lg_border_color;
                   8443:   padding: 0 10px 10px 10px;
1.746     neumanie 8444: }
1.795     www      8445: 
1.1020    raeburn  8446: .LC_DocsBox {
                   8447:   border: solid 1px $lg_border_color;
                   8448:   padding: 0 0 10px 10px;
                   8449: }
                   8450: 
1.795     www      8451: .LC_AboutMe_Image {
1.911     bisitz   8452:   float:left;
                   8453:   margin-right:10px;
1.747     neumanie 8454: }
1.795     www      8455: 
                   8456: .LC_Clear_AboutMe_Image {
1.911     bisitz   8457:   clear:left;
1.747     neumanie 8458: }
1.795     www      8459: 
1.721     harmsja  8460: dl.LC_ListStyleClean dt {
1.911     bisitz   8461:   padding-right: 5px;
                   8462:   display: table-header-group;
1.693     droeschl 8463: }
                   8464: 
1.721     harmsja  8465: dl.LC_ListStyleClean dd {
1.911     bisitz   8466:   display: table-row;
1.693     droeschl 8467: }
                   8468: 
1.721     harmsja  8469: .LC_ListStyleClean,
                   8470: .LC_ListStyleSimple,
                   8471: .LC_ListStyleNormal,
1.795     www      8472: .LC_ListStyleSpecial {
1.911     bisitz   8473:   /* display:block; */
                   8474:   list-style-position: inside;
                   8475:   list-style-type: none;
                   8476:   overflow: hidden;
                   8477:   padding: 0;
1.693     droeschl 8478: }
                   8479: 
1.721     harmsja  8480: .LC_ListStyleSimple li,
                   8481: .LC_ListStyleSimple dd,
                   8482: .LC_ListStyleNormal li,
                   8483: .LC_ListStyleNormal dd,
                   8484: .LC_ListStyleSpecial li,
1.795     www      8485: .LC_ListStyleSpecial dd {
1.911     bisitz   8486:   margin: 0;
                   8487:   padding: 5px 5px 5px 10px;
                   8488:   clear: both;
1.693     droeschl 8489: }
                   8490: 
1.721     harmsja  8491: .LC_ListStyleClean li,
                   8492: .LC_ListStyleClean dd {
1.911     bisitz   8493:   padding-top: 0;
                   8494:   padding-bottom: 0;
1.693     droeschl 8495: }
                   8496: 
1.721     harmsja  8497: .LC_ListStyleSimple dd,
1.795     www      8498: .LC_ListStyleSimple li {
1.911     bisitz   8499:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8500: }
                   8501: 
1.721     harmsja  8502: .LC_ListStyleSpecial li,
                   8503: .LC_ListStyleSpecial dd {
1.911     bisitz   8504:   list-style-type: none;
                   8505:   background-color: RGB(220, 220, 220);
                   8506:   margin-bottom: 4px;
1.693     droeschl 8507: }
                   8508: 
1.721     harmsja  8509: table.LC_SimpleTable {
1.911     bisitz   8510:   margin:5px;
                   8511:   border:solid 1px $lg_border_color;
1.795     www      8512: }
1.693     droeschl 8513: 
1.721     harmsja  8514: table.LC_SimpleTable tr {
1.911     bisitz   8515:   padding: 0;
                   8516:   border:solid 1px $lg_border_color;
1.693     droeschl 8517: }
1.795     www      8518: 
                   8519: table.LC_SimpleTable thead {
1.911     bisitz   8520:   background:rgb(220,220,220);
1.693     droeschl 8521: }
                   8522: 
1.721     harmsja  8523: div.LC_columnSection {
1.911     bisitz   8524:   display: block;
                   8525:   clear: both;
                   8526:   overflow: hidden;
                   8527:   margin: 0;
1.693     droeschl 8528: }
                   8529: 
1.721     harmsja  8530: div.LC_columnSection>* {
1.911     bisitz   8531:   float: left;
                   8532:   margin: 10px 20px 10px 0;
                   8533:   overflow:hidden;
1.693     droeschl 8534: }
1.721     harmsja  8535: 
1.795     www      8536: table em {
1.911     bisitz   8537:   font-weight: bold;
                   8538:   font-style: normal;
1.748     schulted 8539: }
1.795     www      8540: 
1.779     bisitz   8541: table.LC_tableBrowseRes,
1.795     www      8542: table.LC_tableOfContent {
1.911     bisitz   8543:   border:none;
                   8544:   border-spacing: 1px;
                   8545:   padding: 3px;
                   8546:   background-color: #FFFFFF;
                   8547:   font-size: 90%;
1.753     droeschl 8548: }
1.789     droeschl 8549: 
1.911     bisitz   8550: table.LC_tableOfContent {
                   8551:   border-collapse: collapse;
1.789     droeschl 8552: }
                   8553: 
1.771     droeschl 8554: table.LC_tableBrowseRes a,
1.768     schulted 8555: table.LC_tableOfContent a {
1.911     bisitz   8556:   background-color: transparent;
                   8557:   text-decoration: none;
1.753     droeschl 8558: }
                   8559: 
1.795     www      8560: table.LC_tableOfContent img {
1.911     bisitz   8561:   border: none;
                   8562:   height: 1.3em;
                   8563:   vertical-align: text-bottom;
                   8564:   margin-right: 0.3em;
1.753     droeschl 8565: }
1.757     schulted 8566: 
1.795     www      8567: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8568:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8569: }
                   8570: 
1.795     www      8571: a#LC_content_toolbar_everything {
1.911     bisitz   8572:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8573: }
                   8574: 
1.795     www      8575: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8576:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8577: }
                   8578: 
1.795     www      8579: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8580:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8581: }
                   8582: 
1.795     www      8583: a#LC_content_toolbar_changefolder {
1.911     bisitz   8584:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8585: }
                   8586: 
1.795     www      8587: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8588:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8589: }
                   8590: 
1.1043    raeburn  8591: a#LC_content_toolbar_edittoplevel {
                   8592:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8593: }
                   8594: 
1.1075.2.161.  .12(raeb 8595:-23): a#LC_content_toolbar_printout {
                   8596:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8597:-23): }
                   8598:-23): 
1.795     www      8599: ul#LC_toolbar li a:hover {
1.911     bisitz   8600:   background-position: bottom center;
1.757     schulted 8601: }
                   8602: 
1.795     www      8603: ul#LC_toolbar {
1.911     bisitz   8604:   padding: 0;
                   8605:   margin: 2px;
                   8606:   list-style:none;
                   8607:   position:relative;
                   8608:   background-color:white;
1.1075.2.9  raeburn  8609:   overflow: auto;
1.757     schulted 8610: }
                   8611: 
1.795     www      8612: ul#LC_toolbar li {
1.911     bisitz   8613:   border:1px solid white;
                   8614:   padding: 0;
                   8615:   margin: 0;
                   8616:   float: left;
                   8617:   display:inline;
                   8618:   vertical-align:middle;
1.1075.2.9  raeburn  8619:   white-space: nowrap;
1.911     bisitz   8620: }
1.757     schulted 8621: 
1.783     amueller 8622: 
1.795     www      8623: a.LC_toolbarItem {
1.911     bisitz   8624:   display:block;
                   8625:   padding: 0;
                   8626:   margin: 0;
                   8627:   height: 32px;
                   8628:   width: 32px;
                   8629:   color:white;
                   8630:   border: none;
                   8631:   background-repeat:no-repeat;
                   8632:   background-color:transparent;
1.757     schulted 8633: }
                   8634: 
1.915     droeschl 8635: ul.LC_funclist {
                   8636:     margin: 0;
                   8637:     padding: 0.5em 1em 0.5em 0;
                   8638: }
                   8639: 
1.933     droeschl 8640: ul.LC_funclist > li:first-child {
                   8641:     font-weight:bold; 
                   8642:     margin-left:0.8em;
                   8643: }
                   8644: 
1.915     droeschl 8645: ul.LC_funclist + ul.LC_funclist {
                   8646:     /* 
                   8647:        left border as a seperator if we have more than
                   8648:        one list 
                   8649:     */
                   8650:     border-left: 1px solid $sidebg;
                   8651:     /* 
                   8652:        this hides the left border behind the border of the 
                   8653:        outer box if element is wrapped to the next 'line' 
                   8654:     */
                   8655:     margin-left: -1px;
                   8656: }
                   8657: 
1.843     bisitz   8658: ul.LC_funclist li {
1.915     droeschl 8659:   display: inline;
1.782     bisitz   8660:   white-space: nowrap;
1.915     droeschl 8661:   margin: 0 0 0 25px;
                   8662:   line-height: 150%;
1.782     bisitz   8663: }
                   8664: 
1.974     wenzelju 8665: .LC_hidden {
                   8666:   display: none;
                   8667: }
                   8668: 
1.1030    www      8669: .LCmodal-overlay {
                   8670: 		position:fixed;
                   8671: 		top:0;
                   8672: 		right:0;
                   8673: 		bottom:0;
                   8674: 		left:0;
                   8675: 		height:100%;
                   8676: 		width:100%;
                   8677: 		margin:0;
                   8678: 		padding:0;
                   8679: 		background:#999;
                   8680: 		opacity:.75;
                   8681: 		filter: alpha(opacity=75);
                   8682: 		-moz-opacity: 0.75;
                   8683: 		z-index:101;
                   8684: }
                   8685: 
                   8686: * html .LCmodal-overlay {   
                   8687: 		position: absolute;
                   8688: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8689: }
                   8690: 
                   8691: .LCmodal-window {
                   8692: 		position:fixed;
                   8693: 		top:50%;
                   8694: 		left:50%;
                   8695: 		margin:0;
                   8696: 		padding:0;
                   8697: 		z-index:102;
                   8698: 	}
                   8699: 
                   8700: * html .LCmodal-window {
                   8701: 		position:absolute;
                   8702: }
                   8703: 
                   8704: .LCclose-window {
                   8705: 		position:absolute;
                   8706: 		width:32px;
                   8707: 		height:32px;
                   8708: 		right:8px;
                   8709: 		top:8px;
                   8710: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8711: 		text-indent:-99999px;
                   8712: 		overflow:hidden;
                   8713: 		cursor:pointer;
                   8714: }
                   8715: 
1.1075.2.158  raeburn  8716: .LCisDisabled {
                   8717:   cursor: not-allowed;
                   8718:   opacity: 0.5;
                   8719: }
                   8720: 
                   8721: a[aria-disabled="true"] {
                   8722:   color: currentColor;
                   8723:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8724:   pointer-events: none;
                   8725:   text-decoration: none;
                   8726: }
                   8727: 
1.1075.2.141  raeburn  8728: pre.LC_wordwrap {
                   8729:   white-space: pre-wrap;
                   8730:   white-space: -moz-pre-wrap;
                   8731:   white-space: -pre-wrap;
                   8732:   white-space: -o-pre-wrap;
                   8733:   word-wrap: break-word;
                   8734: }
                   8735: 
1.1075.2.17  raeburn  8736: /*
1.1075.2.161.  .21(raeb 8737:-24):   styles used for response display
                   8738:-24): */
                   8739:-24): div.LC_radiofoil, div.LC_rankfoil {
                   8740:-24):   margin: .5em 0em .5em 0em;
                   8741:-24): }
                   8742:-24): table.LC_itemgroup {
                   8743:-24):   margin-top: 1em;
                   8744:-24): }
                   8745:-24): 
                   8746:-24): /*
1.1075.2.17  raeburn  8747:   styles used by TTH when "Default set of options to pass to tth/m
                   8748:   when converting TeX" in course settings has been set
                   8749: 
                   8750:   option passed: -t
                   8751: 
                   8752: */
                   8753: 
                   8754: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8755: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8756: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8757: td div.norm {line-height:normal;}
                   8758: 
                   8759: /*
                   8760:   option passed -y3
                   8761: */
                   8762: 
                   8763: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8764: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8765: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8766: 
1.1075.2.161.  .21(raeb 8767:-24): /*
                   8768:-24):   sections with roles, for content only
                   8769:-24): */
                   8770:-24): section[class^="role-"] {
                   8771:-24):   padding-left: 10px;
                   8772:-24):   padding-right: 5px;
                   8773:-24):   margin-top: 8px;
                   8774:-24):   margin-bottom: 8px;
                   8775:-24):   border: 1px solid #2A4;
                   8776:-24):   border-radius: 5px;
                   8777:-24):   box-shadow: 0px 1px 1px #BBB;
                   8778:-24): }
                   8779:-24): section[class^="role-"]>h1 {
                   8780:-24):   position: relative;
                   8781:-24):   margin: 0px;
                   8782:-24):   padding-top: 10px;
                   8783:-24):   padding-left: 40px;
                   8784:-24): }
                   8785:-24): section[class^="role-"]>h1:before {
                   8786:-24):   position: absolute;
                   8787:-24):   left: -5px;
                   8788:-24):   top: 5px;
                   8789:-24): }
                   8790:-24): section.role-activity>h1:before {
                   8791:-24):   content:url('/adm/daxe/images/section_icons/activity.png');
                   8792:-24): }
                   8793:-24): section.role-advice>h1:before {
                   8794:-24):   content:url('/adm/daxe/images/section_icons/advice.png');
                   8795:-24): }
                   8796:-24): section.role-bibliography>h1:before {
                   8797:-24):   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8798:-24): }
                   8799:-24): section.role-citation>h1:before {
                   8800:-24):   content:url('/adm/daxe/images/section_icons/citation.png');
                   8801:-24): }
                   8802:-24): section.role-conclusion>h1:before {
                   8803:-24):   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8804:-24): }
                   8805:-24): section.role-definition>h1:before {
                   8806:-24):   content:url('/adm/daxe/images/section_icons/definition.png');
                   8807:-24): }
                   8808:-24): section.role-demonstration>h1:before {
                   8809:-24):   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8810:-24): }
                   8811:-24): section.role-example>h1:before {
                   8812:-24):   content:url('/adm/daxe/images/section_icons/example.png');
                   8813:-24): }
                   8814:-24): section.role-explanation>h1:before {
                   8815:-24):   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8816:-24): }
                   8817:-24): section.role-introduction>h1:before {
                   8818:-24):   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8819:-24): }
                   8820:-24): section.role-method>h1:before {
                   8821:-24):   content:url('/adm/daxe/images/section_icons/method.png');
                   8822:-24): }
                   8823:-24): section.role-more_information>h1:before {
                   8824:-24):   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8825:-24): }
                   8826:-24): section.role-objectives>h1:before {
                   8827:-24):   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8828:-24): }
                   8829:-24): section.role-prerequisites>h1:before {
                   8830:-24):   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8831:-24): }
                   8832:-24): section.role-remark>h1:before {
                   8833:-24):   content:url('/adm/daxe/images/section_icons/remark.png');
                   8834:-24): }
                   8835:-24): section.role-reminder>h1:before {
                   8836:-24):   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8837:-24): }
                   8838:-24): section.role-summary>h1:before {
                   8839:-24):   content:url('/adm/daxe/images/section_icons/summary.png');
                   8840:-24): }
                   8841:-24): section.role-syntax>h1:before {
                   8842:-24):   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8843:-24): }
                   8844:-24): section.role-warning>h1:before {
                   8845:-24):   content:url('/adm/daxe/images/section_icons/warning.png');
                   8846:-24): }
                   8847:-24): 
1.1075.2.121  raeburn  8848: #LC_minitab_header {
                   8849:   float:left;
                   8850:   width:100%;
                   8851:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8852:   font-size:93%;
                   8853:   line-height:normal;
                   8854:   margin: 0.5em 0 0.5em 0;
                   8855: }
                   8856: #LC_minitab_header ul {
                   8857:   margin:0;
                   8858:   padding:10px 10px 0;
                   8859:   list-style:none;
                   8860: }
                   8861: #LC_minitab_header li {
                   8862:   float:left;
                   8863:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8864:   margin:0;
                   8865:   padding:0 0 0 9px;
                   8866: }
                   8867: #LC_minitab_header a {
                   8868:   display:block;
                   8869:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8870:   padding:5px 15px 4px 6px;
                   8871: }
                   8872: #LC_minitab_header #LC_current_minitab {
                   8873:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8874: }
                   8875: #LC_minitab_header #LC_current_minitab a {
                   8876:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8877:   padding-bottom:5px;
                   8878: }
                   8879: 
                   8880: 
1.343     albertel 8881: END
                   8882: }
                   8883: 
1.306     albertel 8884: =pod
                   8885: 
                   8886: =item * &headtag()
                   8887: 
                   8888: Returns a uniform footer for LON-CAPA web pages.
                   8889: 
1.307     albertel 8890: Inputs: $title - optional title for the head
                   8891:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8892:         $args - optional arguments
1.319     albertel 8893:             force_register - if is true call registerurl so the remote is 
                   8894:                              informed
1.415     albertel 8895:             redirect       -> array ref of
                   8896:                                    1- seconds before redirect occurs
                   8897:                                    2- url to redirect to
                   8898:                                    3- whether the side effect should occur
1.315     albertel 8899:                            (side effect of setting 
                   8900:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8901:22):                                redirected to)
                   8902:22):                                    4- whether the redirect target should be
                   8903:22):                                       the opener of the current (pop-up)
                   8904:22):                                       window (side effect of setting
                   8905:22):                                       $env{'internal.head.to_opener'} to
                   8906:22):                                       1, if true.
          .10(raeb 8907:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8908:             domain         -> force to color decorate a page for a specific
                   8909:                                domain
                   8910:             function       -> force usage of a specific rolish color scheme
                   8911:             bgcolor        -> override the default page bgcolor
1.460     albertel 8912:             no_auto_mt_title
                   8913:                            -> prevent &mt()ing the title arg
1.464     albertel 8914: 
1.306     albertel 8915: =cut
                   8916: 
                   8917: sub headtag {
1.313     albertel 8918:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8919:     
1.363     albertel 8920:     my $function = $args->{'function'} || &get_users_function();
                   8921:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8922:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8923:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8924:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8925: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8926: 		   #time(),
1.418     albertel 8927: 		   $env{'environment.color.timestamp'},
1.363     albertel 8928: 		   $function,$domain,$bgcolor);
                   8929: 
1.369     www      8930:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8931: 
1.308     albertel 8932:     my $result =
                   8933: 	'<head>'.
1.1075.2.56  raeburn  8934: 	&font_settings($args);
1.319     albertel 8935: 
1.1075.2.72  raeburn  8936:     my $inhibitprint;
                   8937:     if ($args->{'print_suppress'}) {
                   8938:         $inhibitprint = &print_suppression();
                   8939:     }
1.1064    raeburn  8940: 
1.1075.2.161.  .31(raeb 8941:-24):     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 8942: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8943:     }
1.1075.2.12  raeburn  8944:     if ($args->{'force_register'}) {
                   8945:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8946:     }
1.436     albertel 8947:     if (!$args->{'no_nav_bar'} 
                   8948: 	&& !$args->{'only_body'}
1.1075.2.161.  .31(raeb 8949:-24): 	&& !$args->{'frameset'}
                   8950:-24): 	&& !$args->{'switchserver'}) {
1.1075.2.52  raeburn  8951: 	$result .= &help_menu_js($httphost);
1.1032    www      8952:         $result.=&modal_window();
1.1038    www      8953:         $result.=&togglebox_script();
1.1034    www      8954:         $result.=&wishlist_window();
1.1041    www      8955:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8956:     } else {
                   8957:         if ($args->{'add_modal'}) {
                   8958:            $result.=&modal_window();
                   8959:         }
                   8960:         if ($args->{'add_wishlist'}) {
                   8961:            $result.=&wishlist_window();
                   8962:         }
1.1038    www      8963:         if ($args->{'add_togglebox'}) {
                   8964:            $result.=&togglebox_script();
                   8965:         }
1.1041    www      8966:         if ($args->{'add_progressbar'}) {
                   8967:            $result.=&LCprogressbarUpdate_script();
                   8968:         }
1.436     albertel 8969:     }
1.314     albertel 8970:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8971:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8972:-22):         if (!$skip_enc_check) {
                   8973:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8974:-22):         }
1.414     albertel 8975: 	if (!$inhibit_continue) {
                   8976: 	    $env{'internal.head.redirect'} = $url;
                   8977: 	}
1.1075.2.161.  .9(raebu 8978:22):         $result.=<<"ADDMETA";
1.313     albertel 8979: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8980:22): ADDMETA
                   8981:22):         if ($to_opener) {
                   8982:22):             $env{'internal.head.to_opener'} = 1;
                   8983:22):             my $dest = &js_escape($url);
                   8984:22):             my $timeout = int($time * 1000);
                   8985:22):             $result .=<<"ENDJS";
                   8986:22): <script type="text/javascript">
                   8987:22): // <![CDATA[
                   8988:22): function LC_To_Opener() {
                   8989:22):     var dest = '$dest';
                   8990:22):     if (dest != '') {
                   8991:22):         if (window.opener != null && !window.opener.closed) {
                   8992:22):             window.opener.location.href=dest;
                   8993:22):             window.close();
                   8994:22):         } else {
                   8995:22):             window.location.href=dest;
                   8996:22):         }
                   8997:22):     }
                   8998:22): }
                   8999:22): \$(document).ready(function () {
                   9000:22):     setTimeout('LC_To_Opener()',$timeout);
                   9001:22): });
                   9002:22): // ]]>
                   9003:22): </script>
                   9004:22): ENDJS
                   9005:22):         } else {
                   9006:22):             $result.=<<"ADDMETA";
1.344     albertel 9007: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9008: ADDMETA
1.1075.2.161.  .9(raebu 9009:22):         }
1.1075.2.89  raeburn  9010:     } else {
                   9011:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9012:             my $requrl = $env{'request.uri'};
                   9013:             if ($requrl eq '') {
                   9014:                 $requrl = $ENV{'REQUEST_URI'};
                   9015:                 $requrl =~ s/\?.+$//;
                   9016:             }
                   9017:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9018:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9019:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9020:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9021:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9022:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  9023:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  9024:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  9025:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9026:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  9027:                             $offload = 1;
1.1075.2.151  raeburn  9028:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9029:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9030:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9031:                                     $offloadoth = 1;
                   9032:                                     $dom_in_use = $env{'user.domain'};
                   9033:                                 }
                   9034:                             }
1.1075.2.145  raeburn  9035:                         }
                   9036:                     }
                   9037:                     unless ($offload) {
                   9038:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9039:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9040:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9041:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9042:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9043:                                         $offload = 1;
1.1075.2.151  raeburn  9044:                                         $offloadoth = 1;
1.1075.2.145  raeburn  9045:                                         $dom_in_use = $env{'user.domain'};
                   9046:                                     }
1.1075.2.89  raeburn  9047:                                 }
1.1075.2.145  raeburn  9048:                             }
                   9049:                         }
                   9050:                     }
                   9051:                     if ($offload) {
1.1075.2.158  raeburn  9052:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  9053:                         if (($newserver eq '') && ($offloadoth)) {
                   9054:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 9055:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  9056:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9057:                             }
                   9058:                         }
1.1075.2.145  raeburn  9059:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9060:                             my $numsec = 5;
                   9061:                             my $timeout = $numsec * 1000;
                   9062:                             my ($newurl,$locknum,%locks,$msg);
                   9063:                             if ($env{'request.role.adv'}) {
                   9064:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9065:                             }
                   9066:                             my $disable_submit = 0;
                   9067:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9068:                                 $disable_submit = 1;
                   9069:                             }
                   9070:                             if ($locknum) {
                   9071:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  9072:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  9073:                                        join(", ",sort(values(%locks)))."\n";
                   9074:                                 if (&show_course()) {
                   9075:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  9076:                                 } else {
1.1075.2.145  raeburn  9077:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   9078:                                 }
                   9079:                             } else {
                   9080:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9081:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9082:                                 }
                   9083:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9084:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9085:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9086:                                     $newurl .= '&role='.$env{'request.role'};
                   9087:                                 }
                   9088:                                 if ($env{'request.symb'}) {
                   9089:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9090:                                     if ($shownsymb =~ m{^/enc/}) {
                   9091:                                         my $reqdmajor = 2;
                   9092:                                         my $reqdminor = 11;
                   9093:                                         my $reqdsubminor = 3;
                   9094:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9095:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9096:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9097:                                         if (($major eq '' && $minor eq '') ||
                   9098:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9099:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9100:                                              ($reqdsubminor > $subminor))))) {
                   9101:                                             undef($shownsymb);
                   9102:                                         }
1.1075.2.89  raeburn  9103:                                     }
1.1075.2.145  raeburn  9104:                                     if ($shownsymb) {
                   9105:                                         &js_escape(\$shownsymb);
                   9106:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  9107:                                     }
1.1075.2.145  raeburn  9108:                                 } else {
                   9109:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9110:                                     &js_escape(\$shownurl);
                   9111:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  9112:                                 }
1.1075.2.145  raeburn  9113:                             }
                   9114:                             &js_escape(\$msg);
                   9115:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  9116: <meta http-equiv="pragma" content="no-cache" />
                   9117: <script type="text/javascript">
1.1075.2.92  raeburn  9118: // <![CDATA[
1.1075.2.89  raeburn  9119: function LC_Offload_Now() {
                   9120:     var dest = "$newurl";
                   9121:     if (dest != '') {
                   9122:         window.location.href="$newurl";
                   9123:     }
                   9124: }
1.1075.2.92  raeburn  9125: \$(document).ready(function () {
                   9126:     window.alert('$msg');
                   9127:     if ($disable_submit) {
1.1075.2.89  raeburn  9128:         \$(".LC_hwk_submit").prop("disabled", true);
                   9129:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  9130:     }
                   9131:     setTimeout('LC_Offload_Now()', $timeout);
                   9132: });
                   9133: // ]]>
1.1075.2.89  raeburn  9134: </script>
                   9135: OFFLOAD
                   9136:                         }
                   9137:                     }
                   9138:                 }
                   9139:             }
                   9140:         }
1.313     albertel 9141:     }
1.306     albertel 9142:     if (!defined($title)) {
                   9143: 	$title = 'The LearningOnline Network with CAPA';
                   9144:     }
1.460     albertel 9145:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.161.  .25(raeb 9146:-24):     if ($title =~ /^LON-CAPA\s+/) {
                   9147:-24):         $result .= '<title> '.$title.'</title>';
                   9148:-24):     } else {
                   9149:-24):         $result .= '<title> LON-CAPA '.$title.'</title>';  
                   9150:-24):     }
                   9151:-24):     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1075.2.61  raeburn  9152:     if (!$args->{'frameset'}) {
                   9153:         $result .= ' /';
                   9154:     }
                   9155:     $result .= '>'
1.1064    raeburn  9156:         .$inhibitprint
1.414     albertel 9157: 	.$head_extra;
1.1075.2.108  raeburn  9158:     my $clientmobile;
                   9159:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9160:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9161:     } else {
                   9162:         $clientmobile = $env{'browser.mobile'};
                   9163:     }
                   9164:     if ($clientmobile) {
1.1075.2.42  raeburn  9165:         $result .= '
                   9166: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9167: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9168:     }
1.1075.2.126  raeburn  9169:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9170:     return $result.'</head>';
1.306     albertel 9171: }
                   9172: 
                   9173: =pod
                   9174: 
1.340     albertel 9175: =item * &font_settings()
                   9176: 
                   9177: Returns neccessary <meta> to set the proper encoding
                   9178: 
1.1075.2.56  raeburn  9179: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9180: 
                   9181: =cut
                   9182: 
                   9183: sub font_settings {
1.1075.2.56  raeburn  9184:     my ($args) = @_;
1.340     albertel 9185:     my $headerstring='';
1.1075.2.56  raeburn  9186:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9187:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 9188: 	$headerstring.=
1.1075.2.61  raeburn  9189: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9190:         if (!$args->{'frameset'}) {
                   9191:             $headerstring.= ' /';
                   9192:         }
                   9193:         $headerstring .= '>'."\n";
1.340     albertel 9194:     }
                   9195:     return $headerstring;
                   9196: }
                   9197: 
1.341     albertel 9198: =pod
                   9199: 
1.1064    raeburn  9200: =item * &print_suppression()
                   9201: 
                   9202: In course context returns css which causes the body to be blank when media="print",
                   9203: if printout generation is unavailable for the current resource.
                   9204: 
                   9205: This could be because:
                   9206: 
                   9207: (a) printstartdate is in the future
                   9208: 
                   9209: (b) printenddate is in the past
                   9210: 
                   9211: (c) there is an active exam block with "printout"
                   9212: functionality blocked
                   9213: 
                   9214: Users with pav, pfo or evb privileges are exempt.
                   9215: 
                   9216: Inputs: none
                   9217: 
                   9218: =cut
                   9219: 
                   9220: 
                   9221: sub print_suppression {
                   9222:     my $noprint;
                   9223:     if ($env{'request.course.id'}) {
                   9224:         my $scope = $env{'request.course.id'};
                   9225:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9226:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9227:             return;
                   9228:         }
                   9229:         if ($env{'request.course.sec'} ne '') {
                   9230:             $scope .= "/$env{'request.course.sec'}";
                   9231:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9232:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9233:                 return;
1.1064    raeburn  9234:             }
                   9235:         }
                   9236:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9237:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  9238:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9239:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9240:         if ($blocked) {
                   9241:             my $checkrole = "cm./$cdom/$cnum";
                   9242:             if ($env{'request.course.sec'} ne '') {
                   9243:                 $checkrole .= "/$env{'request.course.sec'}";
                   9244:             }
                   9245:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9246:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9247:                 $noprint = 1;
                   9248:             }
                   9249:         }
                   9250:         unless ($noprint) {
                   9251:             my $symb = &Apache::lonnet::symbread();
                   9252:             if ($symb ne '') {
                   9253:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9254:                 if (ref($navmap)) {
                   9255:                     my $res = $navmap->getBySymb($symb);
                   9256:                     if (ref($res)) {
                   9257:                         if (!$res->resprintable()) {
                   9258:                             $noprint = 1;
                   9259:                         }
                   9260:                     }
                   9261:                 }
                   9262:             }
                   9263:         }
                   9264:         if ($noprint) {
                   9265:             return <<"ENDSTYLE";
                   9266: <style type="text/css" media="print">
                   9267:     body { display:none }
                   9268: </style>
                   9269: ENDSTYLE
                   9270:         }
                   9271:     }
                   9272:     return;
                   9273: }
                   9274: 
                   9275: =pod
                   9276: 
1.341     albertel 9277: =item * &xml_begin()
                   9278: 
                   9279: Returns the needed doctype and <html>
                   9280: 
                   9281: Inputs: none
                   9282: 
                   9283: =cut
                   9284: 
                   9285: sub xml_begin {
1.1075.2.61  raeburn  9286:     my ($is_frameset) = @_;
1.341     albertel 9287:     my $output='';
                   9288: 
                   9289:     if ($env{'browser.mathml'}) {
                   9290: 	$output='<?xml version="1.0"?>'
                   9291:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9292: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9293:             
                   9294: #	    .'<!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">] >'
                   9295: 	    .'<!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">'
                   9296:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9297: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  9298:     } elsif ($is_frameset) {
                   9299:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9300:                 '<html>'."\n";
1.341     albertel 9301:     } else {
1.1075.2.61  raeburn  9302: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9303:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9304:     }
                   9305:     return $output;
                   9306: }
1.340     albertel 9307: 
                   9308: =pod
                   9309: 
1.306     albertel 9310: =item * &start_page()
                   9311: 
                   9312: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9313: 
1.648     raeburn  9314: Inputs:
                   9315: 
                   9316: =over 4
                   9317: 
                   9318: $title - optional title for the page
                   9319: 
                   9320: $head_extra - optional extra HTML to incude inside the <head>
                   9321: 
                   9322: $args - additional optional args supported are:
                   9323: 
                   9324: =over 8
                   9325: 
                   9326:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9327:                                     arg on
1.814     bisitz   9328:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9329:              add_entries    -> additional attributes to add to the  <body>
                   9330:              domain         -> force to color decorate a page for a 
1.317     albertel 9331:                                     specific domain
1.648     raeburn  9332:              function       -> force usage of a specific rolish color
1.317     albertel 9333:                                     scheme
1.648     raeburn  9334:              redirect       -> see &headtag()
                   9335:              bgcolor        -> override the default page bg color
                   9336:              js_ready       -> return a string ready for being used in 
1.317     albertel 9337:                                     a javascript writeln
1.648     raeburn  9338:              html_encode    -> return a string ready for being used in 
1.320     albertel 9339:                                     a html attribute
1.648     raeburn  9340:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9341:                                     $forcereg arg
1.648     raeburn  9342:              frameset       -> if true will start with a <frameset>
1.330     albertel 9343:                                     rather than <body>
1.648     raeburn  9344:              skip_phases    -> hash ref of 
1.338     albertel 9345:                                     head -> skip the <html><head> generation
                   9346:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  9347:              no_inline_link -> if true and in remote mode, don't show the
                   9348:                                     'Switch To Inline Menu' link
1.648     raeburn  9349:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9350:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9351:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.161.  .29(raeb 9352:-24):              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9353:-24):                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9354:-24):                                    to override those values, or add to them, specify the value to
                   9355:-24):                                    include in the style attribute to include in the div tag by using
                   9356:-24):                                    bread_crumbs_style (e.g., overflow: visible)
1.1075.2.123  raeburn  9357:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9358:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  9359:              group          -> includes the current group, if page is for a
                   9360:                                specific group
1.1075.2.133  raeburn  9361:              use_absolute   -> for request for external resource or syllabus, this
                   9362:                                will contain https://<hostname> if server uses
                   9363:                                https (as per hosts.tab), but request is for http
                   9364:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  9365:              links_disabled -> Links in primary and secondary menus are disabled
                   9366:                                (Can enable them once page has loaded - see lonroles.pm
                   9367:                                for an example).
1.1075.2.161.  .6(raebu 9368:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9369: 
1.648     raeburn  9370: =back
1.460     albertel 9371: 
1.648     raeburn  9372: =back
1.562     albertel 9373: 
1.306     albertel 9374: =cut
                   9375: 
                   9376: sub start_page {
1.309     albertel 9377:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9378:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9379: 
1.315     albertel 9380:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 9381:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9382: 
1.338     albertel 9383:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  9384:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9385:     }
1.1075.2.161.  .1(raebu 9386:21): 
                   9387:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   9388:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9389:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9390:21):                 $args->{'no_primary_menu'} = 1;
                   9391:21):             }
                   9392:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9393:21):                 $args->{'no_inline_menu'} = 1;
                   9394:21):             }
                   9395:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9396:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9397:21):             }
                   9398:21):         } else {
                   9399:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9400:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9401:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9402:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9403:21):                     $args->{'no_primary_menu'} = 1;
                   9404:21):                 }
                   9405:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9406:21):                     $args->{'no_inline_menu'} = 1;
                   9407:21):                 }
                   9408:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9409:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9410:21):                 }
                   9411:21):             }
                   9412:21):         }
                   9413:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9414:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9415:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   9416:21):     } elsif ($env{'request.course.id'}) {
                   9417:21):         my $expiretime=600;
                   9418:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9419:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9420:21):         }
                   9421:21):         my ($deeplinkmenu,$menuref);
                   9422:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9423:21):         if ($menucoll) {
                   9424:21):             if (ref($menuref) eq 'HASH') {
                   9425:21):                 %menu = %{$menuref};
                   9426:21):             }
                   9427:21):             if ($menu{'top'} eq 'n') {
                   9428:21):                 $args->{'no_primary_menu'} = 1;
                   9429:21):             }
                   9430:21):             if ($menu{'inline'} eq 'n') {
                   9431:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   9432:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9433:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9434:21):                     my $crstype = &course_type();
                   9435:21):                     my $now = time;
                   9436:21):                     my $ccrole;
                   9437:21):                     if ($crstype eq 'Community') {
                   9438:21):                         $ccrole = 'co';
                   9439:21):                     } else {
                   9440:21):                         $ccrole = 'cc';
                   9441:21):                     }
                   9442:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9443:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9444:21):                         if ((($start) && ($start<0)) ||
                   9445:21):                             (($end) && ($end<$now))  ||
                   9446:21):                             (($start) && ($now<$start))) {
                   9447:21):                             $args->{'no_inline_menu'} = 1;
                   9448:21):                         }
                   9449:21):                     } else {
                   9450:21):                         $args->{'no_inline_menu'} = 1;
                   9451:21):                     }
                   9452:21):                 }
                   9453:21):             }
                   9454:21):         }
                   9455:21):     }
          .4(raebu 9456:22): 
          .8(raebu 9457:22):     my $showncrumbs;
1.338     albertel 9458:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9459: 	if ($args->{'frameset'}) {
                   9460: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9461: 						$args->{'add_entries'});
                   9462: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9463:         } else {
                   9464:             $result .=
                   9465:                 &bodytag($title, 
                   9466:                          $args->{'function'},       $args->{'add_entries'},
                   9467:                          $args->{'only_body'},      $args->{'domain'},
                   9468:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  9469:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 9470:21):                          $args,                     \@advtools,
          .8(raebu 9471:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   9472:         }
1.330     albertel 9473:     }
1.338     albertel 9474: 
1.315     albertel 9475:     if ($args->{'js_ready'}) {
1.713     kaisler  9476: 		$result = &js_ready($result);
1.315     albertel 9477:     }
1.320     albertel 9478:     if ($args->{'html_encode'}) {
1.713     kaisler  9479: 		$result = &html_encode($result);
                   9480:     }
                   9481: 
1.813     bisitz   9482:     # Preparation for new and consistent functionlist at top of screen
                   9483:     # if ($args->{'functionlist'}) {
                   9484:     #            $result .= &build_functionlist();
                   9485:     #}
                   9486: 
1.964     droeschl 9487:     # Don't add anything more if only_body wanted or in const space
                   9488:     return $result if    $args->{'only_body'} 
                   9489:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9490: 
                   9491:     #Breadcrumbs
1.758     kaisler  9492:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 9493:22):         unless ($showncrumbs) {
1.758     kaisler  9494: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9495: 		#if any br links exists, add them to the breadcrumbs
                   9496: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9497: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9498: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9499: 			}
                   9500: 		}
1.1075.2.19  raeburn  9501:                 # if @advtools array contains items add then to the breadcrumbs
                   9502:                 if (@advtools > 0) {
                   9503:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9504:                 }
1.1075.2.123  raeburn  9505:                 my $menulink;
                   9506:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 9507:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   9508:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  9509:                     $menulink = 0;
                   9510:                 } else {
                   9511:                     undef($menulink);
                   9512:                 }
1.1075.2.161.  .8(raebu 9513:22):                 my $linkprotout;
                   9514:22):                 if ($env{'request.deeplink.login'}) {
                   9515:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9516:22):                     if ($linkprotout) {
                   9517:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9518:22):                     }
                   9519:22):                 }
1.758     kaisler  9520: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9521: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.161.  .29(raeb 9522:-24): 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   9523:-24):                                                                        '',$menulink,'',
                   9524:-24):                                                                        $args->{'bread_crumbs_style'});
          .1(raebu 9525:21): 		} else {
          .29(raeb 9526:-24): 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   9527:-24):                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  9528: 		}
1.1075.2.161.  .8(raebu 9529:22):         }
1.1075.2.24  raeburn  9530:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9531:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9532:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9533:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9534:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9535:     }
1.315     albertel 9536:     return $result;
1.306     albertel 9537: }
                   9538: 
                   9539: sub end_page {
1.315     albertel 9540:     my ($args) = @_;
                   9541:     $env{'internal.end_page'}++;
1.330     albertel 9542:     my $result;
1.335     albertel 9543:     if ($args->{'discussion'}) {
                   9544: 	my ($target,$parser);
                   9545: 	if (ref($args->{'discussion'})) {
                   9546: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9547: 				$args->{'discussion'}{'parser'});
                   9548: 	}
                   9549: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9550:     }
1.330     albertel 9551:     if ($args->{'frameset'}) {
                   9552: 	$result .= '</frameset>';
                   9553:     } else {
1.635     raeburn  9554: 	$result .= &endbodytag($args);
1.330     albertel 9555:     }
1.1075.2.6  raeburn  9556:     unless ($args->{'notbody'}) {
                   9557:         $result .= "\n</html>";
                   9558:     }
1.330     albertel 9559: 
1.315     albertel 9560:     if ($args->{'js_ready'}) {
1.317     albertel 9561: 	$result = &js_ready($result);
1.315     albertel 9562:     }
1.335     albertel 9563: 
1.320     albertel 9564:     if ($args->{'html_encode'}) {
                   9565: 	$result = &html_encode($result);
                   9566:     }
1.335     albertel 9567: 
1.315     albertel 9568:     return $result;
                   9569: }
                   9570: 
1.1075.2.161.  .1(raebu 9571:21): sub menucoll_in_effect {
                   9572:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9573:21):     if ($env{'request.course.id'}) {
                   9574:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9575:21):         if ($env{'request.deeplink.login'}) {
                   9576:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9577:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9578:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9579:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9580:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9581:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9582:21):                     if (ref($navmap)) {
                   9583:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9584:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9585:21):                                                           '0.deeplink');
                   9586:21):                     } else {
                   9587:21):                         $check_login_symb = 1;
                   9588:21):                     }
                   9589:21):                 } else {
                   9590:21):                     my $symb=&Apache::lonnet::symbread();
                   9591:21):                     if ($symb) {
                   9592:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9593:21):                     } else {
                   9594:21):                         $check_login_symb = 1;
                   9595:21):                     }
                   9596:21):                 }
                   9597:21):             } else {
                   9598:21):                 $check_login_symb = 1;
                   9599:21):             }
                   9600:21):             if ($check_login_symb) {
                   9601:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9602:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9603:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9604:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9605:21):                     if (ref($navmap)) {
                   9606:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9607:21):                     }
                   9608:21):                 } else {
                   9609:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9610:21):                 }
                   9611:21):             }
                   9612:21):             if ($deeplink ne '') {
          .6(raebu 9613:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9614:21):                 if ($display =~ /^\d+$/) {
                   9615:21):                     $deeplinkmenu = 1;
                   9616:21):                     $menucoll = $display;
                   9617:21):                 }
                   9618:21):             }
                   9619:21):         }
                   9620:21):         if ($menucoll) {
                   9621:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9622:21):         }
                   9623:21):     }
                   9624:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9625:21): }
                   9626:21): 
                   9627:21): sub deeplink_login_symb {
                   9628:21):     my ($cnum,$cdom) = @_;
                   9629:21):     my $login_symb;
                   9630:21):     if ($env{'request.deeplink.login'}) {
                   9631:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9632:21):     }
                   9633:21):     return $login_symb;
                   9634:21): }
                   9635:21): 
                   9636:21): sub symb_from_tinyurl {
                   9637:21):     my ($url,$cnum,$cdom) = @_;
                   9638:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9639:21):         my $key = $1;
                   9640:21):         my ($tinyurl,$login);
                   9641:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9642:21):         if (defined($cached)) {
                   9643:21):             $tinyurl = $result;
                   9644:21):         } else {
                   9645:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9646:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9647:21):             if ($currtiny{$key} ne '') {
                   9648:21):                 $tinyurl = $currtiny{$key};
                   9649:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9650:21):             }
                   9651:21):         }
                   9652:21):         if ($tinyurl ne '') {
                   9653:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9654:21):             if (wantarray) {
                   9655:21):                 return ($cnumreq,$symb);
                   9656:21):             } elsif ($cnumreq eq $cnum) {
                   9657:21):                 return $symb;
                   9658:21):             }
                   9659:21):         }
                   9660:21):     }
                   9661:21):     if (wantarray) {
                   9662:21):         return ();
                   9663:21):     } else {
                   9664:21):         return;
                   9665:21):     }
                   9666:21): }
                   9667:21): 
          .17(raeb 9668:-23): sub usable_exttools {
                   9669:-23):     my %tooltypes;
                   9670:-23):     if ($env{'request.course.id'}) {
                   9671:-23):         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9672:-23):            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9673:-23):                %tooltypes = (
                   9674:-23):                              crs => 1,
                   9675:-23):                              dom => 1,
                   9676:-23):                             );
                   9677:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9678:-23):                $tooltypes{'crs'} = 1;
                   9679:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9680:-23):                $tooltypes{'dom'} = 1;
                   9681:-23):            }
                   9682:-23):         } else {
                   9683:-23):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9684:-23):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9685:-23):             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9686:-23):             if ($crstype eq '') {
                   9687:-23):                 $crstype = 'course';
                   9688:-23):             }
                   9689:-23):             if ($crstype eq 'course') {
                   9690:-23):                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9691:-23):                     $crstype = 'official';
                   9692:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9693:-23):                     $crstype = 'textbook';
                   9694:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9695:-23):                     $crstype = 'lti';
                   9696:-23):                 } else {
                   9697:-23):                     $crstype = 'unofficial';
                   9698:-23):                 }
                   9699:-23):             }
                   9700:-23):             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9701:-23):             if ($domdefaults{$crstype.'domexttool'}) {
                   9702:-23):                 $tooltypes{'dom'} = 1;
                   9703:-23):             }
                   9704:-23):             if ($domdefaults{$crstype.'exttool'}) {
                   9705:-23):                 $tooltypes{'crs'} = 1;
                   9706:-23):             }
                   9707:-23):         }
                   9708:-23):     }
                   9709:-23):     return %tooltypes;
                   9710:-23): }
                   9711:-23): 
1.1034    www      9712: sub wishlist_window {
                   9713:     return(<<'ENDWISHLIST');
1.1046    raeburn  9714: <script type="text/javascript">
1.1034    www      9715: // <![CDATA[
                   9716: // <!-- BEGIN LON-CAPA Internal
                   9717: function set_wishlistlink(title, path) {
                   9718:     if (!title) {
                   9719:         title = document.title;
                   9720:         title = title.replace(/^LON-CAPA /,'');
                   9721:     }
1.1075.2.65  raeburn  9722:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9723:     title = title.replace("'","\\\'");
1.1034    www      9724:     if (!path) {
                   9725:         path = location.pathname;
                   9726:     }
1.1075.2.65  raeburn  9727:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9728:     path = path.replace("'","\\\'");
1.1034    www      9729:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9730:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9731: }
                   9732: // END LON-CAPA Internal -->
                   9733: // ]]>
                   9734: </script>
                   9735: ENDWISHLIST
                   9736: }
                   9737: 
1.1030    www      9738: sub modal_window {
                   9739:     return(<<'ENDMODAL');
1.1046    raeburn  9740: <script type="text/javascript">
1.1030    www      9741: // <![CDATA[
                   9742: // <!-- BEGIN LON-CAPA Internal
                   9743: var modalWindow = {
                   9744: 	parent:"body",
                   9745: 	windowId:null,
                   9746: 	content:null,
                   9747: 	width:null,
                   9748: 	height:null,
                   9749: 	close:function()
                   9750: 	{
                   9751: 	        $(".LCmodal-window").remove();
                   9752: 	        $(".LCmodal-overlay").remove();
                   9753: 	},
                   9754: 	open:function()
                   9755: 	{
                   9756: 		var modal = "";
                   9757: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9758: 		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;\">";
                   9759: 		modal += this.content;
                   9760: 		modal += "</div>";	
                   9761: 
                   9762: 		$(this.parent).append(modal);
                   9763: 
                   9764: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9765: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9766: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9767: 	}
                   9768: };
1.1075.2.42  raeburn  9769: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9770: 	{
1.1075.2.119  raeburn  9771:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9772: 		modalWindow.windowId = "myModal";
                   9773: 		modalWindow.width = width;
                   9774: 		modalWindow.height = height;
1.1075.2.80  raeburn  9775: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9776: 		modalWindow.open();
1.1075.2.87  raeburn  9777: 	};
1.1030    www      9778: // END LON-CAPA Internal -->
                   9779: // ]]>
                   9780: </script>
                   9781: ENDMODAL
                   9782: }
                   9783: 
                   9784: sub modal_link {
1.1075.2.42  raeburn  9785:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9786:     unless ($width) { $width=480; }
                   9787:     unless ($height) { $height=400; }
1.1031    www      9788:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9789:     unless ($transparency) { $transparency='true'; }
                   9790: 
1.1074    raeburn  9791:     my $target_attr;
                   9792:     if (defined($target)) {
                   9793:         $target_attr = 'target="'.$target.'"';
                   9794:     }
                   9795:     return <<"ENDLINK";
1.1075.2.143  raeburn  9796: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9797: ENDLINK
1.1030    www      9798: }
                   9799: 
1.1032    www      9800: sub modal_adhoc_script {
1.1075.2.155  raeburn  9801:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9802:     my $mathjax;
                   9803:     if ($possmathjax) {
                   9804:         $mathjax = <<'ENDJAX';
                   9805:                if (typeof MathJax == 'object') {
                   9806:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9807:                }
                   9808: ENDJAX
                   9809:     }
1.1032    www      9810:     return (<<ENDADHOC);
1.1046    raeburn  9811: <script type="text/javascript">
1.1032    www      9812: // <![CDATA[
                   9813:         var $funcname = function()
                   9814:         {
                   9815:                 modalWindow.windowId = "myModal";
                   9816:                 modalWindow.width = $width;
                   9817:                 modalWindow.height = $height;
                   9818:                 modalWindow.content = '$content';
                   9819:                 modalWindow.open();
1.1075.2.155  raeburn  9820:                 $mathjax
1.1032    www      9821:         };  
                   9822: // ]]>
                   9823: </script>
                   9824: ENDADHOC
                   9825: }
                   9826: 
1.1041    www      9827: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9828:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9829:     my $innerwidth=$width-20;
                   9830:     $content=&js_ready(
1.1042    www      9831:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9832:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9833:                  $content.
1.1041    www      9834:                  &end_scrollbox().
1.1075.2.42  raeburn  9835:                  &end_page()
1.1041    www      9836:              );
1.1075.2.155  raeburn  9837:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9838: }
                   9839: 
                   9840: sub modal_adhoc_window {
1.1075.2.155  raeburn  9841:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9842:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9843:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9844: }
                   9845: 
                   9846: sub modal_adhoc_launch {
                   9847:     my ($funcname,$width,$height,$content)=@_;
                   9848:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9849: <script type="text/javascript">
                   9850: // <![CDATA[
                   9851: $funcname();
                   9852: // ]]>
                   9853: </script>
                   9854: ENDLAUNCH
                   9855: }
                   9856: 
                   9857: sub modal_adhoc_close {
                   9858:     return (<<ENDCLOSE);
                   9859: <script type="text/javascript">
                   9860: // <![CDATA[
                   9861: modalWindow.close();
                   9862: // ]]>
                   9863: </script>
                   9864: ENDCLOSE
                   9865: }
                   9866: 
1.1038    www      9867: sub togglebox_script {
                   9868:    return(<<ENDTOGGLE);
                   9869: <script type="text/javascript"> 
                   9870: // <![CDATA[
                   9871: function LCtoggleDisplay(id,hidetext,showtext) {
                   9872:    link = document.getElementById(id + "link").childNodes[0];
                   9873:    with (document.getElementById(id).style) {
                   9874:       if (display == "none" ) {
                   9875:           display = "inline";
                   9876:           link.nodeValue = hidetext;
                   9877:         } else {
                   9878:           display = "none";
                   9879:           link.nodeValue = showtext;
                   9880:        }
                   9881:    }
                   9882: }
                   9883: // ]]>
                   9884: </script>
                   9885: ENDTOGGLE
                   9886: }
                   9887: 
1.1039    www      9888: sub start_togglebox {
                   9889:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9890:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9891:     unless ($showtext) { $showtext=&mt('show'); }
                   9892:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9893:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9894:     return &start_data_table().
                   9895:            &start_data_table_header_row().
                   9896:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9897:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9898:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9899:            &end_data_table_header_row().
                   9900:            '<tr id="'.$id.'" style="display:none""><td>';
                   9901: }
                   9902: 
                   9903: sub end_togglebox {
                   9904:     return '</td></tr>'.&end_data_table();
                   9905: }
                   9906: 
1.1041    www      9907: sub LCprogressbar_script {
1.1075.2.130  raeburn  9908:    my ($id,$number_to_do)=@_;
                   9909:    if ($number_to_do) {
                   9910:        return(<<ENDPROGRESS);
1.1041    www      9911: <script type="text/javascript">
                   9912: // <![CDATA[
1.1045    www      9913: \$('#progressbar$id').progressbar({
1.1041    www      9914:   value: 0,
                   9915:   change: function(event, ui) {
                   9916:     var newVal = \$(this).progressbar('option', 'value');
                   9917:     \$('.pblabel', this).text(LCprogressTxt);
                   9918:   }
                   9919: });
                   9920: // ]]>
                   9921: </script>
                   9922: ENDPROGRESS
1.1075.2.130  raeburn  9923:    } else {
                   9924:        return(<<ENDPROGRESS);
                   9925: <script type="text/javascript">
                   9926: // <![CDATA[
                   9927: \$('#progressbar$id').progressbar({
                   9928:   value: false,
                   9929:   create: function(event, ui) {
                   9930:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9931:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9932:   }
                   9933: });
                   9934: // ]]>
                   9935: </script>
                   9936: ENDPROGRESS
                   9937:    }
1.1041    www      9938: }
                   9939: 
                   9940: sub LCprogressbarUpdate_script {
                   9941:    return(<<ENDPROGRESSUPDATE);
                   9942: <style type="text/css">
                   9943: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9944: .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      9945: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9946: </style>
                   9947: <script type="text/javascript">
                   9948: // <![CDATA[
1.1045    www      9949: var LCprogressTxt='---';
                   9950: 
1.1075.2.130  raeburn  9951: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9952:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9953:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9954:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9955:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9956:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9957:    } else {
                   9958:        \$('#progressbar'+id).progressbar('value',percent);
                   9959:    }
1.1041    www      9960: }
                   9961: // ]]>
                   9962: </script>
                   9963: ENDPROGRESSUPDATE
                   9964: }
                   9965: 
1.1042    www      9966: my $LClastpercent;
1.1045    www      9967: my $LCidcnt;
                   9968: my $LCcurrentid;
1.1042    www      9969: 
1.1041    www      9970: sub LCprogressbar {
1.1075.2.130  raeburn  9971:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9972:     $LClastpercent=0;
1.1045    www      9973:     $LCidcnt++;
                   9974:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9975:     my ($starting,$content);
                   9976:     if ($number_to_do) {
                   9977:         $starting=&mt('Starting');
                   9978:         $content=(<<ENDPROGBAR);
                   9979: $preamble
1.1045    www      9980:   <div id="progressbar$LCcurrentid">
1.1041    www      9981:     <span class="pblabel">$starting</span>
                   9982:   </div>
                   9983: ENDPROGBAR
1.1075.2.130  raeburn  9984:     } else {
                   9985:         $starting=&mt('Loading...');
                   9986:         $LClastpercent='false';
                   9987:         $content=(<<ENDPROGBAR);
                   9988: $preamble
                   9989:   <div id="progressbar$LCcurrentid">
                   9990:       <div class="progress-label">$starting</div>
                   9991:   </div>
                   9992: ENDPROGBAR
                   9993:     }
                   9994:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9995: }
                   9996: 
                   9997: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9998:     my ($r,$val,$text,$number_to_do)=@_;
                   9999:     if ($number_to_do) {
                   10000:         unless ($val) { 
                   10001:             if ($LClastpercent) {
                   10002:                 $val=$LClastpercent;
                   10003:             } else {
                   10004:                 $val=0;
                   10005:             }
                   10006:         }
                   10007:         if ($val<0) { $val=0; }
                   10008:         if ($val>100) { $val=0; }
                   10009:         $LClastpercent=$val;
                   10010:         unless ($text) { $text=$val.'%'; }
                   10011:     } else {
                   10012:         $val = 'false';
1.1042    www      10013:     }
1.1041    www      10014:     $text=&js_ready($text);
1.1044    www      10015:     &r_print($r,<<ENDUPDATE);
1.1041    www      10016: <script type="text/javascript">
                   10017: // <![CDATA[
1.1075.2.130  raeburn  10018: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10019: // ]]>
                   10020: </script>
                   10021: ENDUPDATE
1.1035    www      10022: }
                   10023: 
1.1042    www      10024: sub LCprogressbarClose {
                   10025:     my ($r)=@_;
                   10026:     $LClastpercent=0;
1.1044    www      10027:     &r_print($r,<<ENDCLOSE);
1.1042    www      10028: <script type="text/javascript">
                   10029: // <![CDATA[
1.1045    www      10030: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10031: // ]]>
                   10032: </script>
                   10033: ENDCLOSE
1.1044    www      10034: }
                   10035: 
                   10036: sub r_print {
                   10037:     my ($r,$to_print)=@_;
                   10038:     if ($r) {
                   10039:       $r->print($to_print);
                   10040:       $r->rflush();
                   10041:     } else {
                   10042:       print($to_print);
                   10043:     }
1.1042    www      10044: }
                   10045: 
1.320     albertel 10046: sub html_encode {
                   10047:     my ($result) = @_;
                   10048: 
1.322     albertel 10049:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10050:     
                   10051:     return $result;
                   10052: }
1.1044    www      10053: 
1.317     albertel 10054: sub js_ready {
                   10055:     my ($result) = @_;
                   10056: 
1.323     albertel 10057:     $result =~ s/[\n\r]/ /xmsg;
                   10058:     $result =~ s/\\/\\\\/xmsg;
                   10059:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10060:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10061:     
                   10062:     return $result;
                   10063: }
                   10064: 
1.315     albertel 10065: sub validate_page {
                   10066:     if (  exists($env{'internal.start_page'})
1.316     albertel 10067: 	  &&     $env{'internal.start_page'} > 1) {
                   10068: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10069: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10070: 				 $ENV{'request.filename'});
1.315     albertel 10071:     }
                   10072:     if (  exists($env{'internal.end_page'})
1.316     albertel 10073: 	  &&     $env{'internal.end_page'} > 1) {
                   10074: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10075: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10076: 				 $env{'request.filename'});
1.315     albertel 10077:     }
                   10078:     if (     exists($env{'internal.start_page'})
                   10079: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10080: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10081: 				 $env{'request.filename'});
1.315     albertel 10082:     }
                   10083:     if (   ! exists($env{'internal.start_page'})
                   10084: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10085: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10086: 				 $env{'request.filename'});
1.315     albertel 10087:     }
1.306     albertel 10088: }
1.315     albertel 10089: 
1.996     www      10090: 
                   10091: sub start_scrollbox {
1.1075.2.56  raeburn  10092:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10093:     unless ($outerwidth) { $outerwidth='520px'; }
                   10094:     unless ($width) { $width='500px'; }
                   10095:     unless ($height) { $height='200px'; }
1.1075    raeburn  10096:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10097:     if ($id ne '') {
1.1075.2.42  raeburn  10098:         $table_id = ' id="table_'.$id.'"';
                   10099:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10100:     }
1.1075    raeburn  10101:     if ($bgcolor ne '') {
                   10102:         $tdcol = "background-color: $bgcolor;";
                   10103:     }
1.1075.2.42  raeburn  10104:     my $nicescroll_js;
                   10105:     if ($env{'browser.mobile'}) {
                   10106:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10107:     }
1.1075    raeburn  10108:     return <<"END";
1.1075.2.42  raeburn  10109: $nicescroll_js
                   10110: 
                   10111: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  10112: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  10113: END
1.996     www      10114: }
                   10115: 
                   10116: sub end_scrollbox {
1.1036    www      10117:     return '</div></td></tr></table>';
1.996     www      10118: }
                   10119: 
1.1075.2.42  raeburn  10120: sub nicescroll_javascript {
                   10121:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10122:     my %options;
                   10123:     if (ref($cursor) eq 'HASH') {
                   10124:         %options = %{$cursor};
                   10125:     }
                   10126:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10127:         $options{'railalign'} = 'left';
                   10128:     }
                   10129:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10130:         my $function  = &get_users_function();
                   10131:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   10132:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10133:             $options{'cursorcolor'} = '#00F';
                   10134:         }
                   10135:     }
                   10136:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10137:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   10138:             $options{'cursoropacity'}='1.0';
                   10139:         }
                   10140:     } else {
                   10141:         $options{'cursoropacity'}='1.0';
                   10142:     }
                   10143:     if ($options{'cursorfixedheight'} eq 'none') {
                   10144:         delete($options{'cursorfixedheight'});
                   10145:     } else {
                   10146:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10147:     }
                   10148:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10149:         delete($options{'railoffset'});
                   10150:     }
                   10151:     my @niceoptions;
                   10152:     while (my($key,$value) = each(%options)) {
                   10153:         if ($value =~ /^\{.+\}$/) {
                   10154:             push(@niceoptions,$key.':'.$value);
                   10155:         } else {
                   10156:             push(@niceoptions,$key.':"'.$value.'"');
                   10157:         }
                   10158:     }
                   10159:     my $nicescroll_js = '
                   10160: $(document).ready(
                   10161:       function() {
                   10162:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10163:       }
                   10164: );
                   10165: ';
                   10166:     if ($framecheck) {
                   10167:         $nicescroll_js .= '
                   10168: function expand_div(caller) {
                   10169:     if (top === self) {
                   10170:         document.getElementById("'.$id.'").style.width = "auto";
                   10171:         document.getElementById("'.$id.'").style.height = "auto";
                   10172:     } else {
                   10173:         try {
                   10174:             if (parent.frames) {
                   10175:                 if (parent.frames.length > 1) {
                   10176:                     var framesrc = parent.frames[1].location.href;
                   10177:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10178:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10179:                         document.getElementById("'.$id.'").style.width = "auto";
                   10180:                         document.getElementById("'.$id.'").style.height = "auto";
                   10181:                     }
                   10182:                 }
                   10183:             }
                   10184:         } catch (e) {
                   10185:             return;
                   10186:         }
                   10187:     }
                   10188:     return;
                   10189: }
                   10190: ';
                   10191:     }
                   10192:     if ($needjsready) {
                   10193:         $nicescroll_js = '
                   10194: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10195:     } else {
                   10196:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10197:     }
                   10198:     return $nicescroll_js;
                   10199: }
                   10200: 
1.318     albertel 10201: sub simple_error_page {
1.1075.2.49  raeburn  10202:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 10203:22):     my %displayargs;
1.1075.2.49  raeburn  10204:     if (ref($args) eq 'HASH') {
                   10205:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 10206:22):         if ($args->{'only_body'}) {
                   10207:22):             $displayargs{'only_body'} = 1;
                   10208:22):         }
                   10209:22):         if ($args->{'no_nav_bar'}) {
                   10210:22):             $displayargs{'no_nav_bar'} = 1;
                   10211:22):         }
1.1075.2.49  raeburn  10212:     } else {
                   10213:         $msg = &mt($msg);
                   10214:     }
                   10215: 
1.318     albertel 10216:     my $page =
1.1075.2.161.  .4(raebu 10217:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  10218: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10219: 	&Apache::loncommon::end_page();
                   10220:     if (ref($r)) {
                   10221: 	$r->print($page);
1.327     albertel 10222: 	return;
1.318     albertel 10223:     }
                   10224:     return $page;
                   10225: }
1.347     albertel 10226: 
                   10227: {
1.610     albertel 10228:     my @row_count;
1.961     onken    10229: 
                   10230:     sub start_data_table_count {
                   10231:         unshift(@row_count, 0);
                   10232:         return;
                   10233:     }
                   10234: 
                   10235:     sub end_data_table_count {
                   10236:         shift(@row_count);
                   10237:         return;
                   10238:     }
                   10239: 
1.347     albertel 10240:     sub start_data_table {
1.1018    raeburn  10241: 	my ($add_class,$id) = @_;
1.422     albertel 10242: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10243:         my $table_id;
                   10244:         if (defined($id)) {
                   10245:             $table_id = ' id="'.$id.'"';
                   10246:         }
1.961     onken    10247: 	&start_data_table_count();
1.1018    raeburn  10248: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10249:     }
                   10250: 
                   10251:     sub end_data_table {
1.961     onken    10252: 	&end_data_table_count();
1.389     albertel 10253: 	return '</table>'."\n";;
1.347     albertel 10254:     }
                   10255: 
                   10256:     sub start_data_table_row {
1.974     wenzelju 10257: 	my ($add_class, $id) = @_;
1.610     albertel 10258: 	$row_count[0]++;
                   10259: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10260: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10261:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10262:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10263:     }
1.471     banghart 10264:     
                   10265:     sub continue_data_table_row {
1.974     wenzelju 10266: 	my ($add_class, $id) = @_;
1.610     albertel 10267: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10268: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10269:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10270:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10271:     }
1.347     albertel 10272: 
                   10273:     sub end_data_table_row {
1.389     albertel 10274: 	return '</tr>'."\n";;
1.347     albertel 10275:     }
1.367     www      10276: 
1.421     albertel 10277:     sub start_data_table_empty_row {
1.707     bisitz   10278: #	$row_count[0]++;
1.421     albertel 10279: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10280:     }
                   10281: 
                   10282:     sub end_data_table_empty_row {
                   10283: 	return '</tr>'."\n";;
                   10284:     }
                   10285: 
1.367     www      10286:     sub start_data_table_header_row {
1.389     albertel 10287: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10288:     }
                   10289: 
                   10290:     sub end_data_table_header_row {
1.389     albertel 10291: 	return '</tr>'."\n";;
1.367     www      10292:     }
1.890     droeschl 10293: 
                   10294:     sub data_table_caption {
                   10295:         my $caption = shift;
                   10296:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10297:     }
1.347     albertel 10298: }
                   10299: 
1.548     albertel 10300: =pod
                   10301: 
                   10302: =item * &inhibit_menu_check($arg)
                   10303: 
                   10304: Checks for a inhibitmenu state and generates output to preserve it
                   10305: 
                   10306: Inputs:         $arg - can be any of
                   10307:                      - undef - in which case the return value is a string 
                   10308:                                to add  into arguments list of a uri
                   10309:                      - 'input' - in which case the return value is a HTML
                   10310:                                  <form> <input> field of type hidden to
                   10311:                                  preserve the value
                   10312:                      - a url - in which case the return value is the url with
                   10313:                                the neccesary cgi args added to preserve the
                   10314:                                inhibitmenu state
                   10315:                      - a ref to a url - no return value, but the string is
                   10316:                                         updated to include the neccessary cgi
                   10317:                                         args to preserve the inhibitmenu state
                   10318: 
                   10319: =cut
                   10320: 
                   10321: sub inhibit_menu_check {
                   10322:     my ($arg) = @_;
                   10323:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10324:     if ($arg eq 'input') {
                   10325: 	if ($env{'form.inhibitmenu'}) {
                   10326: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10327: 	} else {
                   10328: 	    return
                   10329: 	}
                   10330:     }
                   10331:     if ($env{'form.inhibitmenu'}) {
                   10332: 	if (ref($arg)) {
                   10333: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10334: 	} elsif ($arg eq '') {
                   10335: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10336: 	} else {
                   10337: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10338: 	}
                   10339:     }
                   10340:     if (!ref($arg)) {
                   10341: 	return $arg;
                   10342:     }
                   10343: }
                   10344: 
1.251     albertel 10345: ###############################################
1.182     matthew  10346: 
                   10347: =pod
                   10348: 
1.549     albertel 10349: =back
                   10350: 
                   10351: =head1 User Information Routines
                   10352: 
                   10353: =over 4
                   10354: 
1.405     albertel 10355: =item * &get_users_function()
1.182     matthew  10356: 
                   10357: Used by &bodytag to determine the current users primary role.
                   10358: Returns either 'student','coordinator','admin', or 'author'.
                   10359: 
                   10360: =cut
                   10361: 
                   10362: ###############################################
                   10363: sub get_users_function {
1.815     tempelho 10364:     my $function = 'norole';
1.818     tempelho 10365:     if ($env{'request.role'}=~/^(st)/) {
                   10366:         $function='student';
                   10367:     }
1.907     raeburn  10368:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10369:         $function='coordinator';
                   10370:     }
1.258     albertel 10371:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10372:         $function='admin';
                   10373:     }
1.826     bisitz   10374:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10375:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10376:         $function='author';
                   10377:     }
                   10378:     return $function;
1.54      www      10379: }
1.99      www      10380: 
                   10381: ###############################################
                   10382: 
1.233     raeburn  10383: =pod
                   10384: 
1.821     raeburn  10385: =item * &show_course()
                   10386: 
                   10387: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10388: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10389: 
                   10390: Inputs:
                   10391: None
                   10392: 
                   10393: Outputs:
                   10394: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10395: 
                   10396: =cut
                   10397: 
                   10398: ###############################################
                   10399: sub show_course {
                   10400:     my $course = !$env{'user.adv'};
                   10401:     if (!$env{'user.adv'}) {
                   10402:         foreach my $env (keys(%env)) {
                   10403:             next if ($env !~ m/^user\.priv\./);
                   10404:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10405:                 $course = 0;
                   10406:                 last;
                   10407:             }
                   10408:         }
                   10409:     }
                   10410:     return $course;
                   10411: }
                   10412: 
                   10413: ###############################################
                   10414: 
                   10415: =pod
                   10416: 
1.542     raeburn  10417: =item * &check_user_status()
1.274     raeburn  10418: 
                   10419: Determines current status of supplied role for a
                   10420: specific user. Roles can be active, previous or future.
                   10421: 
                   10422: Inputs: 
                   10423: user's domain, user's username, course's domain,
1.375     raeburn  10424: course's number, optional section ID.
1.274     raeburn  10425: 
                   10426: Outputs:
                   10427: role status: active, previous or future. 
                   10428: 
                   10429: =cut
                   10430: 
                   10431: sub check_user_status {
1.412     raeburn  10432:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10433:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  10434:     my @uroles = keys(%userinfo);
1.274     raeburn  10435:     my $srchstr;
                   10436:     my $active_chk = 'none';
1.412     raeburn  10437:     my $now = time;
1.274     raeburn  10438:     if (@uroles > 0) {
1.908     raeburn  10439:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10440:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10441:         } else {
1.412     raeburn  10442:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10443:         }
                   10444:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10445:             my $role_end = 0;
                   10446:             my $role_start = 0;
                   10447:             $active_chk = 'active';
1.412     raeburn  10448:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10449:                 $role_end = $1;
                   10450:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10451:                     $role_start = $1;
1.274     raeburn  10452:                 }
                   10453:             }
                   10454:             if ($role_start > 0) {
1.412     raeburn  10455:                 if ($now < $role_start) {
1.274     raeburn  10456:                     $active_chk = 'future';
                   10457:                 }
                   10458:             }
                   10459:             if ($role_end > 0) {
1.412     raeburn  10460:                 if ($now > $role_end) {
1.274     raeburn  10461:                     $active_chk = 'previous';
                   10462:                 }
                   10463:             }
                   10464:         }
                   10465:     }
                   10466:     return $active_chk;
                   10467: }
                   10468: 
                   10469: ###############################################
                   10470: 
                   10471: =pod
                   10472: 
1.405     albertel 10473: =item * &get_sections()
1.233     raeburn  10474: 
                   10475: Determines all the sections for a course including
                   10476: sections with students and sections containing other roles.
1.419     raeburn  10477: Incoming parameters: 
                   10478: 
                   10479: 1. domain
                   10480: 2. course number 
                   10481: 3. reference to array containing roles for which sections should 
                   10482: be gathered (optional).
                   10483: 4. reference to array containing status types for which sections 
                   10484: should be gathered (optional).
                   10485: 
                   10486: If the third argument is undefined, sections are gathered for any role. 
                   10487: If the fourth argument is undefined, sections are gathered for any status.
                   10488: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10489:  
1.374     raeburn  10490: Returns section hash (keys are section IDs, values are
                   10491: number of users in each section), subject to the
1.419     raeburn  10492: optional roles filter, optional status filter 
1.233     raeburn  10493: 
                   10494: =cut
                   10495: 
                   10496: ###############################################
                   10497: sub get_sections {
1.419     raeburn  10498:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10499:     if (!defined($cdom) || !defined($cnum)) {
                   10500:         my $cid =  $env{'request.course.id'};
                   10501: 
                   10502: 	return if (!defined($cid));
                   10503: 
                   10504:         $cdom = $env{'course.'.$cid.'.domain'};
                   10505:         $cnum = $env{'course.'.$cid.'.num'};
                   10506:     }
                   10507: 
                   10508:     my %sectioncount;
1.419     raeburn  10509:     my $now = time;
1.240     albertel 10510: 
1.1075.2.33  raeburn  10511:     my $check_students = 1;
                   10512:     my $only_students = 0;
                   10513:     if (ref($possible_roles) eq 'ARRAY') {
                   10514:         if (grep(/^st$/,@{$possible_roles})) {
                   10515:             if (@{$possible_roles} == 1) {
                   10516:                 $only_students = 1;
                   10517:             }
                   10518:         } else {
                   10519:             $check_students = 0;
                   10520:         }
                   10521:     }
                   10522: 
                   10523:     if ($check_students) {
1.276     albertel 10524: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10525: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10526: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10527:         my $start_index = &Apache::loncoursedata::CL_START();
                   10528:         my $end_index = &Apache::loncoursedata::CL_END();
                   10529:         my $status;
1.366     albertel 10530: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10531: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10532: 				                     $data->[$status_index],
                   10533:                                                      $data->[$start_index],
                   10534:                                                      $data->[$end_index]);
                   10535:             if ($stu_status eq 'Active') {
                   10536:                 $status = 'active';
                   10537:             } elsif ($end < $now) {
                   10538:                 $status = 'previous';
                   10539:             } elsif ($start > $now) {
                   10540:                 $status = 'future';
                   10541:             } 
                   10542: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10543:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10544:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10545: 		    $sectioncount{$section}++;
                   10546:                 }
1.240     albertel 10547: 	    }
                   10548: 	}
                   10549:     }
1.1075.2.33  raeburn  10550:     if ($only_students) {
                   10551:         return %sectioncount;
                   10552:     }
1.240     albertel 10553:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10554:     foreach my $user (sort(keys(%courseroles))) {
                   10555: 	if ($user !~ /^(\w{2})/) { next; }
                   10556: 	my ($role) = ($user =~ /^(\w{2})/);
                   10557: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10558: 	my ($section,$status);
1.240     albertel 10559: 	if ($role eq 'cr' &&
                   10560: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10561: 	    $section=$1;
                   10562: 	}
                   10563: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10564: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10565:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10566:         if ($end == -1 && $start == -1) {
                   10567:             next; #deleted role
                   10568:         }
                   10569:         if (!defined($possible_status)) { 
                   10570:             $sectioncount{$section}++;
                   10571:         } else {
                   10572:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10573:                 $status = 'active';
                   10574:             } elsif ($end < $now) {
                   10575:                 $status = 'future';
                   10576:             } elsif ($start > $now) {
                   10577:                 $status = 'previous';
                   10578:             }
                   10579:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10580:                 $sectioncount{$section}++;
                   10581:             }
                   10582:         }
1.233     raeburn  10583:     }
1.366     albertel 10584:     return %sectioncount;
1.233     raeburn  10585: }
                   10586: 
1.274     raeburn  10587: ###############################################
1.294     raeburn  10588: 
                   10589: =pod
1.405     albertel 10590: 
                   10591: =item * &get_course_users()
                   10592: 
1.275     raeburn  10593: Retrieves usernames:domains for users in the specified course
                   10594: with specific role(s), and access status. 
                   10595: 
                   10596: Incoming parameters:
1.277     albertel 10597: 1. course domain
                   10598: 2. course number
                   10599: 3. access status: users must have - either active, 
1.275     raeburn  10600: previous, future, or all.
1.277     albertel 10601: 4. reference to array of permissible roles
1.288     raeburn  10602: 5. reference to array of section restrictions (optional)
                   10603: 6. reference to results object (hash of hashes).
                   10604: 7. reference to optional userdata hash
1.609     raeburn  10605: 8. reference to optional statushash
1.630     raeburn  10606: 9. flag if privileged users (except those set to unhide in
                   10607:    course settings) should be excluded    
1.609     raeburn  10608: Keys of top level results hash are roles.
1.275     raeburn  10609: Keys of inner hashes are username:domain, with 
                   10610: values set to access type.
1.288     raeburn  10611: Optional userdata hash returns an array with arguments in the 
                   10612: same order as loncoursedata::get_classlist() for student data.
                   10613: 
1.609     raeburn  10614: Optional statushash returns
                   10615: 
1.288     raeburn  10616: Entries for end, start, section and status are blank because
                   10617: of the possibility of multiple values for non-student roles.
                   10618: 
1.275     raeburn  10619: =cut
1.405     albertel 10620: 
1.275     raeburn  10621: ###############################################
1.405     albertel 10622: 
1.275     raeburn  10623: sub get_course_users {
1.630     raeburn  10624:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10625:     my %idx = ();
1.419     raeburn  10626:     my %seclists;
1.288     raeburn  10627: 
                   10628:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10629:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10630:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10631:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10632:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10633:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10634:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10635:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10636: 
1.290     albertel 10637:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10638:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10639:         my $now = time;
1.277     albertel 10640:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10641:             my $match = 0;
1.412     raeburn  10642:             my $secmatch = 0;
1.419     raeburn  10643:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10644:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10645:             if ($section eq '') {
                   10646:                 $section = 'none';
                   10647:             }
1.291     albertel 10648:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10649:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10650:                     $secmatch = 1;
                   10651:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10652:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10653:                         $secmatch = 1;
                   10654:                     }
                   10655:                 } else {  
1.419     raeburn  10656: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10657: 		        $secmatch = 1;
                   10658:                     }
1.290     albertel 10659: 		}
1.412     raeburn  10660:                 if (!$secmatch) {
                   10661:                     next;
                   10662:                 }
1.419     raeburn  10663:             }
1.275     raeburn  10664:             if (defined($$types{'active'})) {
1.288     raeburn  10665:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10666:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10667:                     $match = 1;
1.275     raeburn  10668:                 }
                   10669:             }
                   10670:             if (defined($$types{'previous'})) {
1.609     raeburn  10671:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10672:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10673:                     $match = 1;
1.275     raeburn  10674:                 }
                   10675:             }
                   10676:             if (defined($$types{'future'})) {
1.609     raeburn  10677:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10678:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10679:                     $match = 1;
1.275     raeburn  10680:                 }
                   10681:             }
1.609     raeburn  10682:             if ($match) {
                   10683:                 push(@{$seclists{$student}},$section);
                   10684:                 if (ref($userdata) eq 'HASH') {
                   10685:                     $$userdata{$student} = $$classlist{$student};
                   10686:                 }
                   10687:                 if (ref($statushash) eq 'HASH') {
                   10688:                     $statushash->{$student}{'st'}{$section} = $status;
                   10689:                 }
1.288     raeburn  10690:             }
1.275     raeburn  10691:         }
                   10692:     }
1.412     raeburn  10693:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10694:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10695:         my $now = time;
1.609     raeburn  10696:         my %displaystatus = ( previous => 'Expired',
                   10697:                               active   => 'Active',
                   10698:                               future   => 'Future',
                   10699:                             );
1.1075.2.36  raeburn  10700:         my (%nothide,@possdoms);
1.630     raeburn  10701:         if ($hidepriv) {
                   10702:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10703:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10704:                 if ($user !~ /:/) {
                   10705:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10706:                 } else {
                   10707:                     $nothide{$user} = 1;
                   10708:                 }
                   10709:             }
1.1075.2.36  raeburn  10710:             my @possdoms = ($cdom);
                   10711:             if ($coursehash{'checkforpriv'}) {
                   10712:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10713:             }
1.630     raeburn  10714:         }
1.439     raeburn  10715:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10716:             my $match = 0;
1.412     raeburn  10717:             my $secmatch = 0;
1.439     raeburn  10718:             my $status;
1.412     raeburn  10719:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10720:             $user =~ s/:$//;
1.439     raeburn  10721:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10722:             if ($end == -1 || $start == -1) {
                   10723:                 next;
                   10724:             }
                   10725:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10726:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10727:                 my ($uname,$udom) = split(/:/,$user);
                   10728:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10729:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10730:                         $secmatch = 1;
                   10731:                     } elsif ($usec eq '') {
1.420     albertel 10732:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10733:                             $secmatch = 1;
                   10734:                         }
                   10735:                     } else {
                   10736:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10737:                             $secmatch = 1;
                   10738:                         }
                   10739:                     }
                   10740:                     if (!$secmatch) {
                   10741:                         next;
                   10742:                     }
1.288     raeburn  10743:                 }
1.419     raeburn  10744:                 if ($usec eq '') {
                   10745:                     $usec = 'none';
                   10746:                 }
1.275     raeburn  10747:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10748:                     if ($hidepriv) {
1.1075.2.36  raeburn  10749:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10750:                             (!$nothide{$uname.':'.$udom})) {
                   10751:                             next;
                   10752:                         }
                   10753:                     }
1.503     raeburn  10754:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10755:                         $status = 'previous';
                   10756:                     } elsif ($start > $now) {
                   10757:                         $status = 'future';
                   10758:                     } else {
                   10759:                         $status = 'active';
                   10760:                     }
1.277     albertel 10761:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10762:                         if ($status eq $type) {
1.420     albertel 10763:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10764:                                 push(@{$$users{$role}{$user}},$type);
                   10765:                             }
1.288     raeburn  10766:                             $match = 1;
                   10767:                         }
                   10768:                     }
1.419     raeburn  10769:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10770:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10771: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10772:                         }
1.420     albertel 10773:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10774:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10775:                         }
1.609     raeburn  10776:                         if (ref($statushash) eq 'HASH') {
                   10777:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10778:                         }
1.275     raeburn  10779:                     }
                   10780:                 }
                   10781:             }
                   10782:         }
1.290     albertel 10783:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10784:             if ((defined($cdom)) && (defined($cnum))) {
                   10785:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10786:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10787:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10788:                     next if ($owner eq '');
                   10789:                     my ($ownername,$ownerdom);
                   10790:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10791:                         $ownername = $1;
                   10792:                         $ownerdom = $2;
                   10793:                     } else {
                   10794:                         $ownername = $owner;
                   10795:                         $ownerdom = $cdom;
                   10796:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10797:                     }
                   10798:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10799:                     if (defined($userdata) && 
1.609     raeburn  10800: 			!exists($$userdata{$owner})) {
                   10801: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10802:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10803:                             push(@{$seclists{$owner}},'none');
                   10804:                         }
                   10805:                         if (ref($statushash) eq 'HASH') {
                   10806:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10807:                         }
1.290     albertel 10808: 		    }
1.279     raeburn  10809:                 }
                   10810:             }
                   10811:         }
1.419     raeburn  10812:         foreach my $user (keys(%seclists)) {
                   10813:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10814:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10815:         }
1.275     raeburn  10816:     }
                   10817:     return;
                   10818: }
                   10819: 
1.288     raeburn  10820: sub get_user_info {
                   10821:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10822:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10823: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10824:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10825:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10826:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10827:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10828:     return;
                   10829: }
1.275     raeburn  10830: 
1.472     raeburn  10831: ###############################################
                   10832: 
                   10833: =pod
                   10834: 
                   10835: =item * &get_user_quota()
                   10836: 
1.1075.2.41  raeburn  10837: Retrieves quota assigned for storage of user files.
                   10838: Default is to report quota for portfolio files.
1.472     raeburn  10839: 
                   10840: Incoming parameters:
                   10841: 1. user's username
                   10842: 2. user's domain
1.1075.2.41  raeburn  10843: 3. quota name - portfolio, author, or course
                   10844:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10845: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10846:    course
1.472     raeburn  10847: 
                   10848: Returns:
1.1075.2.58  raeburn  10849: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10850: 2. (Optional) Type of setting: custom or default
                   10851:    (individually assigned or default for user's 
                   10852:    institutional status).
                   10853: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10854:    or student - types as defined in localenroll::inst_usertypes 
                   10855:    for user's domain, which determines default quota for user.
                   10856: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10857: 
                   10858: If a value has been stored in the user's environment, 
1.536     raeburn  10859: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10860: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10861: 
                   10862: =cut
                   10863: 
                   10864: ###############################################
                   10865: 
                   10866: 
                   10867: sub get_user_quota {
1.1075.2.42  raeburn  10868:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10869:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10870:     if (!defined($udom)) {
                   10871:         $udom = $env{'user.domain'};
                   10872:     }
                   10873:     if (!defined($uname)) {
                   10874:         $uname = $env{'user.name'};
                   10875:     }
                   10876:     if (($udom eq '' || $uname eq '') ||
                   10877:         ($udom eq 'public') && ($uname eq 'public')) {
                   10878:         $quota = 0;
1.536     raeburn  10879:         $quotatype = 'default';
                   10880:         $defquota = 0; 
1.472     raeburn  10881:     } else {
1.536     raeburn  10882:         my $inststatus;
1.1075.2.41  raeburn  10883:         if ($quotaname eq 'course') {
                   10884:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10885:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10886:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10887:             } else {
                   10888:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10889:                 $quota = $cenv{'internal.uploadquota'};
                   10890:             }
1.536     raeburn  10891:         } else {
1.1075.2.41  raeburn  10892:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10893:                 if ($quotaname eq 'author') {
                   10894:                     $quota = $env{'environment.authorquota'};
                   10895:                 } else {
                   10896:                     $quota = $env{'environment.portfolioquota'};
                   10897:                 }
                   10898:                 $inststatus = $env{'environment.inststatus'};
                   10899:             } else {
                   10900:                 my %userenv = 
                   10901:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10902:                                          'authorquota','inststatus'],$udom,$uname);
                   10903:                 my ($tmp) = keys(%userenv);
                   10904:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10905:                     if ($quotaname eq 'author') {
                   10906:                         $quota = $userenv{'authorquota'};
                   10907:                     } else {
                   10908:                         $quota = $userenv{'portfolioquota'};
                   10909:                     }
                   10910:                     $inststatus = $userenv{'inststatus'};
                   10911:                 } else {
                   10912:                     undef(%userenv);
                   10913:                 }
                   10914:             }
                   10915:         }
                   10916:         if ($quota eq '' || wantarray) {
                   10917:             if ($quotaname eq 'course') {
                   10918:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10919:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10920:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10921:                     $defquota = $domdefs{$crstype.'quota'};
                   10922:                 }
                   10923:                 if ($defquota eq '') {
                   10924:                     $defquota = 500;
                   10925:                 }
1.1075.2.41  raeburn  10926:             } else {
                   10927:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10928:             }
                   10929:             if ($quota eq '') {
                   10930:                 $quota = $defquota;
                   10931:                 $quotatype = 'default';
                   10932:             } else {
                   10933:                 $quotatype = 'custom';
                   10934:             }
1.472     raeburn  10935:         }
                   10936:     }
1.536     raeburn  10937:     if (wantarray) {
                   10938:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10939:     } else {
                   10940:         return $quota;
                   10941:     }
1.472     raeburn  10942: }
                   10943: 
                   10944: ###############################################
                   10945: 
                   10946: =pod
                   10947: 
                   10948: =item * &default_quota()
                   10949: 
1.536     raeburn  10950: Retrieves default quota assigned for storage of user portfolio files,
                   10951: given an (optional) user's institutional status.
1.472     raeburn  10952: 
                   10953: Incoming parameters:
1.1075.2.42  raeburn  10954: 
1.472     raeburn  10955: 1. domain
1.536     raeburn  10956: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10957:    status types (e.g., faculty, staff, student etc.)
                   10958:    which apply to the user for whom the default is being retrieved.
                   10959:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10960:    default quota will be returned.
                   10961: 3.  quota name - portfolio, author, or course
                   10962:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10963: 
                   10964: Returns:
1.1075.2.42  raeburn  10965: 
1.1075.2.58  raeburn  10966: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10967: 2. (Optional) institutional type which determined the value of the
                   10968:    default quota.
1.472     raeburn  10969: 
                   10970: If a value has been stored in the domain's configuration db,
                   10971: it will return that, otherwise it returns 20 (for backwards 
                   10972: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10973: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10974: 
1.536     raeburn  10975: If the user's status includes multiple types (e.g., staff and student),
                   10976: the largest default quota which applies to the user determines the
                   10977: default quota returned.
                   10978: 
1.472     raeburn  10979: =cut
                   10980: 
                   10981: ###############################################
                   10982: 
                   10983: 
                   10984: sub default_quota {
1.1075.2.41  raeburn  10985:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10986:     my ($defquota,$settingstatus);
                   10987:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10988:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10989:     my $key = 'defaultquota';
                   10990:     if ($quotaname eq 'author') {
                   10991:         $key = 'authorquota';
                   10992:     }
1.622     raeburn  10993:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10994:         if ($inststatus ne '') {
1.765     raeburn  10995:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10996:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10997:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10998:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10999:                         if ($defquota eq '') {
1.1075.2.41  raeburn  11000:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11001:                             $settingstatus = $item;
1.1075.2.41  raeburn  11002:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11003:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11004:                             $settingstatus = $item;
                   11005:                         }
                   11006:                     }
1.1075.2.41  raeburn  11007:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11008:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11009:                         if ($defquota eq '') {
                   11010:                             $defquota = $quotahash{'quotas'}{$item};
                   11011:                             $settingstatus = $item;
                   11012:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11013:                             $defquota = $quotahash{'quotas'}{$item};
                   11014:                             $settingstatus = $item;
                   11015:                         }
1.536     raeburn  11016:                     }
                   11017:                 }
                   11018:             }
                   11019:         }
                   11020:         if ($defquota eq '') {
1.1075.2.41  raeburn  11021:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11022:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11023:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11024:                 $defquota = $quotahash{'quotas'}{'default'};
                   11025:             }
1.536     raeburn  11026:             $settingstatus = 'default';
1.1075.2.42  raeburn  11027:             if ($defquota eq '') {
                   11028:                 if ($quotaname eq 'author') {
                   11029:                     $defquota = 500;
                   11030:                 }
                   11031:             }
1.536     raeburn  11032:         }
                   11033:     } else {
                   11034:         $settingstatus = 'default';
1.1075.2.41  raeburn  11035:         if ($quotaname eq 'author') {
                   11036:             $defquota = 500;
                   11037:         } else {
                   11038:             $defquota = 20;
                   11039:         }
1.536     raeburn  11040:     }
                   11041:     if (wantarray) {
                   11042:         return ($defquota,$settingstatus);
1.472     raeburn  11043:     } else {
1.536     raeburn  11044:         return $defquota;
1.472     raeburn  11045:     }
                   11046: }
                   11047: 
1.1075.2.41  raeburn  11048: ###############################################
                   11049: 
                   11050: =pod
                   11051: 
1.1075.2.42  raeburn  11052: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  11053: 
                   11054: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  11055: of existing file within authoring space will cause quota for the authoring
                   11056: space to be exceeded.
                   11057: 
                   11058: Same, if upload of a file directly to a course/community via Course Editor
                   11059: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  11060: 
1.1075.2.61  raeburn  11061: Inputs: 7 
1.1075.2.42  raeburn  11062: 1. username or coursenum
1.1075.2.41  raeburn  11063: 2. domain
1.1075.2.42  raeburn  11064: 3. context ('author' or 'course')
1.1075.2.41  raeburn  11065: 4. filename of file for which action is being requested
                   11066: 5. filesize (kB) of file
                   11067: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  11068: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  11069: 
                   11070: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   11071:          otherwise return null.
                   11072: 
1.1075.2.42  raeburn  11073: =back
                   11074: 
1.1075.2.41  raeburn  11075: =cut
                   11076: 
1.1075.2.42  raeburn  11077: sub excess_filesize_warning {
1.1075.2.59  raeburn  11078:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  11079:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  11080:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  11081:     if ($context eq 'author') {
                   11082:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11083:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11084:     } else {
                   11085:         foreach my $subdir ('docs','supplemental') {
                   11086:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11087:         }
                   11088:     }
1.1075.2.41  raeburn  11089:     $disk_quota = int($disk_quota * 1000);
                   11090:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  11091:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  11092:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  11093:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11094:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  11095:                             $disk_quota,$current_disk_usage).
                   11096:                '</p>';
                   11097:     }
                   11098:     return;
                   11099: }
                   11100: 
                   11101: ###############################################
                   11102: 
                   11103: 
1.384     raeburn  11104: sub get_secgrprole_info {
                   11105:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11106:     my %sections_count = &get_sections($cdom,$cnum);
                   11107:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11108:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11109:     my @groups = sort(keys(%curr_groups));
                   11110:     my $allroles = [];
                   11111:     my $rolehash;
                   11112:     my $accesshash = {
                   11113:                      active => 'Currently has access',
                   11114:                      future => 'Will have future access',
                   11115:                      previous => 'Previously had access',
                   11116:                   };
                   11117:     if ($needroles) {
                   11118:         $rolehash = {'all' => 'all'};
1.385     albertel 11119:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11120: 	if (&Apache::lonnet::error(%user_roles)) {
                   11121: 	    undef(%user_roles);
                   11122: 	}
                   11123:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11124:             my ($role)=split(/\:/,$item,2);
                   11125:             if ($role eq 'cr') { next; }
                   11126:             if ($role =~ /^cr/) {
                   11127:                 $$rolehash{$role} = (split('/',$role))[3];
                   11128:             } else {
                   11129:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11130:             }
                   11131:         }
                   11132:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11133:             push(@{$allroles},$key);
                   11134:         }
                   11135:         push (@{$allroles},'st');
                   11136:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11137:     }
                   11138:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11139: }
                   11140: 
1.555     raeburn  11141: sub user_picker {
1.1075.2.127  raeburn  11142:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11143:     my $currdom = $dom;
1.1075.2.114  raeburn  11144:     my @alldoms = &Apache::lonnet::all_domains();
                   11145:     if (@alldoms == 1) {
                   11146:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11147:                                                ['directorysrch'],$alldoms[0]);
                   11148:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11149:         my $showdom = $domdesc;
                   11150:         if ($showdom eq '') {
                   11151:             $showdom = $dom;
                   11152:         }
                   11153:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11154:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11155:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11156:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11157:             }
                   11158:         }
                   11159:     }
1.555     raeburn  11160:     my %curr_selected = (
                   11161:                         srchin => 'dom',
1.580     raeburn  11162:                         srchby => 'lastname',
1.555     raeburn  11163:                       );
                   11164:     my $srchterm;
1.625     raeburn  11165:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11166:         if ($srch->{'srchby'} ne '') {
                   11167:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11168:         }
                   11169:         if ($srch->{'srchin'} ne '') {
                   11170:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11171:         }
                   11172:         if ($srch->{'srchtype'} ne '') {
                   11173:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11174:         }
                   11175:         if ($srch->{'srchdomain'} ne '') {
                   11176:             $currdom = $srch->{'srchdomain'};
                   11177:         }
                   11178:         $srchterm = $srch->{'srchterm'};
                   11179:     }
1.1075.2.98  raeburn  11180:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11181:                     'usr'       => 'Search criteria',
1.563     raeburn  11182:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11183:                     'uname'     => 'username',
                   11184:                     'lastname'  => 'last name',
1.555     raeburn  11185:                     'lastfirst' => 'last name, first name',
1.558     albertel 11186:                     'crs'       => 'in this course',
1.576     raeburn  11187:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11188:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11189:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11190:                     'exact'     => 'is',
                   11191:                     'contains'  => 'contains',
1.569     raeburn  11192:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  11193:                                        );
                   11194:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11195:                     'youm'      => "You must include some text to search for.",
                   11196:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11197:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11198:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11199:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11200:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11201:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11202:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11203:                                        );
1.1075.2.98  raeburn  11204:     &html_escape(\%html_lt);
                   11205:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  11206:     my $domform;
1.1075.2.126  raeburn  11207:     my $allow_blank = 1;
1.1075.2.115  raeburn  11208:     if ($fixeddom) {
1.1075.2.126  raeburn  11209:         $allow_blank = 0;
                   11210:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  11211:     } else {
1.1075.2.126  raeburn  11212:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  11213:     }
1.563     raeburn  11214:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11215: 
                   11216:     my @srchins = ('crs','dom','alc','instd');
                   11217: 
                   11218:     foreach my $option (@srchins) {
                   11219:         # FIXME 'alc' option unavailable until 
                   11220:         #       loncreateuser::print_user_query_page()
                   11221:         #       has been completed.
                   11222:         next if ($option eq 'alc');
1.880     raeburn  11223:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11224:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  11225:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11226:         if ($curr_selected{'srchin'} eq $option) {
                   11227:             $srchinsel .= ' 
1.1075.2.98  raeburn  11228:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11229:         } else {
                   11230:             $srchinsel .= '
1.1075.2.98  raeburn  11231:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11232:         }
1.555     raeburn  11233:     }
1.563     raeburn  11234:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11235: 
                   11236:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11237:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11238:         if ($curr_selected{'srchby'} eq $option) {
                   11239:             $srchbysel .= '
1.1075.2.98  raeburn  11240:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11241:         } else {
                   11242:             $srchbysel .= '
1.1075.2.98  raeburn  11243:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11244:          }
                   11245:     }
                   11246:     $srchbysel .= "\n  </select>\n";
                   11247: 
                   11248:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11249:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11250:         if ($curr_selected{'srchtype'} eq $option) {
                   11251:             $srchtypesel .= '
1.1075.2.98  raeburn  11252:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11253:         } else {
                   11254:             $srchtypesel .= '
1.1075.2.98  raeburn  11255:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11256:         }
                   11257:     }
                   11258:     $srchtypesel .= "\n  </select>\n";
                   11259: 
1.558     albertel 11260:     my ($newuserscript,$new_user_create);
1.994     raeburn  11261:     my $context_dom = $env{'request.role.domain'};
                   11262:     if ($context eq 'requestcrs') {
                   11263:         if ($env{'form.coursedom'} ne '') { 
                   11264:             $context_dom = $env{'form.coursedom'};
                   11265:         }
                   11266:     }
1.556     raeburn  11267:     if ($forcenewuser) {
1.576     raeburn  11268:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11269:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11270:                 if ($cancreate) {
                   11271:                     $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>';
                   11272:                 } else {
1.799     bisitz   11273:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11274:                     my %usertypetext = (
                   11275:                         official   => 'institutional',
                   11276:                         unofficial => 'non-institutional',
                   11277:                     );
1.799     bisitz   11278:                     $new_user_create = '<p class="LC_warning">'
                   11279:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11280:                                       .' '
                   11281:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11282:                                           ,'<a href="'.$helplink.'">','</a>')
                   11283:                                       .'</p><br />';
1.627     raeburn  11284:                 }
1.576     raeburn  11285:             }
                   11286:         }
                   11287: 
1.556     raeburn  11288:         $newuserscript = <<"ENDSCRIPT";
                   11289: 
1.570     raeburn  11290: function setSearch(createnew,callingForm) {
1.556     raeburn  11291:     if (createnew == 1) {
1.570     raeburn  11292:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11293:             if (callingForm.srchby.options[i].value == 'uname') {
                   11294:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11295:             }
                   11296:         }
1.570     raeburn  11297:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11298:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11299: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11300:             }
                   11301:         }
1.570     raeburn  11302:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11303:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11304:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11305:             }
                   11306:         }
1.570     raeburn  11307:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11308:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11309:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11310:             }
                   11311:         }
                   11312:     }
                   11313: }
                   11314: ENDSCRIPT
1.558     albertel 11315: 
1.556     raeburn  11316:     }
                   11317: 
1.555     raeburn  11318:     my $output = <<"END_BLOCK";
1.556     raeburn  11319: <script type="text/javascript">
1.824     bisitz   11320: // <![CDATA[
1.570     raeburn  11321: function validateEntry(callingForm) {
1.558     albertel 11322: 
1.556     raeburn  11323:     var checkok = 1;
1.558     albertel 11324:     var srchin;
1.570     raeburn  11325:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11326: 	if ( callingForm.srchin[i].checked ) {
                   11327: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11328: 	}
                   11329:     }
                   11330: 
1.570     raeburn  11331:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11332:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11333:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11334:     var srchterm =  callingForm.srchterm.value;
                   11335:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11336:     var msg = "";
                   11337: 
                   11338:     if (srchterm == "") {
                   11339:         checkok = 0;
1.1075.2.98  raeburn  11340:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11341:     }
                   11342: 
1.569     raeburn  11343:     if (srchtype== 'begins') {
                   11344:         if (srchterm.length < 2) {
                   11345:             checkok = 0;
1.1075.2.98  raeburn  11346:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11347:         }
                   11348:     }
                   11349: 
1.556     raeburn  11350:     if (srchtype== 'contains') {
                   11351:         if (srchterm.length < 3) {
                   11352:             checkok = 0;
1.1075.2.98  raeburn  11353:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11354:         }
                   11355:     }
                   11356:     if (srchin == 'instd') {
                   11357:         if (srchdomain == '') {
                   11358:             checkok = 0;
1.1075.2.98  raeburn  11359:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11360:         }
                   11361:     }
                   11362:     if (srchin == 'dom') {
                   11363:         if (srchdomain == '') {
                   11364:             checkok = 0;
1.1075.2.98  raeburn  11365:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11366:         }
                   11367:     }
                   11368:     if (srchby == 'lastfirst') {
                   11369:         if (srchterm.indexOf(",") == -1) {
                   11370:             checkok = 0;
1.1075.2.98  raeburn  11371:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11372:         }
                   11373:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11374:             checkok = 0;
1.1075.2.98  raeburn  11375:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11376:         }
                   11377:     }
                   11378:     if (checkok == 0) {
1.1075.2.98  raeburn  11379:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11380:         return;
                   11381:     }
                   11382:     if (checkok == 1) {
1.570     raeburn  11383:         callingForm.submit();
1.556     raeburn  11384:     }
                   11385: }
                   11386: 
                   11387: $newuserscript
                   11388: 
1.824     bisitz   11389: // ]]>
1.556     raeburn  11390: </script>
1.558     albertel 11391: 
                   11392: $new_user_create
                   11393: 
1.555     raeburn  11394: END_BLOCK
1.558     albertel 11395: 
1.876     raeburn  11396:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  11397:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11398:                $domform.
                   11399:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  11400:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11401:                $srchbysel.
                   11402:                $srchtypesel. 
                   11403:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11404:                $srchinsel.
                   11405:                &Apache::lonhtmlcommon::row_closure(1). 
                   11406:                &Apache::lonhtmlcommon::end_pick_box().
                   11407:                '<br />';
1.1075.2.114  raeburn  11408:     return ($output,1);
1.555     raeburn  11409: }
                   11410: 
1.612     raeburn  11411: sub user_rule_check {
1.615     raeburn  11412:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  11413:     my ($response,%inst_response);
1.612     raeburn  11414:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  11415:         if (keys(%{$usershash}) > 1) {
                   11416:             my (%by_username,%by_id,%userdoms);
                   11417:             my $checkid;
1.612     raeburn  11418:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  11419:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11420:                     $checkid = 1;
                   11421:                 }
                   11422:             }
                   11423:             foreach my $user (keys(%{$usershash})) {
                   11424:                 my ($uname,$udom) = split(/:/,$user);
                   11425:                 if ($checkid) {
                   11426:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11427:                         if ($usershash->{$user}->{'id'} ne '') {
                   11428:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   11429:                             $userdoms{$udom} = 1;
                   11430:                             if (ref($inst_results) eq 'HASH') {
                   11431:                                 $inst_results->{$uname.':'.$udom} = {};
                   11432:                             }
                   11433:                         }
                   11434:                     }
                   11435:                 } else {
                   11436:                     $by_username{$udom}{$uname} = 1;
                   11437:                     $userdoms{$udom} = 1;
                   11438:                     if (ref($inst_results) eq 'HASH') {
                   11439:                         $inst_results->{$uname.':'.$udom} = {};
                   11440:                     }
                   11441:                 }
                   11442:             }
                   11443:             foreach my $udom (keys(%userdoms)) {
                   11444:                 if (!$got_rules->{$udom}) {
                   11445:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11446:                                                              ['usercreation'],$udom);
                   11447:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11448:                         foreach my $item ('username','id') {
                   11449:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11450:                                 $$curr_rules{$udom}{$item} =
                   11451:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   11452:                             }
                   11453:                         }
                   11454:                     }
                   11455:                     $got_rules->{$udom} = 1;
                   11456:                 }
                   11457:             }
                   11458:             if ($checkid) {
                   11459:                 foreach my $udom (keys(%by_id)) {
                   11460:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11461:                     if ($outcome eq 'ok') {
                   11462:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11463:                             my $uname = $by_id{$udom}{$id};
                   11464:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11465:                         }
                   11466:                         if (ref($results) eq 'HASH') {
                   11467:                             foreach my $uname (keys(%{$results})) {
                   11468:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11469:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11470:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11471:                                 }
                   11472:                             }
                   11473:                         }
                   11474:                     }
1.612     raeburn  11475:                 }
1.615     raeburn  11476:             } else {
1.1075.2.99  raeburn  11477:                 foreach my $udom (keys(%by_username)) {
                   11478:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11479:                     if ($outcome eq 'ok') {
                   11480:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11481:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11482:                         }
                   11483:                         if (ref($results) eq 'HASH') {
                   11484:                             foreach my $uname (keys(%{$results})) {
                   11485:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11486:                             }
                   11487:                         }
                   11488:                     }
                   11489:                 }
1.612     raeburn  11490:             }
1.1075.2.99  raeburn  11491:         } elsif (keys(%{$usershash}) == 1) {
                   11492:             my $user = (keys(%{$usershash}))[0];
                   11493:             my ($uname,$udom) = split(/:/,$user);
                   11494:             if (($udom ne '') && ($uname ne '')) {
                   11495:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11496:                     if (ref($checks) eq 'HASH') {
                   11497:                         if (defined($checks->{'username'})) {
                   11498:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   11499:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11500:                         } elsif (defined($checks->{'id'})) {
                   11501:                             if ($usershash->{$user}->{'id'} ne '') {
                   11502:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11503:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11504:                                                                   $usershash->{$user}->{'id'});
                   11505:                             } else {
                   11506:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11507:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11508:                             }
                   11509:                         }
                   11510:                     } else {
                   11511:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11512:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11513:                        return;
                   11514:                     }
                   11515:                     if (!$got_rules->{$udom}) {
                   11516:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11517:                                                                  ['usercreation'],$udom);
                   11518:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11519:                             foreach my $item ('username','id') {
                   11520:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11521:                                    $$curr_rules{$udom}{$item} =
                   11522:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11523:                                 }
                   11524:                             }
1.585     raeburn  11525:                         }
1.1075.2.99  raeburn  11526:                         $got_rules->{$udom} = 1;
1.585     raeburn  11527:                     }
                   11528:                 }
1.1075.2.99  raeburn  11529:             } else {
                   11530:                 return;
                   11531:             }
                   11532:         } else {
                   11533:             return;
                   11534:         }
                   11535:         foreach my $user (keys(%{$usershash})) {
                   11536:             my ($uname,$udom) = split(/:/,$user);
                   11537:             next if (($udom eq '') || ($uname eq ''));
                   11538:             my $id;
                   11539:             if (ref($inst_results) eq 'HASH') {
                   11540:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11541:                     $id = $inst_results->{$user}->{'id'};
                   11542:                 }
                   11543:             }
                   11544:             if ($id eq '') {
                   11545:                 if (ref($usershash->{$user})) {
                   11546:                     $id = $usershash->{$user}->{'id'};
                   11547:                 }
1.585     raeburn  11548:             }
1.612     raeburn  11549:             foreach my $item (keys(%{$checks})) {
                   11550:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11551:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11552:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  11553:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11554:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11555:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11556:                                 if ($rule_check{$rule}) {
                   11557:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  11558:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11559:                                         if (ref($inst_results) eq 'HASH') {
                   11560:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11561:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11562:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  11563:                                                 } elsif ($item eq 'id') {
                   11564:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11565:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11566:                                                     }
1.615     raeburn  11567:                                                 }
1.612     raeburn  11568:                                             }
                   11569:                                         }
1.615     raeburn  11570:                                     }
                   11571:                                     last;
1.585     raeburn  11572:                                 }
                   11573:                             }
                   11574:                         }
                   11575:                     }
                   11576:                 }
                   11577:             }
                   11578:         }
                   11579:     }
1.612     raeburn  11580:     return;
                   11581: }
                   11582: 
                   11583: sub user_rule_formats {
                   11584:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11585:     my %text = ( 
                   11586:                  'username' => 'Usernames',
                   11587:                  'id'       => 'IDs',
                   11588:                );
                   11589:     my $output;
                   11590:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11591:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11592:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11593:             $output = '<br />'.
                   11594:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11595:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11596:                       ' <ul>';
1.612     raeburn  11597:             foreach my $rule (@{$ruleorder}) {
                   11598:                 if (ref($curr_rules) eq 'ARRAY') {
                   11599:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11600:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11601:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11602:                                         $rules->{$rule}{'desc'}.'</li>';
                   11603:                         }
                   11604:                     }
                   11605:                 }
                   11606:             }
                   11607:             $output .= '</ul>';
                   11608:         }
                   11609:     }
                   11610:     return $output;
                   11611: }
                   11612: 
                   11613: sub instrule_disallow_msg {
1.615     raeburn  11614:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11615:     my $response;
                   11616:     my %text = (
                   11617:                   item   => 'username',
                   11618:                   items  => 'usernames',
                   11619:                   match  => 'matches',
                   11620:                   do     => 'does',
                   11621:                   action => 'a username',
                   11622:                   one    => 'one',
                   11623:                );
                   11624:     if ($count > 1) {
                   11625:         $text{'item'} = 'usernames';
                   11626:         $text{'match'} ='match';
                   11627:         $text{'do'} = 'do';
                   11628:         $text{'action'} = 'usernames',
                   11629:         $text{'one'} = 'ones';
                   11630:     }
                   11631:     if ($checkitem eq 'id') {
                   11632:         $text{'items'} = 'IDs';
                   11633:         $text{'item'} = 'ID';
                   11634:         $text{'action'} = 'an ID';
1.615     raeburn  11635:         if ($count > 1) {
                   11636:             $text{'item'} = 'IDs';
                   11637:             $text{'action'} = 'IDs';
                   11638:         }
1.612     raeburn  11639:     }
1.674     bisitz   11640:     $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  11641:     if ($mode eq 'upload') {
                   11642:         if ($checkitem eq 'username') {
                   11643:             $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'}.");
                   11644:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11645:             $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  11646:         }
1.669     raeburn  11647:     } elsif ($mode eq 'selfcreate') {
                   11648:         if ($checkitem eq 'id') {
                   11649:             $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.");
                   11650:         }
1.615     raeburn  11651:     } else {
                   11652:         if ($checkitem eq 'username') {
                   11653:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11654:         } elsif ($checkitem eq 'id') {
                   11655:             $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.");
                   11656:         }
1.612     raeburn  11657:     }
                   11658:     return $response;
1.585     raeburn  11659: }
                   11660: 
1.624     raeburn  11661: sub personal_data_fieldtitles {
                   11662:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11663:                         id => 'Student/Employee ID',
                   11664:                         permanentemail => 'E-mail address',
                   11665:                         lastname => 'Last Name',
                   11666:                         firstname => 'First Name',
                   11667:                         middlename => 'Middle Name',
                   11668:                         generation => 'Generation',
                   11669:                         gen => 'Generation',
1.765     raeburn  11670:                         inststatus => 'Affiliation',
1.624     raeburn  11671:                    );
                   11672:     return %fieldtitles;
                   11673: }
                   11674: 
1.642     raeburn  11675: sub sorted_inst_types {
                   11676:     my ($dom) = @_;
1.1075.2.70  raeburn  11677:     my ($usertypes,$order);
                   11678:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11679:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11680:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11681:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11682:     } else {
                   11683:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11684:     }
1.642     raeburn  11685:     my $othertitle = &mt('All users');
                   11686:     if ($env{'request.course.id'}) {
1.668     raeburn  11687:         $othertitle  = &mt('Any users');
1.642     raeburn  11688:     }
                   11689:     my @types;
                   11690:     if (ref($order) eq 'ARRAY') {
                   11691:         @types = @{$order};
                   11692:     }
                   11693:     if (@types == 0) {
                   11694:         if (ref($usertypes) eq 'HASH') {
                   11695:             @types = sort(keys(%{$usertypes}));
                   11696:         }
                   11697:     }
                   11698:     if (keys(%{$usertypes}) > 0) {
                   11699:         $othertitle = &mt('Other users');
                   11700:     }
                   11701:     return ($othertitle,$usertypes,\@types);
                   11702: }
                   11703: 
1.645     raeburn  11704: sub get_institutional_codes {
1.1075.2.157  raeburn  11705:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11706: # Get complete list of course sections to update
                   11707:     my @currsections = ();
                   11708:     my @currxlists = ();
1.1075.2.157  raeburn  11709:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11710:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11711:     my $crskey = $crs.':'.$coursecode;
                   11712:     @{$unclutteredsec{$crskey}} = ();
                   11713:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11714: 
                   11715:     if ($$settings{'internal.sectionnums'} ne '') {
                   11716:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11717:     }
                   11718: 
                   11719:     if ($$settings{'internal.crosslistings'} ne '') {
                   11720:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11721:     }
                   11722: 
                   11723:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11724:         foreach my $xl (@currxlists) {
                   11725:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11726:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11727:                     push(@{$allcourses},$1);
1.645     raeburn  11728:                     $$LC_code{$1} = $2;
                   11729:                 }
                   11730:             }
                   11731:         }
                   11732:     }
1.1075.2.157  raeburn  11733: 
1.645     raeburn  11734:     if (@currsections > 0) {
1.1075.2.157  raeburn  11735:         foreach my $sec (@currsections) {
                   11736:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11737:                 my $instsec = $1;
1.645     raeburn  11738:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11739:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11740:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11741:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11742:                 }
                   11743:             }
                   11744:         }
                   11745:     }
                   11746: 
                   11747:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11748:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11749:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11750:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11751:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11752:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11753:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11754:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11755:                 }
                   11756:             }
                   11757:         }
                   11758:     }
                   11759:     return;
                   11760: }
                   11761: 
1.971     raeburn  11762: sub get_standard_codeitems {
                   11763:     return ('Year','Semester','Department','Number','Section');
                   11764: }
                   11765: 
1.112     bowersj2 11766: =pod
                   11767: 
1.780     raeburn  11768: =head1 Slot Helpers
                   11769: 
                   11770: =over 4
                   11771: 
                   11772: =item * sorted_slots()
                   11773: 
1.1040    raeburn  11774: Sorts an array of slot names in order of an optional sort key,
                   11775: default sort is by slot start time (earliest first). 
1.780     raeburn  11776: 
                   11777: Inputs:
                   11778: 
                   11779: =over 4
                   11780: 
                   11781: slotsarr  - Reference to array of unsorted slot names.
                   11782: 
                   11783: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11784: 
1.1040    raeburn  11785: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11786: 
1.549     albertel 11787: =back
                   11788: 
1.780     raeburn  11789: Returns:
                   11790: 
                   11791: =over 4
                   11792: 
1.1040    raeburn  11793: sorted   - An array of slot names sorted by a specified sort key 
                   11794:            (default sort key is start time of the slot).
1.780     raeburn  11795: 
                   11796: =back
                   11797: 
                   11798: =cut
                   11799: 
                   11800: 
                   11801: sub sorted_slots {
1.1040    raeburn  11802:     my ($slotsarr,$slots,$sortkey) = @_;
                   11803:     if ($sortkey eq '') {
                   11804:         $sortkey = 'starttime';
                   11805:     }
1.780     raeburn  11806:     my @sorted;
                   11807:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11808:         @sorted =
                   11809:             sort {
                   11810:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11811:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11812:                      }
                   11813:                      if (ref($slots->{$a})) { return -1;}
                   11814:                      if (ref($slots->{$b})) { return 1;}
                   11815:                      return 0;
                   11816:                  } @{$slotsarr};
                   11817:     }
                   11818:     return @sorted;
                   11819: }
                   11820: 
1.1040    raeburn  11821: =pod
                   11822: 
                   11823: =item * get_future_slots()
                   11824: 
                   11825: Inputs:
                   11826: 
                   11827: =over 4
                   11828: 
                   11829: cnum - course number
                   11830: 
                   11831: cdom - course domain
                   11832: 
                   11833: now - current UNIX time
                   11834: 
                   11835: symb - optional symb
                   11836: 
                   11837: =back
                   11838: 
                   11839: Returns:
                   11840: 
                   11841: =over 4
                   11842: 
                   11843: sorted_reservable - ref to array of student_schedulable slots currently 
                   11844:                     reservable, ordered by end date of reservation period.
                   11845: 
                   11846: reservable_now - ref to hash of student_schedulable slots currently
                   11847:                  reservable.
                   11848: 
                   11849:     Keys in inner hash are:
                   11850:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11851:     (b) endreserve: end date of reservation period.
                   11852:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11853:         selected.
1.1040    raeburn  11854: 
                   11855: sorted_future - ref to array of student_schedulable slots reservable in
                   11856:                 the future, ordered by start date of reservation period.
                   11857: 
                   11858: future_reservable - ref to hash of student_schedulable slots reservable
                   11859:                     in the future.
                   11860: 
                   11861:     Keys in inner hash are:
                   11862:     (a) symb: either blank or symb to which slot use is restricted.
                   11863:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11864:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11865:         selected.
1.1040    raeburn  11866: 
                   11867: =back
                   11868: 
                   11869: =cut
                   11870: 
                   11871: sub get_future_slots {
                   11872:     my ($cnum,$cdom,$now,$symb) = @_;
                   11873:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11874:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11875:     foreach my $slot (keys(%slots)) {
                   11876:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11877:         if ($symb) {
                   11878:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11879:                      ($slots{$slot}->{'symb'} ne $symb));
                   11880:         }
                   11881:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11882:             ($slots{$slot}->{'endtime'} > $now)) {
                   11883:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11884:                 my $userallowed = 0;
                   11885:                 if ($slots{$slot}->{'allowedsections'}) {
                   11886:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11887:                     if (!defined($env{'request.role.sec'})
                   11888:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11889:                         $userallowed=1;
                   11890:                     } else {
                   11891:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11892:                             $userallowed=1;
                   11893:                         }
                   11894:                     }
                   11895:                     unless ($userallowed) {
                   11896:                         if (defined($env{'request.course.groups'})) {
                   11897:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11898:                             foreach my $group (@groups) {
                   11899:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11900:                                     $userallowed=1;
                   11901:                                     last;
                   11902:                                 }
                   11903:                             }
                   11904:                         }
                   11905:                     }
                   11906:                 }
                   11907:                 if ($slots{$slot}->{'allowedusers'}) {
                   11908:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11909:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11910:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11911:                         $userallowed = 1;
                   11912:                     }
                   11913:                 }
                   11914:                 next unless($userallowed);
                   11915:             }
                   11916:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11917:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11918:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11919:             my $uniqueperiod;
                   11920:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11921:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11922:             }
1.1040    raeburn  11923:             if (($startreserve < $now) &&
                   11924:                 (!$endreserve || $endreserve > $now)) {
                   11925:                 my $lastres = $endreserve;
                   11926:                 if (!$lastres) {
                   11927:                     $lastres = $slots{$slot}->{'starttime'};
                   11928:                 }
                   11929:                 $reservable_now{$slot} = {
                   11930:                                            symb       => $symb,
1.1075.2.104  raeburn  11931:                                            endreserve => $lastres,
                   11932:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11933:                                          };
                   11934:             } elsif (($startreserve > $now) &&
                   11935:                      (!$endreserve || $endreserve > $startreserve)) {
                   11936:                 $future_reservable{$slot} = {
                   11937:                                               symb         => $symb,
1.1075.2.104  raeburn  11938:                                               startreserve => $startreserve,
                   11939:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11940:                                             };
                   11941:             }
                   11942:         }
                   11943:     }
                   11944:     my @unsorted_reservable = keys(%reservable_now);
                   11945:     if (@unsorted_reservable > 0) {
                   11946:         @sorted_reservable = 
                   11947:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11948:     }
                   11949:     my @unsorted_future = keys(%future_reservable);
                   11950:     if (@unsorted_future > 0) {
                   11951:         @sorted_future =
                   11952:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11953:     }
                   11954:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11955: }
1.780     raeburn  11956: 
                   11957: =pod
                   11958: 
1.1057    foxr     11959: =back
                   11960: 
1.549     albertel 11961: =head1 HTTP Helpers
                   11962: 
                   11963: =over 4
                   11964: 
1.648     raeburn  11965: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11966: 
1.258     albertel 11967: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11968: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11969: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11970: 
                   11971: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11972: $possible_names is an ref to an array of form element names.  As an example:
                   11973: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11974: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11975: 
                   11976: =cut
1.1       albertel 11977: 
1.6       albertel 11978: sub get_unprocessed_cgi {
1.25      albertel 11979:   my ($query,$possible_names)= @_;
1.26      matthew  11980:   # $Apache::lonxml::debug=1;
1.356     albertel 11981:   foreach my $pair (split(/&/,$query)) {
                   11982:     my ($name, $value) = split(/=/,$pair);
1.369     www      11983:     $name = &unescape($name);
1.25      albertel 11984:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11985:       $value =~ tr/+/ /;
                   11986:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11987:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11988:     }
1.16      harris41 11989:   }
1.6       albertel 11990: }
                   11991: 
1.112     bowersj2 11992: =pod
                   11993: 
1.648     raeburn  11994: =item * &cacheheader() 
1.112     bowersj2 11995: 
                   11996: returns cache-controlling header code
                   11997: 
                   11998: =cut
                   11999: 
1.7       albertel 12000: sub cacheheader {
1.258     albertel 12001:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12002:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12003:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12004:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12005:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12006:     return $output;
1.7       albertel 12007: }
                   12008: 
1.112     bowersj2 12009: =pod
                   12010: 
1.648     raeburn  12011: =item * &no_cache($r) 
1.112     bowersj2 12012: 
                   12013: specifies header code to not have cache
                   12014: 
                   12015: =cut
                   12016: 
1.9       albertel 12017: sub no_cache {
1.216     albertel 12018:     my ($r) = @_;
                   12019:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12020: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12021:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12022:     $r->no_cache(1);
                   12023:     $r->header_out("Expires" => $date);
                   12024:     $r->header_out("Pragma" => "no-cache");
1.123     www      12025: }
                   12026: 
                   12027: sub content_type {
1.181     albertel 12028:     my ($r,$type,$charset) = @_;
1.299     foxr     12029:     if ($r) {
                   12030: 	#  Note that printout.pl calls this with undef for $r.
                   12031: 	&no_cache($r);
                   12032:     }
1.258     albertel 12033:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12034:     unless ($charset) {
                   12035: 	$charset=&Apache::lonlocal::current_encoding;
                   12036:     }
                   12037:     if ($charset) { $type.='; charset='.$charset; }
                   12038:     if ($r) {
                   12039: 	$r->content_type($type);
                   12040:     } else {
                   12041: 	print("Content-type: $type\n\n");
                   12042:     }
1.9       albertel 12043: }
1.25      albertel 12044: 
1.112     bowersj2 12045: =pod
                   12046: 
1.648     raeburn  12047: =item * &add_to_env($name,$value) 
1.112     bowersj2 12048: 
1.258     albertel 12049: adds $name to the %env hash with value
1.112     bowersj2 12050: $value, if $name already exists, the entry is converted to an array
                   12051: reference and $value is added to the array.
                   12052: 
                   12053: =cut
                   12054: 
1.25      albertel 12055: sub add_to_env {
                   12056:   my ($name,$value)=@_;
1.258     albertel 12057:   if (defined($env{$name})) {
                   12058:     if (ref($env{$name})) {
1.25      albertel 12059:       #already have multiple values
1.258     albertel 12060:       push(@{ $env{$name} },$value);
1.25      albertel 12061:     } else {
                   12062:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12063:       my $first=$env{$name};
                   12064:       undef($env{$name});
                   12065:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12066:     }
                   12067:   } else {
1.258     albertel 12068:     $env{$name}=$value;
1.25      albertel 12069:   }
1.31      albertel 12070: }
1.149     albertel 12071: 
                   12072: =pod
                   12073: 
1.648     raeburn  12074: =item * &get_env_multiple($name) 
1.149     albertel 12075: 
1.258     albertel 12076: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12077: values may be defined and end up as an array ref.
                   12078: 
                   12079: returns an array of values
                   12080: 
                   12081: =cut
                   12082: 
                   12083: sub get_env_multiple {
                   12084:     my ($name) = @_;
                   12085:     my @values;
1.258     albertel 12086:     if (defined($env{$name})) {
1.149     albertel 12087:         # exists is it an array
1.258     albertel 12088:         if (ref($env{$name})) {
                   12089:             @values=@{ $env{$name} };
1.149     albertel 12090:         } else {
1.258     albertel 12091:             $values[0]=$env{$name};
1.149     albertel 12092:         }
                   12093:     }
                   12094:     return(@values);
                   12095: }
                   12096: 
1.660     raeburn  12097: sub ask_for_embedded_content {
                   12098:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12099:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  12100:         %currsubfile,%unused,$rem);
1.1071    raeburn  12101:     my $counter = 0;
                   12102:     my $numnew = 0;
1.987     raeburn  12103:     my $numremref = 0;
                   12104:     my $numinvalid = 0;
                   12105:     my $numpathchg = 0;
                   12106:     my $numexisting = 0;
1.1071    raeburn  12107:     my $numunused = 0;
                   12108:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  12109:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12110:     my $heading = &mt('Upload embedded files');
                   12111:     my $buttontext = &mt('Upload');
                   12112: 
1.1075.2.11  raeburn  12113:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  12114:         if ($actionurl eq '/adm/dependencies') {
                   12115:             $navmap = Apache::lonnavmaps::navmap->new();
                   12116:         }
                   12117:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12118:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  12119:     }
1.1075.2.35  raeburn  12120:     if (($actionurl eq '/adm/portfolio') ||
                   12121:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12122:         my $current_path='/';
                   12123:         if ($env{'form.currentpath'}) {
                   12124:             $current_path = $env{'form.currentpath'};
                   12125:         }
                   12126:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  12127:             $udom = $cdom;
                   12128:             $uname = $cnum;
1.984     raeburn  12129:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12130:         } else {
                   12131:             $udom = $env{'user.domain'};
                   12132:             $uname = $env{'user.name'};
                   12133:             $url = '/userfiles/portfolio';
                   12134:         }
1.987     raeburn  12135:         $toplevel = $url.'/';
1.984     raeburn  12136:         $url .= $current_path;
                   12137:         $getpropath = 1;
1.987     raeburn  12138:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12139:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12140:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12141:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12142:         $toplevel = $url;
1.984     raeburn  12143:         if ($rest ne '') {
1.987     raeburn  12144:             $url .= $rest;
                   12145:         }
                   12146:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12147:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12148:             $url = $args->{'docs_url'};
                   12149:             $toplevel = $url;
1.1075.2.11  raeburn  12150:             if ($args->{'context'} eq 'paste') {
                   12151:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12152:                 ($path) =
                   12153:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12154:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12155:                 $fileloc =~ s{^/}{};
                   12156:             }
1.1071    raeburn  12157:         }
                   12158:     } elsif ($actionurl eq '/adm/dependencies') {
                   12159:         if ($env{'request.course.id'} ne '') {
                   12160:             if (ref($args) eq 'HASH') {
                   12161:                 $url = $args->{'docs_url'};
                   12162:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  12163:                 $toplevel = $url;
                   12164:                 unless ($toplevel =~ m{^/}) {
                   12165:                     $toplevel = "/$url";
                   12166:                 }
1.1075.2.11  raeburn  12167:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  12168:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12169:                     $path = $1;
                   12170:                 } else {
                   12171:                     ($path) =
                   12172:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12173:                 }
1.1075.2.79  raeburn  12174:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12175:                     $fileloc = $toplevel;
                   12176:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12177:                     my ($udom,$uname,$fname) =
                   12178:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12179:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12180:                 } else {
                   12181:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12182:                 }
1.1071    raeburn  12183:                 $fileloc =~ s{^/}{};
                   12184:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12185:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12186:             }
1.987     raeburn  12187:         }
1.1075.2.35  raeburn  12188:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12189:         $udom = $cdom;
                   12190:         $uname = $cnum;
                   12191:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12192:         $toplevel = $url;
                   12193:         $path = $url;
                   12194:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12195:         $fileloc =~ s{^/}{};
                   12196:     }
                   12197:     foreach my $file (keys(%{$allfiles})) {
                   12198:         my $embed_file;
                   12199:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12200:             $embed_file = $1;
                   12201:         } else {
                   12202:             $embed_file = $file;
                   12203:         }
1.1075.2.55  raeburn  12204:         my ($absolutepath,$cleaned_file);
                   12205:         if ($embed_file =~ m{^\w+://}) {
                   12206:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  12207:             $newfiles{$cleaned_file} = 1;
                   12208:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12209:         } else {
1.1075.2.55  raeburn  12210:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12211:             if ($embed_file =~ m{^/}) {
                   12212:                 $absolutepath = $embed_file;
                   12213:             }
1.1075.2.47  raeburn  12214:             if ($cleaned_file =~ m{/}) {
                   12215:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12216:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12217:                 my $item = $fname;
                   12218:                 if ($path ne '') {
                   12219:                     $item = $path.'/'.$fname;
                   12220:                     $subdependencies{$path}{$fname} = 1;
                   12221:                 } else {
                   12222:                     $dependencies{$item} = 1;
                   12223:                 }
                   12224:                 if ($absolutepath) {
                   12225:                     $mapping{$item} = $absolutepath;
                   12226:                 } else {
                   12227:                     $mapping{$item} = $embed_file;
                   12228:                 }
                   12229:             } else {
                   12230:                 $dependencies{$embed_file} = 1;
                   12231:                 if ($absolutepath) {
1.1075.2.47  raeburn  12232:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12233:                 } else {
1.1075.2.47  raeburn  12234:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12235:                 }
                   12236:             }
1.984     raeburn  12237:         }
                   12238:     }
1.1071    raeburn  12239:     my $dirptr = 16384;
1.984     raeburn  12240:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12241:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  12242:         if (($actionurl eq '/adm/portfolio') ||
                   12243:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  12244:             my ($sublistref,$listerror) =
                   12245:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12246:             if (ref($sublistref) eq 'ARRAY') {
                   12247:                 foreach my $line (@{$sublistref}) {
                   12248:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12249:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12250:                 }
1.984     raeburn  12251:             }
1.987     raeburn  12252:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12253:             if (opendir(my $dir,$url.'/'.$path)) {
                   12254:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12255:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12256:             }
1.1075.2.11  raeburn  12257:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12258:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12259:                   ($args->{'context'} eq 'paste')) ||
                   12260:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12261:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  12262:                 my $dir;
                   12263:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12264:                     $dir = $fileloc;
                   12265:                 } else {
                   12266:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12267:                 }
1.1071    raeburn  12268:                 if ($dir ne '') {
                   12269:                     my ($sublistref,$listerror) =
                   12270:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12271:                     if (ref($sublistref) eq 'ARRAY') {
                   12272:                         foreach my $line (@{$sublistref}) {
                   12273:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12274:                                 undef,$mtime)=split(/\&/,$line,12);
                   12275:                             unless (($testdir&$dirptr) ||
                   12276:                                     ($file_name =~ /^\.\.?$/)) {
                   12277:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12278:                             }
                   12279:                         }
                   12280:                     }
                   12281:                 }
1.984     raeburn  12282:             }
                   12283:         }
                   12284:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12285:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12286:                 my $item = $path.'/'.$file;
                   12287:                 unless ($mapping{$item} eq $item) {
                   12288:                     $pathchanges{$item} = 1;
                   12289:                 }
                   12290:                 $existing{$item} = 1;
                   12291:                 $numexisting ++;
                   12292:             } else {
                   12293:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12294:             }
                   12295:         }
1.1071    raeburn  12296:         if ($actionurl eq '/adm/dependencies') {
                   12297:             foreach my $path (keys(%currsubfile)) {
                   12298:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12299:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12300:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  12301:                              next if (($rem ne '') &&
                   12302:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12303:                                        (ref($navmap) &&
                   12304:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12305:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12306:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12307:                              $unused{$path.'/'.$file} = 1; 
                   12308:                          }
                   12309:                     }
                   12310:                 }
                   12311:             }
                   12312:         }
1.984     raeburn  12313:     }
1.987     raeburn  12314:     my %currfile;
1.1075.2.35  raeburn  12315:     if (($actionurl eq '/adm/portfolio') ||
                   12316:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12317:         my ($dirlistref,$listerror) =
                   12318:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12319:         if (ref($dirlistref) eq 'ARRAY') {
                   12320:             foreach my $line (@{$dirlistref}) {
                   12321:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12322:                 $currfile{$file_name} = 1;
                   12323:             }
1.984     raeburn  12324:         }
1.987     raeburn  12325:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12326:         if (opendir(my $dir,$url)) {
1.987     raeburn  12327:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12328:             map {$currfile{$_} = 1;} @dir_list;
                   12329:         }
1.1075.2.11  raeburn  12330:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12331:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12332:               ($args->{'context'} eq 'paste')) ||
                   12333:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12334:         if ($env{'request.course.id'} ne '') {
                   12335:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12336:             if ($dir ne '') {
                   12337:                 my ($dirlistref,$listerror) =
                   12338:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12339:                 if (ref($dirlistref) eq 'ARRAY') {
                   12340:                     foreach my $line (@{$dirlistref}) {
                   12341:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12342:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12343:                         unless (($testdir&$dirptr) ||
                   12344:                                 ($file_name =~ /^\.\.?$/)) {
                   12345:                             $currfile{$file_name} = [$size,$mtime];
                   12346:                         }
                   12347:                     }
                   12348:                 }
                   12349:             }
                   12350:         }
1.984     raeburn  12351:     }
                   12352:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12353:         if (exists($currfile{$file})) {
1.987     raeburn  12354:             unless ($mapping{$file} eq $file) {
                   12355:                 $pathchanges{$file} = 1;
                   12356:             }
                   12357:             $existing{$file} = 1;
                   12358:             $numexisting ++;
                   12359:         } else {
1.984     raeburn  12360:             $newfiles{$file} = 1;
                   12361:         }
                   12362:     }
1.1071    raeburn  12363:     foreach my $file (keys(%currfile)) {
                   12364:         unless (($file eq $filename) ||
                   12365:                 ($file eq $filename.'.bak') ||
                   12366:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  12367:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  12368:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12369:                     next if (($rem ne '') &&
                   12370:                              (($env{"httpref.$rem".$file} ne '') ||
                   12371:                               (ref($navmap) &&
                   12372:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12373:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12374:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12375:                 }
1.1075.2.11  raeburn  12376:             }
1.1071    raeburn  12377:             $unused{$file} = 1;
                   12378:         }
                   12379:     }
1.1075.2.11  raeburn  12380:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12381:         ($args->{'context'} eq 'paste')) {
                   12382:         $counter = scalar(keys(%existing));
                   12383:         $numpathchg = scalar(keys(%pathchanges));
                   12384:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  12385:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   12386:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12387:         $counter = scalar(keys(%existing));
                   12388:         $numpathchg = scalar(keys(%pathchanges));
                   12389:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  12390:     }
1.984     raeburn  12391:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12392:         if ($actionurl eq '/adm/dependencies') {
                   12393:             next if ($embed_file =~ m{^\w+://});
                   12394:         }
1.660     raeburn  12395:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12396:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12397:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12398:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  12399:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12400:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12401:         }
1.1075.2.35  raeburn  12402:         $upload_output .= '</td>';
1.1071    raeburn  12403:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  12404:             $upload_output.='<td align="right">'.
                   12405:                             '<span class="LC_info LC_fontsize_medium">'.
                   12406:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12407:             $numremref++;
1.660     raeburn  12408:         } elsif ($args->{'error_on_invalid_names'}
                   12409:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  12410:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12411:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12412:             $numinvalid++;
1.660     raeburn  12413:         } else {
1.1075.2.35  raeburn  12414:             $upload_output .= '<td>'.
                   12415:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12416:                                                      $embed_file,\%mapping,
1.1071    raeburn  12417:                                                      $allfiles,$codebase,'upload');
                   12418:             $counter ++;
                   12419:             $numnew ++;
1.987     raeburn  12420:         }
                   12421:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12422:     }
                   12423:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12424:         if ($actionurl eq '/adm/dependencies') {
                   12425:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12426:             $modify_output .= &start_data_table_row().
                   12427:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12428:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12429:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12430:                               '<td>'.$size.'</td>'.
                   12431:                               '<td>'.$mtime.'</td>'.
                   12432:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12433:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12434:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12435:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12436:                               &embedded_file_element('upload_embedded',$counter,
                   12437:                                                      $embed_file,\%mapping,
                   12438:                                                      $allfiles,$codebase,'modify').
                   12439:                               '</div></td>'.
                   12440:                               &end_data_table_row()."\n";
                   12441:             $counter ++;
                   12442:         } else {
                   12443:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12444:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12445:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12446:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12447:                               &Apache::loncommon::end_data_table_row()."\n";
                   12448:         }
                   12449:     }
                   12450:     my $delidx = $counter;
                   12451:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12452:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12453:         $delete_output .= &start_data_table_row().
                   12454:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12455:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12456:                           '<td>'.$size.'</td>'.
                   12457:                           '<td>'.$mtime.'</td>'.
                   12458:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12459:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12460:                           &embedded_file_element('upload_embedded',$delidx,
                   12461:                                                  $oldfile,\%mapping,$allfiles,
                   12462:                                                  $codebase,'delete').'</td>'.
                   12463:                           &end_data_table_row()."\n"; 
                   12464:         $numunused ++;
                   12465:         $delidx ++;
1.987     raeburn  12466:     }
                   12467:     if ($upload_output) {
                   12468:         $upload_output = &start_data_table().
                   12469:                          $upload_output.
                   12470:                          &end_data_table()."\n";
                   12471:     }
1.1071    raeburn  12472:     if ($modify_output) {
                   12473:         $modify_output = &start_data_table().
                   12474:                          &start_data_table_header_row().
                   12475:                          '<th>'.&mt('File').'</th>'.
                   12476:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12477:                          '<th>'.&mt('Modified').'</th>'.
                   12478:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12479:                          &end_data_table_header_row().
                   12480:                          $modify_output.
                   12481:                          &end_data_table()."\n";
                   12482:     }
                   12483:     if ($delete_output) {
                   12484:         $delete_output = &start_data_table().
                   12485:                          &start_data_table_header_row().
                   12486:                          '<th>'.&mt('File').'</th>'.
                   12487:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12488:                          '<th>'.&mt('Modified').'</th>'.
                   12489:                          '<th>'.&mt('Delete?').'</th>'.
                   12490:                          &end_data_table_header_row().
                   12491:                          $delete_output.
                   12492:                          &end_data_table()."\n";
                   12493:     }
1.987     raeburn  12494:     my $applies = 0;
                   12495:     if ($numremref) {
                   12496:         $applies ++;
                   12497:     }
                   12498:     if ($numinvalid) {
                   12499:         $applies ++;
                   12500:     }
                   12501:     if ($numexisting) {
                   12502:         $applies ++;
                   12503:     }
1.1071    raeburn  12504:     if ($counter || $numunused) {
1.987     raeburn  12505:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12506:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12507:                   $state.'<h3>'.$heading.'</h3>'; 
                   12508:         if ($actionurl eq '/adm/dependencies') {
                   12509:             if ($numnew) {
                   12510:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12511:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12512:                            $upload_output.'<br />'."\n";
                   12513:             }
                   12514:             if ($numexisting) {
                   12515:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12516:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12517:                            $modify_output.'<br />'."\n";
                   12518:                            $buttontext = &mt('Save changes');
                   12519:             }
                   12520:             if ($numunused) {
                   12521:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12522:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12523:                            $delete_output.'<br />'."\n";
                   12524:                            $buttontext = &mt('Save changes');
                   12525:             }
                   12526:         } else {
                   12527:             $output .= $upload_output.'<br />'."\n";
                   12528:         }
                   12529:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12530:                    $counter.'" />'."\n";
                   12531:         if ($actionurl eq '/adm/dependencies') { 
                   12532:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12533:                        $numnew.'" />'."\n";
                   12534:         } elsif ($actionurl eq '') {
1.987     raeburn  12535:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12536:         }
                   12537:     } elsif ($applies) {
                   12538:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12539:         if ($applies > 1) {
                   12540:             $output .=  
1.1075.2.35  raeburn  12541:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12542:             if ($numremref) {
                   12543:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12544:             }
                   12545:             if ($numinvalid) {
                   12546:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12547:             }
                   12548:             if ($numexisting) {
                   12549:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12550:             }
                   12551:             $output .= '</ul><br />';
                   12552:         } elsif ($numremref) {
                   12553:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12554:         } elsif ($numinvalid) {
                   12555:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12556:         } elsif ($numexisting) {
                   12557:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12558:         }
                   12559:         $output .= $upload_output.'<br />';
                   12560:     }
                   12561:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12562:     $chgcount = $counter;
1.987     raeburn  12563:     if (keys(%pathchanges) > 0) {
                   12564:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12565:             if ($counter) {
1.987     raeburn  12566:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12567:                                                   $embed_file,\%mapping,
1.1071    raeburn  12568:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12569:             } else {
                   12570:                 $pathchange_output .= 
                   12571:                     &start_data_table_row().
                   12572:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12573:                     $chgcount.'" checked="checked" /></td>'.
                   12574:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12575:                     '<td>'.$embed_file.
                   12576:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12577:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12578:                     '</td>'.&end_data_table_row();
1.660     raeburn  12579:             }
1.987     raeburn  12580:             $numpathchg ++;
                   12581:             $chgcount ++;
1.660     raeburn  12582:         }
                   12583:     }
1.1075.2.35  raeburn  12584:     if (($counter) || ($numunused)) {
1.987     raeburn  12585:         if ($numpathchg) {
                   12586:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12587:                        $numpathchg.'" />'."\n";
                   12588:         }
                   12589:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12590:             ($actionurl eq '/adm/imsimport')) {
                   12591:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12592:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12593:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12594:         } elsif ($actionurl eq '/adm/dependencies') {
                   12595:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12596:         }
1.1075.2.35  raeburn  12597:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12598:     } elsif ($numpathchg) {
                   12599:         my %pathchange = ();
                   12600:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12601:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12602:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12603:         }
1.987     raeburn  12604:     }
1.1071    raeburn  12605:     return ($output,$counter,$numpathchg);
1.987     raeburn  12606: }
                   12607: 
1.1075.2.47  raeburn  12608: =pod
                   12609: 
                   12610: =item * clean_path($name)
                   12611: 
                   12612: Performs clean-up of directories, subdirectories and filename in an
                   12613: embedded object, referenced in an HTML file which is being uploaded
                   12614: to a course or portfolio, where
                   12615: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12616: checked.
                   12617: 
                   12618: Clean-up is similar to replacements in lonnet::clean_filename()
                   12619: except each / between sub-directory and next level is preserved.
                   12620: 
                   12621: =cut
                   12622: 
                   12623: sub clean_path {
                   12624:     my ($embed_file) = @_;
                   12625:     $embed_file =~s{^/+}{};
                   12626:     my @contents;
                   12627:     if ($embed_file =~ m{/}) {
                   12628:         @contents = split(/\//,$embed_file);
                   12629:     } else {
                   12630:         @contents = ($embed_file);
                   12631:     }
                   12632:     my $lastidx = scalar(@contents)-1;
                   12633:     for (my $i=0; $i<=$lastidx; $i++) {
                   12634:         $contents[$i]=~s{\\}{/}g;
                   12635:         $contents[$i]=~s/\s+/\_/g;
                   12636:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12637:         if ($i == $lastidx) {
                   12638:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12639:         }
                   12640:     }
                   12641:     if ($lastidx > 0) {
                   12642:         return join('/',@contents);
                   12643:     } else {
                   12644:         return $contents[0];
                   12645:     }
                   12646: }
                   12647: 
1.987     raeburn  12648: sub embedded_file_element {
1.1071    raeburn  12649:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12650:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12651:                    (ref($codebase) eq 'HASH'));
                   12652:     my $output;
1.1071    raeburn  12653:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12654:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12655:     }
                   12656:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12657:                &escape($embed_file).'" />';
                   12658:     unless (($context eq 'upload_embedded') && 
                   12659:             ($mapping->{$embed_file} eq $embed_file)) {
                   12660:         $output .='
                   12661:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12662:     }
                   12663:     my $attrib;
                   12664:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12665:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12666:     }
                   12667:     $output .=
                   12668:         "\n\t\t".
                   12669:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12670:         $attrib.'" />';
                   12671:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12672:         $output .=
                   12673:             "\n\t\t".
                   12674:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12675:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12676:     }
1.987     raeburn  12677:     return $output;
1.660     raeburn  12678: }
                   12679: 
1.1071    raeburn  12680: sub get_dependency_details {
                   12681:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12682:     my ($size,$mtime,$showsize,$showmtime);
                   12683:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12684:         if ($embed_file =~ m{/}) {
                   12685:             my ($path,$fname) = split(/\//,$embed_file);
                   12686:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12687:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12688:             }
                   12689:         } else {
                   12690:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12691:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12692:             }
                   12693:         }
                   12694:         $showsize = $size/1024.0;
                   12695:         $showsize = sprintf("%.1f",$showsize);
                   12696:         if ($mtime > 0) {
                   12697:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12698:         }
                   12699:     }
                   12700:     return ($showsize,$showmtime);
                   12701: }
                   12702: 
                   12703: sub ask_embedded_js {
                   12704:     return <<"END";
                   12705: <script type="text/javascript"">
                   12706: // <![CDATA[
                   12707: function toggleBrowse(counter) {
                   12708:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12709:     var fileid = document.getElementById('embedded_item_'+counter);
                   12710:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12711:     if (chkboxid.checked == true) {
                   12712:         uploaddivid.style.display='block';
                   12713:     } else {
                   12714:         uploaddivid.style.display='none';
                   12715:         fileid.value = '';
                   12716:     }
                   12717: }
                   12718: // ]]>
                   12719: </script>
                   12720: 
                   12721: END
                   12722: }
                   12723: 
1.661     raeburn  12724: sub upload_embedded {
                   12725:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12726:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12727:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12728:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12729:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12730:         my $orig_uploaded_filename =
                   12731:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12732:         foreach my $type ('orig','ref','attrib','codebase') {
                   12733:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12734:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12735:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12736:             }
                   12737:         }
1.661     raeburn  12738:         my ($path,$fname) =
                   12739:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12740:         # no path, whole string is fname
                   12741:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12742:         $fname = &Apache::lonnet::clean_filename($fname);
                   12743:         # See if there is anything left
                   12744:         next if ($fname eq '');
                   12745: 
                   12746:         # Check if file already exists as a file or directory.
                   12747:         my ($state,$msg);
                   12748:         if ($context eq 'portfolio') {
                   12749:             my $port_path = $dirpath;
                   12750:             if ($group ne '') {
                   12751:                 $port_path = "groups/$group/$port_path";
                   12752:             }
1.987     raeburn  12753:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12754:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12755:                                               $dir_root,$port_path,$disk_quota,
                   12756:                                               $current_disk_usage,$uname,$udom);
                   12757:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12758:                 || $state eq 'file_locked') {
1.661     raeburn  12759:                 $output .= $msg;
                   12760:                 next;
                   12761:             }
                   12762:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12763:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12764:             if ($state eq 'exists') {
                   12765:                 $output .= $msg;
                   12766:                 next;
                   12767:             }
                   12768:         }
                   12769:         # Check if extension is valid
                   12770:         if (($fname =~ /\.(\w+)$/) &&
                   12771:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12772:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12773:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12774:             next;
                   12775:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12776:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12777:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12778:             next;
                   12779:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12780:             $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  12781:             next;
                   12782:         }
                   12783:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12784:         my $subdir = $path;
                   12785:         $subdir =~ s{/+$}{};
1.661     raeburn  12786:         if ($context eq 'portfolio') {
1.984     raeburn  12787:             my $result;
                   12788:             if ($state eq 'existingfile') {
                   12789:                 $result=
                   12790:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12791:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12792:             } else {
1.984     raeburn  12793:                 $result=
                   12794:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12795:                                                     $dirpath.
1.1075.2.35  raeburn  12796:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12797:                 if ($result !~ m|^/uploaded/|) {
                   12798:                     $output .= '<span class="LC_error">'
                   12799:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12800:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12801:                                .'</span><br />';
                   12802:                     next;
                   12803:                 } else {
1.987     raeburn  12804:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12805:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12806:                 }
1.661     raeburn  12807:             }
1.1075.2.35  raeburn  12808:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12809:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12810:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12811:             my $result =
1.1075.2.35  raeburn  12812:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12813:             if ($result !~ m|^/uploaded/|) {
                   12814:                 $output .= '<span class="LC_error">'
                   12815:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12816:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12817:                            .'</span><br />';
                   12818:                     next;
                   12819:             } else {
                   12820:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12821:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12822:                 if ($context eq 'syllabus') {
                   12823:                     &Apache::lonnet::make_public_indefinitely($result);
                   12824:                 }
1.987     raeburn  12825:             }
1.661     raeburn  12826:         } else {
                   12827: # Save the file
                   12828:             my $target = $env{'form.embedded_item_'.$i};
                   12829:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12830:             my $dest = $fullpath.$fname;
                   12831:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12832:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12833:             my $count;
                   12834:             my $filepath = $dir_root;
1.1027    raeburn  12835:             foreach my $subdir (@parts) {
                   12836:                 $filepath .= "/$subdir";
                   12837:                 if (!-e $filepath) {
1.661     raeburn  12838:                     mkdir($filepath,0770);
                   12839:                 }
                   12840:             }
                   12841:             my $fh;
                   12842:             if (!open($fh,'>'.$dest)) {
                   12843:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12844:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12845:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12846:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12847:                            '</span><br />';
                   12848:             } else {
                   12849:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12850:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12851:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12852:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12853:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12854:                               '</span><br />';
                   12855:                 } else {
1.987     raeburn  12856:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12857:                                $url.'</span>').'<br />';
                   12858:                     unless ($context eq 'testbank') {
                   12859:                         $footer .= &mt('View embedded file: [_1]',
                   12860:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12861:                     }
                   12862:                 }
                   12863:                 close($fh);
                   12864:             }
                   12865:         }
                   12866:         if ($env{'form.embedded_ref_'.$i}) {
                   12867:             $pathchange{$i} = 1;
                   12868:         }
                   12869:     }
                   12870:     if ($output) {
                   12871:         $output = '<p>'.$output.'</p>';
                   12872:     }
                   12873:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12874:     $returnflag = 'ok';
1.1071    raeburn  12875:     my $numpathchgs = scalar(keys(%pathchange));
                   12876:     if ($numpathchgs > 0) {
1.987     raeburn  12877:         if ($context eq 'portfolio') {
                   12878:             $output .= '<p>'.&mt('or').'</p>';
                   12879:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12880:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12881:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12882:             $returnflag = 'modify_orightml';
                   12883:         }
                   12884:     }
1.1071    raeburn  12885:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12886: }
                   12887: 
                   12888: sub modify_html_form {
                   12889:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12890:     my $end = 0;
                   12891:     my $modifyform;
                   12892:     if ($context eq 'upload_embedded') {
                   12893:         return unless (ref($pathchange) eq 'HASH');
                   12894:         if ($env{'form.number_embedded_items'}) {
                   12895:             $end += $env{'form.number_embedded_items'};
                   12896:         }
                   12897:         if ($env{'form.number_pathchange_items'}) {
                   12898:             $end += $env{'form.number_pathchange_items'};
                   12899:         }
                   12900:         if ($end) {
                   12901:             for (my $i=0; $i<$end; $i++) {
                   12902:                 if ($i < $env{'form.number_embedded_items'}) {
                   12903:                     next unless($pathchange->{$i});
                   12904:                 }
                   12905:                 $modifyform .=
                   12906:                     &start_data_table_row().
                   12907:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12908:                     'checked="checked" /></td>'.
                   12909:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12910:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12911:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12912:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12913:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12914:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12915:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12916:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12917:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12918:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12919:                     &end_data_table_row();
1.1071    raeburn  12920:             }
1.987     raeburn  12921:         }
                   12922:     } else {
                   12923:         $modifyform = $pathchgtable;
                   12924:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12925:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12926:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12927:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12928:         }
                   12929:     }
                   12930:     if ($modifyform) {
1.1071    raeburn  12931:         if ($actionurl eq '/adm/dependencies') {
                   12932:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12933:         }
1.987     raeburn  12934:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12935:                '<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".
                   12936:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12937:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12938:                '</ol></p>'."\n".'<p>'.
                   12939:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12940:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12941:                &start_data_table()."\n".
                   12942:                &start_data_table_header_row().
                   12943:                '<th>'.&mt('Change?').'</th>'.
                   12944:                '<th>'.&mt('Current reference').'</th>'.
                   12945:                '<th>'.&mt('Required reference').'</th>'.
                   12946:                &end_data_table_header_row()."\n".
                   12947:                $modifyform.
                   12948:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12949:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12950:                '</form>'."\n";
                   12951:     }
                   12952:     return;
                   12953: }
                   12954: 
                   12955: sub modify_html_refs {
1.1075.2.35  raeburn  12956:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12957:     my $container;
                   12958:     if ($context eq 'portfolio') {
                   12959:         $container = $env{'form.container'};
                   12960:     } elsif ($context eq 'coursedoc') {
                   12961:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12962:     } elsif ($context eq 'manage_dependencies') {
                   12963:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12964:         $container = "/$container";
1.1075.2.35  raeburn  12965:     } elsif ($context eq 'syllabus') {
                   12966:         $container = $url;
1.987     raeburn  12967:     } else {
1.1027    raeburn  12968:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12969:     }
                   12970:     my (%allfiles,%codebase,$output,$content);
                   12971:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12972:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12973:         if (wantarray) {
                   12974:             return ('',0,0); 
                   12975:         } else {
                   12976:             return;
                   12977:         }
                   12978:     }
                   12979:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12980:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12981:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12982:             if (wantarray) {
                   12983:                 return ('',0,0);
                   12984:             } else {
                   12985:                 return;
                   12986:             }
                   12987:         } 
1.987     raeburn  12988:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12989:         if ($content eq '-1') {
                   12990:             if (wantarray) {
                   12991:                 return ('',0,0);
                   12992:             } else {
                   12993:                 return;
                   12994:             }
                   12995:         }
1.987     raeburn  12996:     } else {
1.1071    raeburn  12997:         unless ($container =~ /^\Q$dir_root\E/) {
                   12998:             if (wantarray) {
                   12999:                 return ('',0,0);
                   13000:             } else {
                   13001:                 return;
                   13002:             }
                   13003:         } 
1.1075.2.128  raeburn  13004:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13005:             $content = join('', <$fh>);
                   13006:             close($fh);
                   13007:         } else {
1.1071    raeburn  13008:             if (wantarray) {
                   13009:                 return ('',0,0);
                   13010:             } else {
                   13011:                 return;
                   13012:             }
1.987     raeburn  13013:         }
                   13014:     }
                   13015:     my ($count,$codebasecount) = (0,0);
                   13016:     my $mm = new File::MMagic;
                   13017:     my $mime_type = $mm->checktype_contents($content);
                   13018:     if ($mime_type eq 'text/html') {
                   13019:         my $parse_result = 
                   13020:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13021:                                                     \%codebase,\$content);
                   13022:         if ($parse_result eq 'ok') {
                   13023:             foreach my $i (@changes) {
                   13024:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13025:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13026:                 if ($allfiles{$ref}) {
                   13027:                     my $newname =  $orig;
                   13028:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13029:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13030:                     if ($attrib_regexp =~ /:/) {
                   13031:                         $attrib_regexp =~ s/\:/|/g;
                   13032:                     }
                   13033:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13034:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13035:                         $count += $numchg;
1.1075.2.35  raeburn  13036:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  13037:                         delete($allfiles{$ref});
1.987     raeburn  13038:                     }
                   13039:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13040:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13041:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13042:                         $codebasecount ++;
                   13043:                     }
                   13044:                 }
                   13045:             }
1.1075.2.35  raeburn  13046:             my $skiprewrites;
1.987     raeburn  13047:             if ($count || $codebasecount) {
                   13048:                 my $saveresult;
1.1071    raeburn  13049:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  13050:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13051:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13052:                     if ($url eq $container) {
                   13053:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13054:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13055:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13056:                                             $fname.'</span>').'</p>';
1.987     raeburn  13057:                     } else {
                   13058:                          $output = '<p class="LC_error">'.
                   13059:                                    &mt('Error: update failed for: [_1].',
                   13060:                                    '<span class="LC_filename">'.
                   13061:                                    $container.'</span>').'</p>';
                   13062:                     }
1.1075.2.35  raeburn  13063:                     if ($context eq 'syllabus') {
                   13064:                         unless ($saveresult eq 'ok') {
                   13065:                             $skiprewrites = 1;
                   13066:                         }
                   13067:                     }
1.987     raeburn  13068:                 } else {
1.1075.2.128  raeburn  13069:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13070:                         print $fh $content;
                   13071:                         close($fh);
                   13072:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13073:                                   $count,'<span class="LC_filename">'.
                   13074:                                   $container.'</span>').'</p>';
1.661     raeburn  13075:                     } else {
1.987     raeburn  13076:                          $output = '<p class="LC_error">'.
                   13077:                                    &mt('Error: could not update [_1].',
                   13078:                                    '<span class="LC_filename">'.
                   13079:                                    $container.'</span>').'</p>';
1.661     raeburn  13080:                     }
                   13081:                 }
                   13082:             }
1.1075.2.35  raeburn  13083:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13084:                 my ($actionurl,$state);
                   13085:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13086:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13087:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13088:                                               \%codebase,
                   13089:                                               {'context' => 'rewrites',
                   13090:                                                'ignore_remote_references' => 1,});
                   13091:                 if (ref($mapping) eq 'HASH') {
                   13092:                     my $rewrites = 0;
                   13093:                     foreach my $key (keys(%{$mapping})) {
                   13094:                         next if ($key =~ m{^https?://});
                   13095:                         my $ref = $mapping->{$key};
                   13096:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13097:                         my $attrib;
                   13098:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13099:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13100:                         }
                   13101:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13102:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13103:                             $rewrites += $numchg;
                   13104:                         }
                   13105:                     }
                   13106:                     if ($rewrites) {
                   13107:                         my $saveresult;
                   13108:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13109:                         if ($url eq $container) {
                   13110:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13111:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13112:                                             $count,'<span class="LC_filename">'.
                   13113:                                             $fname.'</span>').'</p>';
                   13114:                         } else {
                   13115:                             $output .= '<p class="LC_error">'.
                   13116:                                        &mt('Error: could not update links in [_1].',
                   13117:                                        '<span class="LC_filename">'.
                   13118:                                        $container.'</span>').'</p>';
                   13119: 
                   13120:                         }
                   13121:                     }
                   13122:                 }
                   13123:             }
1.987     raeburn  13124:         } else {
                   13125:             &logthis('Failed to parse '.$container.
                   13126:                      ' to modify references: '.$parse_result);
1.661     raeburn  13127:         }
                   13128:     }
1.1071    raeburn  13129:     if (wantarray) {
                   13130:         return ($output,$count,$codebasecount);
                   13131:     } else {
                   13132:         return $output;
                   13133:     }
1.661     raeburn  13134: }
                   13135: 
                   13136: sub check_for_existing {
                   13137:     my ($path,$fname,$element) = @_;
                   13138:     my ($state,$msg);
                   13139:     if (-d $path.'/'.$fname) {
                   13140:         $state = 'exists';
                   13141:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13142:     } elsif (-e $path.'/'.$fname) {
                   13143:         $state = 'exists';
                   13144:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13145:     }
                   13146:     if ($state eq 'exists') {
                   13147:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13148:     }
                   13149:     return ($state,$msg);
                   13150: }
                   13151: 
                   13152: sub check_for_upload {
                   13153:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13154:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13155:     my $filesize = length($env{'form.'.$element});
                   13156:     if (!$filesize) {
                   13157:         my $msg = '<span class="LC_error">'.
                   13158:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13159:                       '<span class="LC_filename">'.$fname.'</span>',
                   13160:                       $filesize).'<br />'.
1.1007    raeburn  13161:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13162:                   '</span>';
                   13163:         return ('zero_bytes',$msg);
                   13164:     }
                   13165:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13166:     my $getpropath = 1;
1.1021    raeburn  13167:     my ($dirlistref,$listerror) =
                   13168:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13169:     my $found_file = 0;
                   13170:     my $locked_file = 0;
1.991     raeburn  13171:     my @lockers;
                   13172:     my $navmap;
                   13173:     if ($env{'request.course.id'}) {
                   13174:         $navmap = Apache::lonnavmaps::navmap->new();
                   13175:     }
1.1021    raeburn  13176:     if (ref($dirlistref) eq 'ARRAY') {
                   13177:         foreach my $line (@{$dirlistref}) {
                   13178:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13179:             if ($file_name eq $fname){
                   13180:                 $file_name = $path.$file_name;
                   13181:                 if ($group ne '') {
                   13182:                     $file_name = $group.$file_name;
                   13183:                 }
                   13184:                 $found_file = 1;
                   13185:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13186:                     foreach my $lock (@lockers) {
                   13187:                         if (ref($lock) eq 'ARRAY') {
                   13188:                             my ($symb,$crsid) = @{$lock};
                   13189:                             if ($crsid eq $env{'request.course.id'}) {
                   13190:                                 if (ref($navmap)) {
                   13191:                                     my $res = $navmap->getBySymb($symb);
                   13192:                                     foreach my $part (@{$res->parts()}) { 
                   13193:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13194:                                         unless (($slot_status == $res->RESERVED) ||
                   13195:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13196:                                             $locked_file = 1;
                   13197:                                         }
1.991     raeburn  13198:                                     }
1.1021    raeburn  13199:                                 } else {
                   13200:                                     $locked_file = 1;
1.991     raeburn  13201:                                 }
                   13202:                             } else {
                   13203:                                 $locked_file = 1;
                   13204:                             }
                   13205:                         }
1.1021    raeburn  13206:                    }
                   13207:                 } else {
                   13208:                     my @info = split(/\&/,$rest);
                   13209:                     my $currsize = $info[6]/1000;
                   13210:                     if ($currsize < $filesize) {
                   13211:                         my $extra = $filesize - $currsize;
                   13212:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  13213:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13214:                                       &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  13215:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13216:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13217:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13218:                             return ('will_exceed_quota',$msg);
                   13219:                         }
1.984     raeburn  13220:                     }
                   13221:                 }
1.661     raeburn  13222:             }
                   13223:         }
                   13224:     }
                   13225:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  13226:         my $msg = '<p class="LC_warning">'.
                   13227:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   13228:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13229:         return ('will_exceed_quota',$msg);
                   13230:     } elsif ($found_file) {
                   13231:         if ($locked_file) {
1.1075.2.69  raeburn  13232:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13233:             $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  13234:             $msg .= '</p>';
1.661     raeburn  13235:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13236:             return ('file_locked',$msg);
                   13237:         } else {
1.1075.2.69  raeburn  13238:             my $msg = '<p class="LC_error">';
1.984     raeburn  13239:             $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  13240:             $msg .= '</p>';
1.984     raeburn  13241:             return ('existingfile',$msg);
1.661     raeburn  13242:         }
                   13243:     }
                   13244: }
                   13245: 
1.987     raeburn  13246: sub check_for_traversal {
                   13247:     my ($path,$url,$toplevel) = @_;
                   13248:     my @parts=split(/\//,$path);
                   13249:     my $cleanpath;
                   13250:     my $fullpath = $url;
                   13251:     for (my $i=0;$i<@parts;$i++) {
                   13252:         next if ($parts[$i] eq '.');
                   13253:         if ($parts[$i] eq '..') {
                   13254:             $fullpath =~ s{([^/]+/)$}{};
                   13255:         } else {
                   13256:             $fullpath .= $parts[$i].'/';
                   13257:         }
                   13258:     }
                   13259:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13260:         $cleanpath = $1;
                   13261:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13262:         my $curr_toprel = $1;
                   13263:         my @parts = split(/\//,$curr_toprel);
                   13264:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13265:         my @urlparts = split(/\//,$url_toprel);
                   13266:         my $doubledots;
                   13267:         my $startdiff = -1;
                   13268:         for (my $i=0; $i<@urlparts; $i++) {
                   13269:             if ($startdiff == -1) {
                   13270:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13271:                     $startdiff = $i;
                   13272:                     $doubledots .= '../';
                   13273:                 }
                   13274:             } else {
                   13275:                 $doubledots .= '../';
                   13276:             }
                   13277:         }
                   13278:         if ($startdiff > -1) {
                   13279:             $cleanpath = $doubledots;
                   13280:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13281:                 $cleanpath .= $parts[$i].'/';
                   13282:             }
                   13283:         }
                   13284:     }
                   13285:     $cleanpath =~ s{(/)$}{};
                   13286:     return $cleanpath;
                   13287: }
1.31      albertel 13288: 
1.1053    raeburn  13289: sub is_archive_file {
                   13290:     my ($mimetype) = @_;
                   13291:     if (($mimetype eq 'application/octet-stream') ||
                   13292:         ($mimetype eq 'application/x-stuffit') ||
                   13293:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13294:         return 1;
                   13295:     }
                   13296:     return;
                   13297: }
                   13298: 
                   13299: sub decompress_form {
1.1065    raeburn  13300:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13301:     my %lt = &Apache::lonlocal::texthash (
                   13302:         this => 'This file is an archive file.',
1.1067    raeburn  13303:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13304:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13305:         youm => 'You may wish to extract its contents.',
                   13306:         extr => 'Extract contents',
1.1067    raeburn  13307:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13308:         proa => 'Process automatically?',
1.1053    raeburn  13309:         yes  => 'Yes',
                   13310:         no   => 'No',
1.1067    raeburn  13311:         fold => 'Title for folder containing movie',
                   13312:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13313:     );
1.1065    raeburn  13314:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13315:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13316:     my $info = &list_archive_contents($fileloc,\@paths);
                   13317:     if (@paths) {
                   13318:         foreach my $path (@paths) {
                   13319:             $path =~ s{^/}{};
1.1067    raeburn  13320:             if ($path =~ m{^([^/]+)/$}) {
                   13321:                 $topdir = $1;
                   13322:             }
1.1065    raeburn  13323:             if ($path =~ m{^([^/]+)/}) {
                   13324:                 $toplevel{$1} = $path;
                   13325:             } else {
                   13326:                 $toplevel{$path} = $path;
                   13327:             }
                   13328:         }
                   13329:     }
1.1067    raeburn  13330:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  13331:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13332:                         "$topdir/media/",
                   13333:                         "$topdir/media/$topdir.mp4",
                   13334:                         "$topdir/media/FirstFrame.png",
                   13335:                         "$topdir/media/player.swf",
                   13336:                         "$topdir/media/swfobject.js",
                   13337:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  13338:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  13339:                          "$topdir/$topdir.mp4",
                   13340:                          "$topdir/$topdir\_config.xml",
                   13341:                          "$topdir/$topdir\_controller.swf",
                   13342:                          "$topdir/$topdir\_embed.css",
                   13343:                          "$topdir/$topdir\_First_Frame.png",
                   13344:                          "$topdir/$topdir\_player.html",
                   13345:                          "$topdir/$topdir\_Thumbnails.png",
                   13346:                          "$topdir/playerProductInstall.swf",
                   13347:                          "$topdir/scripts/",
                   13348:                          "$topdir/scripts/config_xml.js",
                   13349:                          "$topdir/scripts/handlebars.js",
                   13350:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13351:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13352:                          "$topdir/scripts/modernizr.js",
                   13353:                          "$topdir/scripts/player-min.js",
                   13354:                          "$topdir/scripts/swfobject.js",
                   13355:                          "$topdir/skins/",
                   13356:                          "$topdir/skins/configuration_express.xml",
                   13357:                          "$topdir/skins/express_show/",
                   13358:                          "$topdir/skins/express_show/player-min.css",
                   13359:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  13360:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13361:                          "$topdir/$topdir.mp4",
                   13362:                          "$topdir/$topdir\_config.xml",
                   13363:                          "$topdir/$topdir\_controller.swf",
                   13364:                          "$topdir/$topdir\_embed.css",
                   13365:                          "$topdir/$topdir\_First_Frame.png",
                   13366:                          "$topdir/$topdir\_player.html",
                   13367:                          "$topdir/$topdir\_Thumbnails.png",
                   13368:                          "$topdir/playerProductInstall.swf",
                   13369:                          "$topdir/scripts/",
                   13370:                          "$topdir/scripts/config_xml.js",
                   13371:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13372:                          "$topdir/skins/",
                   13373:                          "$topdir/skins/configuration_express.xml",
                   13374:                          "$topdir/skins/express_show/",
                   13375:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13376:                          "$topdir/skins/express_show/spritesheet.png",
                   13377:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  13378:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13379:         if (@diffs == 0) {
1.1075.2.59  raeburn  13380:             $is_camtasia = 6;
                   13381:         } else {
1.1075.2.81  raeburn  13382:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  13383:             if (@diffs == 0) {
                   13384:                 $is_camtasia = 8;
1.1075.2.81  raeburn  13385:             } else {
                   13386:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13387:                 if (@diffs == 0) {
                   13388:                     $is_camtasia = 8;
                   13389:                 }
1.1075.2.59  raeburn  13390:             }
1.1067    raeburn  13391:         }
                   13392:     }
                   13393:     my $output;
                   13394:     if ($is_camtasia) {
                   13395:         $output = <<"ENDCAM";
                   13396: <script type="text/javascript" language="Javascript">
                   13397: // <![CDATA[
                   13398: 
                   13399: function camtasiaToggle() {
                   13400:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13401:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  13402:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13403:                 document.getElementById('camtasia_titles').style.display='block';
                   13404:             } else {
                   13405:                 document.getElementById('camtasia_titles').style.display='none';
                   13406:             }
                   13407:         }
                   13408:     }
                   13409:     return;
                   13410: }
                   13411: 
                   13412: // ]]>
                   13413: </script>
                   13414: <p>$lt{'camt'}</p>
                   13415: ENDCAM
1.1065    raeburn  13416:     } else {
1.1067    raeburn  13417:         $output = '<p>'.$lt{'this'};
                   13418:         if ($info eq '') {
                   13419:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13420:         } else {
                   13421:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13422:                        '<div><pre>'.$info.'</pre></div>';
                   13423:         }
1.1065    raeburn  13424:     }
1.1067    raeburn  13425:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13426:     my $duplicates;
                   13427:     my $num = 0;
                   13428:     if (ref($dirlist) eq 'ARRAY') {
                   13429:         foreach my $item (@{$dirlist}) {
                   13430:             if (ref($item) eq 'ARRAY') {
                   13431:                 if (exists($toplevel{$item->[0]})) {
                   13432:                     $duplicates .= 
                   13433:                         &start_data_table_row().
                   13434:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13435:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13436:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13437:                         'value="1" />'.&mt('Yes').'</label>'.
                   13438:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13439:                         '<td>'.$item->[0].'</td>';
                   13440:                     if ($item->[2]) {
                   13441:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13442:                     } else {
                   13443:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13444:                     }
                   13445:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13446:                                    '<td>'.
                   13447:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13448:                                    '</td>'.
                   13449:                                    &end_data_table_row();
                   13450:                     $num ++;
                   13451:                 }
                   13452:             }
                   13453:         }
                   13454:     }
                   13455:     my $itemcount;
                   13456:     if (@paths > 0) {
                   13457:         $itemcount = scalar(@paths);
                   13458:     } else {
                   13459:         $itemcount = 1;
                   13460:     }
1.1067    raeburn  13461:     if ($is_camtasia) {
                   13462:         $output .= $lt{'auto'}.'<br />'.
                   13463:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  13464:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13465:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13466:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13467:                    $lt{'no'}.'</label></span><br />'.
                   13468:                    '<div id="camtasia_titles" style="display:block">'.
                   13469:                    &Apache::lonhtmlcommon::start_pick_box().
                   13470:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13471:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13472:                    &Apache::lonhtmlcommon::row_closure().
                   13473:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13474:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13475:                    &Apache::lonhtmlcommon::row_closure(1).
                   13476:                    &Apache::lonhtmlcommon::end_pick_box().
                   13477:                    '</div>';
                   13478:     }
1.1065    raeburn  13479:     $output .= 
                   13480:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13481:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13482:         "\n";
1.1065    raeburn  13483:     if ($duplicates ne '') {
                   13484:         $output .= '<p><span class="LC_warning">'.
                   13485:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13486:                    &start_data_table().
                   13487:                    &start_data_table_header_row().
                   13488:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13489:                    '<th>'.&mt('Name').'</th>'.
                   13490:                    '<th>'.&mt('Type').'</th>'.
                   13491:                    '<th>'.&mt('Size').'</th>'.
                   13492:                    '<th>'.&mt('Last modified').'</th>'.
                   13493:                    &end_data_table_header_row().
                   13494:                    $duplicates.
                   13495:                    &end_data_table().
                   13496:                    '</p>';
                   13497:     }
1.1067    raeburn  13498:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13499:     if (ref($hiddenelements) eq 'HASH') {
                   13500:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13501:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13502:         }
                   13503:     }
                   13504:     $output .= <<"END";
1.1067    raeburn  13505: <br />
1.1053    raeburn  13506: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13507: </form>
                   13508: $noextract
                   13509: END
                   13510:     return $output;
                   13511: }
                   13512: 
1.1065    raeburn  13513: sub decompression_utility {
                   13514:     my ($program) = @_;
                   13515:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13516:     my $location;
                   13517:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13518:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13519:                          '/usr/sbin/') {
                   13520:             if (-x $dir.$program) {
                   13521:                 $location = $dir.$program;
                   13522:                 last;
                   13523:             }
                   13524:         }
                   13525:     }
                   13526:     return $location;
                   13527: }
                   13528: 
                   13529: sub list_archive_contents {
                   13530:     my ($file,$pathsref) = @_;
                   13531:     my (@cmd,$output);
                   13532:     my $needsregexp;
                   13533:     if ($file =~ /\.zip$/) {
                   13534:         @cmd = (&decompression_utility('unzip'),"-l");
                   13535:         $needsregexp = 1;
                   13536:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13537:              ($file =~ /\.tgz$/)) {
                   13538:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13539:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13540:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13541:     } elsif ($file =~ m|\.tar$|) {
                   13542:         @cmd = (&decompression_utility('tar'),"-tf");
                   13543:     }
                   13544:     if (@cmd) {
                   13545:         undef($!);
                   13546:         undef($@);
                   13547:         if (open(my $fh,"-|", @cmd, $file)) {
                   13548:             while (my $line = <$fh>) {
                   13549:                 $output .= $line;
                   13550:                 chomp($line);
                   13551:                 my $item;
                   13552:                 if ($needsregexp) {
                   13553:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13554:                 } else {
                   13555:                     $item = $line;
                   13556:                 }
                   13557:                 if ($item ne '') {
                   13558:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13559:                         push(@{$pathsref},$item);
                   13560:                     } 
                   13561:                 }
                   13562:             }
                   13563:             close($fh);
                   13564:         }
                   13565:     }
                   13566:     return $output;
                   13567: }
                   13568: 
1.1053    raeburn  13569: sub decompress_uploaded_file {
                   13570:     my ($file,$dir) = @_;
                   13571:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13572:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13573:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13574:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13575:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13576:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13577:     my $decompressed = $env{'cgi.decompressed'};
                   13578:     &Apache::lonnet::delenv('cgi.file');
                   13579:     &Apache::lonnet::delenv('cgi.dir');
                   13580:     &Apache::lonnet::delenv('cgi.decompressed');
                   13581:     return ($decompressed,$result);
                   13582: }
                   13583: 
1.1055    raeburn  13584: sub process_decompression {
                   13585:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13586:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13587:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13588:                &mt('Unexpected file path.').'</p>'."\n";
                   13589:     }
                   13590:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13591:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13592:                &mt('Unexpected course context.').'</p>'."\n";
                   13593:     }
                   13594:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13595:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13596:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13597:     }
1.1055    raeburn  13598:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13599:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13600:         $error = &mt('Filename not a supported archive file type.').
                   13601:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13602:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13603:     } else {
                   13604:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13605:         if ($docuhome eq 'no_host') {
                   13606:             $error = &mt('Could not determine home server for course.');
                   13607:         } else {
                   13608:             my @ids=&Apache::lonnet::current_machine_ids();
                   13609:             my $currdir = "$dir_root/$destination";
                   13610:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13611:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13612:                        "$dir_root/$destination";
                   13613:             } else {
                   13614:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13615:                        "$dir_root/$docudom/$docuname/$destination";
                   13616:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13617:                     $error = &mt('Archive file not found.');
                   13618:                 }
                   13619:             }
1.1065    raeburn  13620:             my (@to_overwrite,@to_skip);
                   13621:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13622:                 my $total = $env{'form.archive_overwrite_total'};
                   13623:                 for (my $i=0; $i<$total; $i++) {
                   13624:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13625:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13626:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13627:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13628:                     }
                   13629:                 }
                   13630:             }
                   13631:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13632:             my $numoverwrite = scalar(@to_overwrite);
                   13633:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13634:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13635:             } elsif ($dir eq '') {
1.1055    raeburn  13636:                 $error = &mt('Directory containing archive file unavailable.');
                   13637:             } elsif (!$error) {
1.1065    raeburn  13638:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13639:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13640:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13641:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13642:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13643:                         ($decompressed,$display) =
                   13644:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13645:                         foreach my $item (@to_skip) {
                   13646:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13647:                                 if (-f "$dir/$tempdir/$item") {
                   13648:                                     unlink("$dir/$tempdir/$item");
                   13649:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13650:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13651:                                 }
                   13652:                             }
                   13653:                         }
                   13654:                         foreach my $item (@to_overwrite) {
                   13655:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13656:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13657:                                     if (-f "$dir/$item") {
                   13658:                                         unlink("$dir/$item");
                   13659:                                     } elsif (-d "$dir/$item") {
                   13660:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13661:                                     }
                   13662:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13663:                                 }
1.1065    raeburn  13664:                             }
                   13665:                         }
1.1075.2.128  raeburn  13666:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13667:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13668:                         }
1.1065    raeburn  13669:                     }
                   13670:                 } else {
                   13671:                     ($decompressed,$display) = 
                   13672:                         &decompress_uploaded_file($file,$dir);
                   13673:                 }
1.1055    raeburn  13674:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13675:                     $output = '<p class="LC_info">'.
                   13676:                               &mt('Files extracted successfully from archive.').
                   13677:                               '</p>'."\n";
1.1055    raeburn  13678:                     my ($warning,$result,@contents);
                   13679:                     my ($newdirlistref,$newlisterror) =
                   13680:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13681:                                                  $docuname,1);
                   13682:                     my (%is_dir,%changes,@newitems);
                   13683:                     my $dirptr = 16384;
1.1065    raeburn  13684:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13685:                         foreach my $dir_line (@{$newdirlistref}) {
                   13686:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13687:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13688:                                 push(@newitems,$item);
                   13689:                                 if ($dirptr&$testdir) {
                   13690:                                     $is_dir{$item} = 1;
                   13691:                                 }
                   13692:                                 $changes{$item} = 1;
                   13693:                             }
                   13694:                         }
                   13695:                     }
                   13696:                     if (keys(%changes) > 0) {
                   13697:                         foreach my $item (sort(@newitems)) {
                   13698:                             if ($changes{$item}) {
                   13699:                                 push(@contents,$item);
                   13700:                             }
                   13701:                         }
                   13702:                     }
                   13703:                     if (@contents > 0) {
1.1067    raeburn  13704:                         my $wantform;
                   13705:                         unless ($env{'form.autoextract_camtasia'}) {
                   13706:                             $wantform = 1;
                   13707:                         }
1.1056    raeburn  13708:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13709:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13710:                                                                 $currdir,\%is_dir,
                   13711:                                                                 \%children,\%parent,
1.1056    raeburn  13712:                                                                 \@contents,\%dirorder,
                   13713:                                                                 \%titles,$wantform);
1.1055    raeburn  13714:                         if ($datatable ne '') {
                   13715:                             $output .= &archive_options_form('decompressed',$datatable,
                   13716:                                                              $count,$hiddenelem);
1.1065    raeburn  13717:                             my $startcount = 6;
1.1055    raeburn  13718:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13719:                                                            \%titles,\%children);
1.1055    raeburn  13720:                         }
1.1067    raeburn  13721:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13722:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13723:                             my %displayed;
                   13724:                             my $total = 1;
                   13725:                             $env{'form.archive_directory'} = [];
                   13726:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13727:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13728:                                 $path =~ s{/$}{};
                   13729:                                 my $item;
                   13730:                                 if ($path ne '') {
                   13731:                                     $item = "$path/$titles{$i}";
                   13732:                                 } else {
                   13733:                                     $item = $titles{$i};
                   13734:                                 }
                   13735:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13736:                                 if ($item eq $contents[0]) {
                   13737:                                     push(@{$env{'form.archive_directory'}},$i);
                   13738:                                     $env{'form.archive_'.$i} = 'display';
                   13739:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13740:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13741:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13742:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13743:                                     $env{'form.archive_'.$i} = 'display';
                   13744:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13745:                                     $displayed{'web'} = $i;
                   13746:                                 } else {
1.1075.2.59  raeburn  13747:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13748:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13749:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13750:                                         push(@{$env{'form.archive_directory'}},$i);
                   13751:                                     }
                   13752:                                     $env{'form.archive_'.$i} = 'dependency';
                   13753:                                 }
                   13754:                                 $total ++;
                   13755:                             }
                   13756:                             for (my $i=1; $i<$total; $i++) {
                   13757:                                 next if ($i == $displayed{'web'});
                   13758:                                 next if ($i == $displayed{'folder'});
                   13759:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13760:                             }
                   13761:                             $env{'form.phase'} = 'decompress_cleanup';
                   13762:                             $env{'form.archivedelete'} = 1;
                   13763:                             $env{'form.archive_count'} = $total-1;
                   13764:                             $output .=
                   13765:                                 &process_extracted_files('coursedocs',$docudom,
                   13766:                                                          $docuname,$destination,
                   13767:                                                          $dir_root,$hiddenelem);
                   13768:                         }
1.1055    raeburn  13769:                     } else {
                   13770:                         $warning = &mt('No new items extracted from archive file.');
                   13771:                     }
                   13772:                 } else {
                   13773:                     $output = $display;
                   13774:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13775:                 }
                   13776:             }
                   13777:         }
                   13778:     }
                   13779:     if ($error) {
                   13780:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13781:                    $error.'</p>'."\n";
                   13782:     }
                   13783:     if ($warning) {
                   13784:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13785:     }
                   13786:     return $output;
                   13787: }
                   13788: 
                   13789: sub get_extracted {
1.1056    raeburn  13790:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13791:         $titles,$wantform) = @_;
1.1055    raeburn  13792:     my $count = 0;
                   13793:     my $depth = 0;
                   13794:     my $datatable;
1.1056    raeburn  13795:     my @hierarchy;
1.1055    raeburn  13796:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13797:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13798:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13799:     foreach my $item (@{$contents}) {
                   13800:         $count ++;
1.1056    raeburn  13801:         @{$dirorder->{$count}} = @hierarchy;
                   13802:         $titles->{$count} = $item;
1.1055    raeburn  13803:         &archive_hierarchy($depth,$count,$parent,$children);
                   13804:         if ($wantform) {
                   13805:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13806:                                        $currdir,$depth,$count);
                   13807:         }
                   13808:         if ($is_dir->{$item}) {
                   13809:             $depth ++;
1.1056    raeburn  13810:             push(@hierarchy,$count);
                   13811:             $parent->{$depth} = $count;
1.1055    raeburn  13812:             $datatable .=
                   13813:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13814:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13815:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13816:             $depth --;
1.1056    raeburn  13817:             pop(@hierarchy);
1.1055    raeburn  13818:         }
                   13819:     }
                   13820:     return ($count,$datatable);
                   13821: }
                   13822: 
                   13823: sub recurse_extracted_archive {
1.1056    raeburn  13824:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13825:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13826:     my $result='';
1.1056    raeburn  13827:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13828:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13829:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13830:         return $result;
                   13831:     }
                   13832:     my $dirptr = 16384;
                   13833:     my ($newdirlistref,$newlisterror) =
                   13834:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13835:     if (ref($newdirlistref) eq 'ARRAY') {
                   13836:         foreach my $dir_line (@{$newdirlistref}) {
                   13837:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13838:             unless ($item =~ /^\.+$/) {
                   13839:                 $$count ++;
1.1056    raeburn  13840:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13841:                 $titles->{$$count} = $item;
1.1055    raeburn  13842:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13843: 
1.1055    raeburn  13844:                 my $is_dir;
                   13845:                 if ($dirptr&$testdir) {
                   13846:                     $is_dir = 1;
                   13847:                 }
                   13848:                 if ($wantform) {
                   13849:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13850:                 }
                   13851:                 if ($is_dir) {
                   13852:                     $$depth ++;
1.1056    raeburn  13853:                     push(@{$hierarchy},$$count);
                   13854:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13855:                     $result .=
                   13856:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13857:                                                    $docuname,$depth,$count,
1.1056    raeburn  13858:                                                    $hierarchy,$dirorder,$children,
                   13859:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13860:                     $$depth --;
1.1056    raeburn  13861:                     pop(@{$hierarchy});
1.1055    raeburn  13862:                 }
                   13863:             }
                   13864:         }
                   13865:     }
                   13866:     return $result;
                   13867: }
                   13868: 
                   13869: sub archive_hierarchy {
                   13870:     my ($depth,$count,$parent,$children) =@_;
                   13871:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13872:         if (exists($parent->{$depth})) {
                   13873:              $children->{$parent->{$depth}} .= $count.':';
                   13874:         }
                   13875:     }
                   13876:     return;
                   13877: }
                   13878: 
                   13879: sub archive_row {
                   13880:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13881:     my ($name) = ($item =~ m{([^/]+)$});
                   13882:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13883:                                        'display'    => 'Add as file',
1.1055    raeburn  13884:                                        'dependency' => 'Include as dependency',
                   13885:                                        'discard'    => 'Discard',
                   13886:                                       );
                   13887:     if ($is_dir) {
1.1059    raeburn  13888:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13889:     }
1.1056    raeburn  13890:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13891:     my $offset = 0;
1.1055    raeburn  13892:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13893:         $offset ++;
1.1065    raeburn  13894:         if ($action ne 'display') {
                   13895:             $offset ++;
                   13896:         }  
1.1055    raeburn  13897:         $output .= '<td><span class="LC_nobreak">'.
                   13898:                    '<label><input type="radio" name="archive_'.$count.
                   13899:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13900:         my $text = $choices{$action};
                   13901:         if ($is_dir) {
                   13902:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13903:             if ($action eq 'display') {
1.1059    raeburn  13904:                 $text = &mt('Add as folder');
1.1055    raeburn  13905:             }
1.1056    raeburn  13906:         } else {
                   13907:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13908: 
                   13909:         }
                   13910:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13911:         if ($action eq 'dependency') {
                   13912:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13913:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13914:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13915:                        '<option value=""></option>'."\n".
                   13916:                        '</select>'."\n".
                   13917:                        '</div>';
1.1059    raeburn  13918:         } elsif ($action eq 'display') {
                   13919:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13920:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13921:                        '</div>';
1.1055    raeburn  13922:         }
1.1056    raeburn  13923:         $output .= '</td>';
1.1055    raeburn  13924:     }
                   13925:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13926:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13927:     for (my $i=0; $i<$depth; $i++) {
                   13928:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13929:     }
                   13930:     if ($is_dir) {
                   13931:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13932:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13933:     } else {
                   13934:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13935:     }
                   13936:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13937:                &end_data_table_row();
                   13938:     return $output;
                   13939: }
                   13940: 
                   13941: sub archive_options_form {
1.1065    raeburn  13942:     my ($form,$display,$count,$hiddenelem) = @_;
                   13943:     my %lt = &Apache::lonlocal::texthash(
                   13944:                perm => 'Permanently remove archive file?',
                   13945:                hows => 'How should each extracted item be incorporated in the course?',
                   13946:                cont => 'Content actions for all',
                   13947:                addf => 'Add as folder/file',
                   13948:                incd => 'Include as dependency for a displayed file',
                   13949:                disc => 'Discard',
                   13950:                no   => 'No',
                   13951:                yes  => 'Yes',
                   13952:                save => 'Save',
                   13953:     );
                   13954:     my $output = <<"END";
                   13955: <form name="$form" method="post" action="">
                   13956: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13957: <label>
                   13958:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13959: </label>
                   13960: &nbsp;
                   13961: <label>
                   13962:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13963: </span>
                   13964: </p>
                   13965: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13966: <br />$lt{'hows'}
                   13967: <div class="LC_columnSection">
                   13968:   <fieldset>
                   13969:     <legend>$lt{'cont'}</legend>
                   13970:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13971:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13972:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13973:   </fieldset>
                   13974: </div>
                   13975: END
                   13976:     return $output.
1.1055    raeburn  13977:            &start_data_table()."\n".
1.1065    raeburn  13978:            $display."\n".
1.1055    raeburn  13979:            &end_data_table()."\n".
                   13980:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13981:            $hiddenelem.
1.1065    raeburn  13982:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13983:            '</form>';
                   13984: }
                   13985: 
                   13986: sub archive_javascript {
1.1056    raeburn  13987:     my ($startcount,$numitems,$titles,$children) = @_;
                   13988:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13989:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13990:     my $scripttag = <<START;
                   13991: <script type="text/javascript">
                   13992: // <![CDATA[
                   13993: 
                   13994: function checkAll(form,prefix) {
                   13995:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13996:     for (var i=0; i < form.elements.length; i++) {
                   13997:         var id = form.elements[i].id;
                   13998:         if ((id != '') && (id != undefined)) {
                   13999:             if (idstr.test(id)) {
                   14000:                 if (form.elements[i].type == 'radio') {
                   14001:                     form.elements[i].checked = true;
1.1056    raeburn  14002:                     var nostart = i-$startcount;
1.1059    raeburn  14003:                     var offset = nostart%7;
                   14004:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14005:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14006:                 }
                   14007:             }
                   14008:         }
                   14009:     }
                   14010: }
                   14011: 
                   14012: function propagateCheck(form,count) {
                   14013:     if (count > 0) {
1.1059    raeburn  14014:         var startelement = $startcount + ((count-1) * 7);
                   14015:         for (var j=1; j<6; j++) {
                   14016:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14017:                 var item = startelement + j; 
                   14018:                 if (form.elements[item].type == 'radio') {
                   14019:                     if (form.elements[item].checked) {
                   14020:                         containerCheck(form,count,j);
                   14021:                         break;
                   14022:                     }
1.1055    raeburn  14023:                 }
                   14024:             }
                   14025:         }
                   14026:     }
                   14027: }
                   14028: 
                   14029: numitems = $numitems
1.1056    raeburn  14030: var titles = new Array(numitems);
                   14031: var parents = new Array(numitems);
1.1055    raeburn  14032: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14033:     parents[i] = new Array;
1.1055    raeburn  14034: }
1.1059    raeburn  14035: var maintitle = '$maintitle';
1.1055    raeburn  14036: 
                   14037: START
                   14038: 
1.1056    raeburn  14039:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14040:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14041:         for (my $i=0; $i<@contents; $i ++) {
                   14042:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14043:         }
                   14044:     }
                   14045: 
1.1056    raeburn  14046:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14047:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14048:     }
                   14049: 
1.1055    raeburn  14050:     $scripttag .= <<END;
                   14051: 
                   14052: function containerCheck(form,count,offset) {
                   14053:     if (count > 0) {
1.1056    raeburn  14054:         dependencyCheck(form,count,offset);
1.1059    raeburn  14055:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14056:         form.elements[item].checked = true;
                   14057:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14058:             if (parents[count].length > 0) {
                   14059:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14060:                     containerCheck(form,parents[count][j],offset);
                   14061:                 }
                   14062:             }
                   14063:         }
                   14064:     }
                   14065: }
                   14066: 
                   14067: function dependencyCheck(form,count,offset) {
                   14068:     if (count > 0) {
1.1059    raeburn  14069:         var chosen = (offset+$startcount)+7*(count-1);
                   14070:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14071:         var currtype = form.elements[depitem].type;
                   14072:         if (form.elements[chosen].value == 'dependency') {
                   14073:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14074:             form.elements[depitem].options.length = 0;
                   14075:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  14076:             for (var i=1; i<=numitems; i++) {
                   14077:                 if (i == count) {
                   14078:                     continue;
                   14079:                 }
1.1059    raeburn  14080:                 var startelement = $startcount + (i-1) * 7;
                   14081:                 for (var j=1; j<6; j++) {
                   14082:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14083:                         var item = startelement + j;
                   14084:                         if (form.elements[item].type == 'radio') {
                   14085:                             if (form.elements[item].checked) {
                   14086:                                 if (form.elements[item].value == 'display') {
                   14087:                                     var n = form.elements[depitem].options.length;
                   14088:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14089:                                 }
                   14090:                             }
                   14091:                         }
                   14092:                     }
                   14093:                 }
                   14094:             }
                   14095:         } else {
                   14096:             document.getElementById('arc_depon_'+count).style.display='none';
                   14097:             form.elements[depitem].options.length = 0;
                   14098:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14099:         }
1.1059    raeburn  14100:         titleCheck(form,count,offset);
1.1056    raeburn  14101:     }
                   14102: }
                   14103: 
                   14104: function propagateSelect(form,count,offset) {
                   14105:     if (count > 0) {
1.1065    raeburn  14106:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14107:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14108:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14109:             if (parents[count].length > 0) {
                   14110:                 for (var j=0; j<parents[count].length; j++) {
                   14111:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14112:                 }
                   14113:             }
                   14114:         }
                   14115:     }
                   14116: }
1.1056    raeburn  14117: 
                   14118: function containerSelect(form,count,offset,picked) {
                   14119:     if (count > 0) {
1.1065    raeburn  14120:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14121:         if (form.elements[item].type == 'radio') {
                   14122:             if (form.elements[item].value == 'dependency') {
                   14123:                 if (form.elements[item+1].type == 'select-one') {
                   14124:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14125:                         if (form.elements[item+1].options[i].value == picked) {
                   14126:                             form.elements[item+1].selectedIndex = i;
                   14127:                             break;
                   14128:                         }
                   14129:                     }
                   14130:                 }
                   14131:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14132:                     if (parents[count].length > 0) {
                   14133:                         for (var j=0; j<parents[count].length; j++) {
                   14134:                             containerSelect(form,parents[count][j],offset,picked);
                   14135:                         }
                   14136:                     }
                   14137:                 }
                   14138:             }
                   14139:         }
                   14140:     }
                   14141: }
                   14142: 
1.1059    raeburn  14143: function titleCheck(form,count,offset) {
                   14144:     if (count > 0) {
                   14145:         var chosen = (offset+$startcount)+7*(count-1);
                   14146:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14147:         var currtype = form.elements[depitem].type;
                   14148:         if (form.elements[chosen].value == 'display') {
                   14149:             document.getElementById('arc_title_'+count).style.display='block';
                   14150:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14151:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14152:             }
                   14153:         } else {
                   14154:             document.getElementById('arc_title_'+count).style.display='none';
                   14155:             if (currtype == 'text') { 
                   14156:                 document.getElementById('archive_title_'+count).value='';
                   14157:             }
                   14158:         }
                   14159:     }
                   14160:     return;
                   14161: }
                   14162: 
1.1055    raeburn  14163: // ]]>
                   14164: </script>
                   14165: END
                   14166:     return $scripttag;
                   14167: }
                   14168: 
                   14169: sub process_extracted_files {
1.1067    raeburn  14170:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14171:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  14172:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14173:     my @ids=&Apache::lonnet::current_machine_ids();
                   14174:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14175:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14176:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14177:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14178:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14179:         $pathtocheck = "$dir_root/$destination";
                   14180:         $dir = $dir_root;
                   14181:         $ishome = 1;
                   14182:     } else {
                   14183:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14184:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  14185:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14186:     }
                   14187:     my $currdir = "$dir_root/$destination";
                   14188:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14189:     if ($env{'form.folderpath'}) {
                   14190:         my @items = split('&',$env{'form.folderpath'});
                   14191:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  14192:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14193:             $containers{'0'}='page';
                   14194:         } else {
                   14195:             $containers{'0'}='sequence';
                   14196:         }
1.1055    raeburn  14197:     }
                   14198:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14199:     if ($numitems) {
                   14200:         for (my $i=1; $i<=$numitems; $i++) {
                   14201:             my $path = $env{'form.archive_content_'.$i};
                   14202:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14203:                 my $item = $1;
                   14204:                 $toplevelitems{$item} = $i;
                   14205:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14206:                     $is_dir{$item} = 1;
                   14207:                 }
                   14208:             }
                   14209:         }
                   14210:     }
1.1067    raeburn  14211:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14212:     if (keys(%toplevelitems) > 0) {
                   14213:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14214:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14215:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14216:     }
1.1066    raeburn  14217:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14218:     if ($numitems) {
                   14219:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  14220:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14221:             my $path = $env{'form.archive_content_'.$i};
                   14222:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14223:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14224:                     if ($prefix ne '' && $path ne '') {
                   14225:                         if (-e $prefix.$path) {
1.1066    raeburn  14226:                             if ((@archdirs > 0) && 
                   14227:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14228:                                 $todeletedir{$prefix.$path} = 1;
                   14229:                             } else {
                   14230:                                 $todelete{$prefix.$path} = 1;
                   14231:                             }
1.1055    raeburn  14232:                         }
                   14233:                     }
                   14234:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14235:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14236:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14237:                     $docstitle = $env{'form.archive_title_'.$i};
                   14238:                     if ($docstitle eq '') {
                   14239:                         $docstitle = $title;
                   14240:                     }
1.1055    raeburn  14241:                     $outer = 0;
1.1056    raeburn  14242:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14243:                         if (@{$dirorder{$i}} > 0) {
                   14244:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14245:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14246:                                     $outer = $item;
                   14247:                                     last;
                   14248:                                 }
                   14249:                             }
                   14250:                         }
                   14251:                     }
                   14252:                     my ($errtext,$fatal) = 
                   14253:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14254:                                                '/'.$folders{$outer}.'.'.
                   14255:                                                $containers{$outer});
                   14256:                     next if ($fatal);
                   14257:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14258:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14259:                             $mapinner{$i} = time;
1.1055    raeburn  14260:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14261:                             $containers{$i} = 'sequence';
                   14262:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14263:                                       $folders{$i}.'.'.$containers{$i};
                   14264:                             my $newidx = &LONCAPA::map::getresidx();
                   14265:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14266:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14267:                             push(@LONCAPA::map::order,$newidx);
                   14268:                             my ($outtext,$errtext) =
                   14269:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14270:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  14271:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14272:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14273:                             unless ($errtext) {
1.1075.2.128  raeburn  14274:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14275:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   14276:                                             '</li>'."\n";
1.1067    raeburn  14277:                             }
1.1055    raeburn  14278:                         }
                   14279:                     } else {
                   14280:                         if ($context eq 'coursedocs') {
                   14281:                             my $newidx=&LONCAPA::map::getresidx();
                   14282:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14283:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14284:                                       $title;
1.1075.2.161.  .13(raeb 14285:-23):                             if (($outer !~ /\D/) &&
                   14286:-23):                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14287:-23):                                 ($newidx !~ /\D/)) {
1.1075.2.128  raeburn  14288:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14289:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  14290:                                 }
1.1075.2.128  raeburn  14291:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14292:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14293:                                 }
                   14294:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14295:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14296:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14297:                                         unless ($ishome) {
                   14298:                                             my $fetch = "$newdest{$i}/$title";
                   14299:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14300:                                             $prompttofetch{$fetch} = 1;
                   14301:                                         }
                   14302:                                    }
                   14303:                                 }
                   14304:                                 $LONCAPA::map::resources[$newidx]=
                   14305:                                     $docstitle.':'.$url.':false:normal:res';
                   14306:                                 push(@LONCAPA::map::order, $newidx);
                   14307:                                 my ($outtext,$errtext)=
                   14308:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14309:                                                             $docuname.'/'.$folders{$outer}.
                   14310:                                                             '.'.$containers{$outer},1,1);
                   14311:                                 unless ($errtext) {
                   14312:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14313:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14314:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14315:                                                    '</li>'."\n";
                   14316:                                     }
1.1067    raeburn  14317:                                 }
1.1075.2.128  raeburn  14318:                             } else {
                   14319:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14320:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  14321:                             }
1.1055    raeburn  14322:                         }
                   14323:                     }
1.1075.2.11  raeburn  14324:                 }
                   14325:             } else {
1.1075.2.128  raeburn  14326:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14327:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  14328:             }
                   14329:         }
                   14330:         for (my $i=1; $i<=$numitems; $i++) {
                   14331:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14332:             my $path = $env{'form.archive_content_'.$i};
                   14333:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14334:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14335:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14336:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14337:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14338:                         my ($itemidx,$fullpath,$relpath);
                   14339:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14340:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14341:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  14342:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14343:                                     $itemidx = $j;
1.1056    raeburn  14344:                                 }
                   14345:                             }
1.1075.2.11  raeburn  14346:                         }
                   14347:                         if ($itemidx eq '') {
                   14348:                             $itemidx =  0;
                   14349:                         }
                   14350:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14351:                             if ($mapinner{$referrer{$i}}) {
                   14352:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14353:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14354:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14355:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14356:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14357:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14358:                                             if (!-e $fullpath) {
                   14359:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14360:                                             }
                   14361:                                         }
1.1075.2.11  raeburn  14362:                                     } else {
                   14363:                                         last;
1.1056    raeburn  14364:                                     }
1.1075.2.11  raeburn  14365:                                 }
                   14366:                             }
                   14367:                         } elsif ($newdest{$referrer{$i}}) {
                   14368:                             $fullpath = $newdest{$referrer{$i}};
                   14369:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14370:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14371:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14372:                                     last;
                   14373:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14374:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14375:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14376:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14377:                                         if (!-e $fullpath) {
                   14378:                                             mkdir($fullpath,0755);
1.1056    raeburn  14379:                                         }
                   14380:                                     }
1.1075.2.11  raeburn  14381:                                 } else {
                   14382:                                     last;
1.1056    raeburn  14383:                                 }
1.1075.2.11  raeburn  14384:                             }
                   14385:                         }
                   14386:                         if ($fullpath ne '') {
                   14387:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  14388:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14389:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14390:                                 }
1.1075.2.11  raeburn  14391:                             }
                   14392:                             if (-e "$fullpath/$title") {
                   14393:                                 my $showpath;
                   14394:                                 if ($relpath ne '') {
                   14395:                                     $showpath = "$relpath/$title";
                   14396:                                 } else {
                   14397:                                     $showpath = "/$title";
1.1056    raeburn  14398:                                 }
1.1075.2.128  raeburn  14399:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14400:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14401:                                            '</li>'."\n";
                   14402:                                 unless ($ishome) {
                   14403:                                     my $fetch = "$fullpath/$title";
                   14404:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   14405:                                     $prompttofetch{$fetch} = 1;
                   14406:                                 }
1.1055    raeburn  14407:                             }
                   14408:                         }
                   14409:                     }
1.1075.2.11  raeburn  14410:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14411:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  14412:                                     &HTML::Entities::encode($path,'<>&"'),
                   14413:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14414:                                 '<br />';
1.1055    raeburn  14415:                 }
                   14416:             } else {
1.1075.2.128  raeburn  14417:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14418:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14419:             }
                   14420:         }
                   14421:         if (keys(%todelete)) {
                   14422:             foreach my $key (keys(%todelete)) {
                   14423:                 unlink($key);
1.1066    raeburn  14424:             }
                   14425:         }
                   14426:         if (keys(%todeletedir)) {
                   14427:             foreach my $key (keys(%todeletedir)) {
                   14428:                 rmdir($key);
                   14429:             }
                   14430:         }
                   14431:         foreach my $dir (sort(keys(%is_dir))) {
                   14432:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14433:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14434:             }
                   14435:         }
1.1067    raeburn  14436:         if ($result ne '') {
                   14437:             $output .= '<ul>'."\n".
                   14438:                        $result."\n".
                   14439:                        '</ul>';
                   14440:         }
                   14441:         unless ($ishome) {
                   14442:             my $replicationfail;
                   14443:             foreach my $item (keys(%prompttofetch)) {
                   14444:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14445:                 unless ($fetchresult eq 'ok') {
                   14446:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14447:                 }
                   14448:             }
                   14449:             if ($replicationfail) {
                   14450:                 $output .= '<p class="LC_error">'.
                   14451:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14452:                            $replicationfail.
                   14453:                            '</ul></p>';
                   14454:             }
                   14455:         }
1.1055    raeburn  14456:     } else {
                   14457:         $warning = &mt('No items found in archive.');
                   14458:     }
                   14459:     if ($error) {
                   14460:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14461:                    $error.'</p>'."\n";
                   14462:     }
                   14463:     if ($warning) {
                   14464:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14465:     }
                   14466:     return $output;
                   14467: }
                   14468: 
1.1066    raeburn  14469: sub cleanup_empty_dirs {
                   14470:     my ($path) = @_;
                   14471:     if (($path ne '') && (-d $path)) {
                   14472:         if (opendir(my $dirh,$path)) {
                   14473:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14474:             my $numitems = 0;
                   14475:             foreach my $item (@dircontents) {
                   14476:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  14477:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14478:                     if (-e "$path/$item") {
                   14479:                         $numitems ++;
                   14480:                     }
                   14481:                 } else {
                   14482:                     $numitems ++;
                   14483:                 }
                   14484:             }
                   14485:             if ($numitems == 0) {
                   14486:                 rmdir($path);
                   14487:             }
                   14488:             closedir($dirh);
                   14489:         }
                   14490:     }
                   14491:     return;
                   14492: }
                   14493: 
1.41      ng       14494: =pod
1.45      matthew  14495: 
1.1075.2.56  raeburn  14496: =item * &get_folder_hierarchy()
1.1068    raeburn  14497: 
                   14498: Provides hierarchy of names of folders/sub-folders containing the current
                   14499: item,
                   14500: 
                   14501: Inputs: 3
                   14502:      - $navmap - navmaps object
                   14503: 
                   14504:      - $map - url for map (either the trigger itself, or map containing
                   14505:                            the resource, which is the trigger).
                   14506: 
                   14507:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14508: 
                   14509: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14510: 
                   14511: =cut
                   14512: 
                   14513: sub get_folder_hierarchy {
                   14514:     my ($navmap,$map,$showitem) = @_;
                   14515:     my @pathitems;
                   14516:     if (ref($navmap)) {
                   14517:         my $mapres = $navmap->getResourceByUrl($map);
                   14518:         if (ref($mapres)) {
                   14519:             my $pcslist = $mapres->map_hierarchy();
                   14520:             if ($pcslist ne '') {
                   14521:                 my @pcs = split(/,/,$pcslist);
                   14522:                 foreach my $pc (@pcs) {
                   14523:                     if ($pc == 1) {
1.1075.2.38  raeburn  14524:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14525:                     } else {
                   14526:                         my $res = $navmap->getByMapPc($pc);
                   14527:                         if (ref($res)) {
                   14528:                             my $title = $res->compTitle();
                   14529:                             $title =~ s/\W+/_/g;
                   14530:                             if ($title ne '') {
                   14531:                                 push(@pathitems,$title);
                   14532:                             }
                   14533:                         }
                   14534:                     }
                   14535:                 }
                   14536:             }
1.1071    raeburn  14537:             if ($showitem) {
                   14538:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  14539:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14540:                 } else {
                   14541:                     my $maptitle = $mapres->compTitle();
                   14542:                     $maptitle =~ s/\W+/_/g;
                   14543:                     if ($maptitle ne '') {
                   14544:                         push(@pathitems,$maptitle);
                   14545:                     }
1.1068    raeburn  14546:                 }
                   14547:             }
                   14548:         }
                   14549:     }
                   14550:     return @pathitems;
                   14551: }
                   14552: 
                   14553: =pod
                   14554: 
1.1015    raeburn  14555: =item * &get_turnedin_filepath()
                   14556: 
                   14557: Determines path in a user's portfolio file for storage of files uploaded
                   14558: to a specific essayresponse or dropbox item.
                   14559: 
                   14560: Inputs: 3 required + 1 optional.
                   14561: $symb is symb for resource, $uname and $udom are for current user (required).
                   14562: $caller is optional (can be "submission", if routine is called when storing
                   14563: an upoaded file when "Submit Answer" button was pressed).
                   14564: 
                   14565: Returns array containing $path and $multiresp. 
                   14566: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14567: than one file upload item.  Callers of routine should append partid as a 
                   14568: subdirectory to $path in cases where $multiresp is 1.
                   14569: 
                   14570: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14571: 
                   14572: =cut
                   14573: 
                   14574: sub get_turnedin_filepath {
                   14575:     my ($symb,$uname,$udom,$caller) = @_;
                   14576:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14577:     my $turnindir;
                   14578:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14579:     $turnindir = $userhash{'turnindir'};
                   14580:     my ($path,$multiresp);
                   14581:     if ($turnindir eq '') {
                   14582:         if ($caller eq 'submission') {
                   14583:             $turnindir = &mt('turned in');
                   14584:             $turnindir =~ s/\W+/_/g;
                   14585:             my %newhash = (
                   14586:                             'turnindir' => $turnindir,
                   14587:                           );
                   14588:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14589:         }
                   14590:     }
                   14591:     if ($turnindir ne '') {
                   14592:         $path = '/'.$turnindir.'/';
                   14593:         my ($multipart,$turnin,@pathitems);
                   14594:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14595:         if (defined($navmap)) {
                   14596:             my $mapres = $navmap->getResourceByUrl($map);
                   14597:             if (ref($mapres)) {
                   14598:                 my $pcslist = $mapres->map_hierarchy();
                   14599:                 if ($pcslist ne '') {
                   14600:                     foreach my $pc (split(/,/,$pcslist)) {
                   14601:                         my $res = $navmap->getByMapPc($pc);
                   14602:                         if (ref($res)) {
                   14603:                             my $title = $res->compTitle();
                   14604:                             $title =~ s/\W+/_/g;
                   14605:                             if ($title ne '') {
1.1075.2.48  raeburn  14606:                                 if (($pc > 1) && (length($title) > 12)) {
                   14607:                                     $title = substr($title,0,12);
                   14608:                                 }
1.1015    raeburn  14609:                                 push(@pathitems,$title);
                   14610:                             }
                   14611:                         }
                   14612:                     }
                   14613:                 }
                   14614:                 my $maptitle = $mapres->compTitle();
                   14615:                 $maptitle =~ s/\W+/_/g;
                   14616:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14617:                     if (length($maptitle) > 12) {
                   14618:                         $maptitle = substr($maptitle,0,12);
                   14619:                     }
1.1015    raeburn  14620:                     push(@pathitems,$maptitle);
                   14621:                 }
                   14622:                 unless ($env{'request.state'} eq 'construct') {
                   14623:                     my $res = $navmap->getBySymb($symb);
                   14624:                     if (ref($res)) {
                   14625:                         my $partlist = $res->parts();
                   14626:                         my $totaluploads = 0;
                   14627:                         if (ref($partlist) eq 'ARRAY') {
                   14628:                             foreach my $part (@{$partlist}) {
                   14629:                                 my @types = $res->responseType($part);
                   14630:                                 my @ids = $res->responseIds($part);
                   14631:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14632:                                     if ($types[$i] eq 'essay') {
                   14633:                                         my $partid = $part.'_'.$ids[$i];
                   14634:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14635:                                             $totaluploads ++;
                   14636:                                         }
                   14637:                                     }
                   14638:                                 }
                   14639:                             }
                   14640:                             if ($totaluploads > 1) {
                   14641:                                 $multiresp = 1;
                   14642:                             }
                   14643:                         }
                   14644:                     }
                   14645:                 }
                   14646:             } else {
                   14647:                 return;
                   14648:             }
                   14649:         } else {
                   14650:             return;
                   14651:         }
                   14652:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14653:         $restitle =~ s/\W+/_/g;
                   14654:         if ($restitle eq '') {
                   14655:             $restitle = ($resurl =~ m{/[^/]+$});
                   14656:             if ($restitle eq '') {
                   14657:                 $restitle = time;
                   14658:             }
                   14659:         }
1.1075.2.48  raeburn  14660:         if (length($restitle) > 12) {
                   14661:             $restitle = substr($restitle,0,12);
                   14662:         }
1.1015    raeburn  14663:         push(@pathitems,$restitle);
                   14664:         $path .= join('/',@pathitems);
                   14665:     }
                   14666:     return ($path,$multiresp);
                   14667: }
                   14668: 
                   14669: =pod
                   14670: 
1.464     albertel 14671: =back
1.41      ng       14672: 
1.112     bowersj2 14673: =head1 CSV Upload/Handling functions
1.38      albertel 14674: 
1.41      ng       14675: =over 4
                   14676: 
1.648     raeburn  14677: =item * &upfile_store($r)
1.41      ng       14678: 
                   14679: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14680: needs $env{'form.upfile'}
1.41      ng       14681: returns $datatoken to be put into hidden field
                   14682: 
                   14683: =cut
1.31      albertel 14684: 
                   14685: sub upfile_store {
                   14686:     my $r=shift;
1.258     albertel 14687:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14688:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14689:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14690:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14691: 
1.1075.2.128  raeburn  14692:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14693:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14694:                                      time.'_'.$$);
                   14695:     return if ($datatoken eq '');
                   14696: 
1.31      albertel 14697:     {
1.158     raeburn  14698:         my $datafile = $r->dir_config('lonDaemons').
                   14699:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14700:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14701:             print $fh $env{'form.upfile'};
1.158     raeburn  14702:             close($fh);
                   14703:         }
1.31      albertel 14704:     }
                   14705:     return $datatoken;
                   14706: }
                   14707: 
1.56      matthew  14708: =pod
                   14709: 
1.1075.2.128  raeburn  14710: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14711: 
                   14712: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14713: $datatoken is the name to assign to the temporary file.
1.258     albertel 14714: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14715: 
                   14716: =cut
1.31      albertel 14717: 
                   14718: sub load_tmp_file {
1.1075.2.128  raeburn  14719:     my ($r,$datatoken) = @_;
                   14720:     return if ($datatoken eq '');
1.31      albertel 14721:     my @studentdata=();
                   14722:     {
1.158     raeburn  14723:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14724:                               '/tmp/'.$datatoken.'.tmp';
                   14725:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14726:             @studentdata=<$fh>;
                   14727:             close($fh);
                   14728:         }
1.31      albertel 14729:     }
1.258     albertel 14730:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14731: }
                   14732: 
1.1075.2.128  raeburn  14733: sub valid_datatoken {
                   14734:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14735:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14736:         return $datatoken;
                   14737:     }
                   14738:     return;
                   14739: }
                   14740: 
1.56      matthew  14741: =pod
                   14742: 
1.648     raeburn  14743: =item * &upfile_record_sep()
1.41      ng       14744: 
                   14745: Separate uploaded file into records
                   14746: returns array of records,
1.258     albertel 14747: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14748: 
                   14749: =cut
1.31      albertel 14750: 
                   14751: sub upfile_record_sep {
1.258     albertel 14752:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14753:     } else {
1.248     albertel 14754: 	my @records;
1.258     albertel 14755: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14756: 	    if ($line=~/^\s*$/) { next; }
                   14757: 	    push(@records,$line);
                   14758: 	}
                   14759: 	return @records;
1.31      albertel 14760:     }
                   14761: }
                   14762: 
1.56      matthew  14763: =pod
                   14764: 
1.648     raeburn  14765: =item * &record_sep($record)
1.41      ng       14766: 
1.258     albertel 14767: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14768: 
                   14769: =cut
                   14770: 
1.263     www      14771: sub takeleft {
                   14772:     my $index=shift;
                   14773:     return substr('0000'.$index,-4,4);
                   14774: }
                   14775: 
1.31      albertel 14776: sub record_sep {
                   14777:     my $record=shift;
                   14778:     my %components=();
1.258     albertel 14779:     if ($env{'form.upfiletype'} eq 'xml') {
                   14780:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14781:         my $i=0;
1.356     albertel 14782:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14783:             $field=~s/^(\"|\')//;
                   14784:             $field=~s/(\"|\')$//;
1.263     www      14785:             $components{&takeleft($i)}=$field;
1.31      albertel 14786:             $i++;
                   14787:         }
1.258     albertel 14788:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14789:         my $i=0;
1.356     albertel 14790:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14791:             $field=~s/^(\"|\')//;
                   14792:             $field=~s/(\"|\')$//;
1.263     www      14793:             $components{&takeleft($i)}=$field;
1.31      albertel 14794:             $i++;
                   14795:         }
                   14796:     } else {
1.561     www      14797:         my $separator=',';
1.480     banghart 14798:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14799:             $separator=';';
1.480     banghart 14800:         }
1.31      albertel 14801:         my $i=0;
1.561     www      14802: # the character we are looking for to indicate the end of a quote or a record 
                   14803:         my $looking_for=$separator;
                   14804: # do not add the characters to the fields
                   14805:         my $ignore=0;
                   14806: # we just encountered a separator (or the beginning of the record)
                   14807:         my $just_found_separator=1;
                   14808: # store the field we are working on here
                   14809:         my $field='';
                   14810: # work our way through all characters in record
                   14811:         foreach my $character ($record=~/(.)/g) {
                   14812:             if ($character eq $looking_for) {
                   14813:                if ($character ne $separator) {
                   14814: # Found the end of a quote, again looking for separator
                   14815:                   $looking_for=$separator;
                   14816:                   $ignore=1;
                   14817:                } else {
                   14818: # Found a separator, store away what we got
                   14819:                   $components{&takeleft($i)}=$field;
                   14820: 	          $i++;
                   14821:                   $just_found_separator=1;
                   14822:                   $ignore=0;
                   14823:                   $field='';
                   14824:                }
                   14825:                next;
                   14826:             }
                   14827: # single or double quotation marks after a separator indicate beginning of a quote
                   14828: # we are now looking for the end of the quote and need to ignore separators
                   14829:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14830:                $looking_for=$character;
                   14831:                next;
                   14832:             }
                   14833: # ignore would be true after we reached the end of a quote
                   14834:             if ($ignore) { next; }
                   14835:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14836:             $field.=$character;
                   14837:             $just_found_separator=0; 
1.31      albertel 14838:         }
1.561     www      14839: # catch the very last entry, since we never encountered the separator
                   14840:         $components{&takeleft($i)}=$field;
1.31      albertel 14841:     }
                   14842:     return %components;
                   14843: }
                   14844: 
1.144     matthew  14845: ######################################################
                   14846: ######################################################
                   14847: 
1.56      matthew  14848: =pod
                   14849: 
1.648     raeburn  14850: =item * &upfile_select_html()
1.41      ng       14851: 
1.144     matthew  14852: Return HTML code to select a file from the users machine and specify 
                   14853: the file type.
1.41      ng       14854: 
                   14855: =cut
                   14856: 
1.144     matthew  14857: ######################################################
                   14858: ######################################################
1.31      albertel 14859: sub upfile_select_html {
1.144     matthew  14860:     my %Types = (
                   14861:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14862:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14863:                  space => &mt('Space separated'),
                   14864:                  tab   => &mt('Tabulator separated'),
                   14865: #                 xml   => &mt('HTML/XML'),
                   14866:                  );
                   14867:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14868:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14869:     foreach my $type (sort(keys(%Types))) {
                   14870:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14871:     }
                   14872:     $Str .= "</select>\n";
                   14873:     return $Str;
1.31      albertel 14874: }
                   14875: 
1.301     albertel 14876: sub get_samples {
                   14877:     my ($records,$toget) = @_;
                   14878:     my @samples=({});
                   14879:     my $got=0;
                   14880:     foreach my $rec (@$records) {
                   14881: 	my %temp = &record_sep($rec);
                   14882: 	if (! grep(/\S/, values(%temp))) { next; }
                   14883: 	if (%temp) {
                   14884: 	    $samples[$got]=\%temp;
                   14885: 	    $got++;
                   14886: 	    if ($got == $toget) { last; }
                   14887: 	}
                   14888:     }
                   14889:     return \@samples;
                   14890: }
                   14891: 
1.144     matthew  14892: ######################################################
                   14893: ######################################################
                   14894: 
1.56      matthew  14895: =pod
                   14896: 
1.648     raeburn  14897: =item * &csv_print_samples($r,$records)
1.41      ng       14898: 
                   14899: Prints a table of sample values from each column uploaded $r is an
                   14900: Apache Request ref, $records is an arrayref from
                   14901: &Apache::loncommon::upfile_record_sep
                   14902: 
                   14903: =cut
                   14904: 
1.144     matthew  14905: ######################################################
                   14906: ######################################################
1.31      albertel 14907: sub csv_print_samples {
                   14908:     my ($r,$records) = @_;
1.662     bisitz   14909:     my $samples = &get_samples($records,5);
1.301     albertel 14910: 
1.594     raeburn  14911:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14912:               &start_data_table_header_row());
1.356     albertel 14913:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14914:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14915:     $r->print(&end_data_table_header_row());
1.301     albertel 14916:     foreach my $hash (@$samples) {
1.594     raeburn  14917: 	$r->print(&start_data_table_row());
1.356     albertel 14918: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14919: 	    $r->print('<td>');
1.356     albertel 14920: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14921: 	    $r->print('</td>');
                   14922: 	}
1.594     raeburn  14923: 	$r->print(&end_data_table_row());
1.31      albertel 14924:     }
1.594     raeburn  14925:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14926: }
                   14927: 
1.144     matthew  14928: ######################################################
                   14929: ######################################################
                   14930: 
1.56      matthew  14931: =pod
                   14932: 
1.648     raeburn  14933: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14934: 
                   14935: Prints a table to create associations between values and table columns.
1.144     matthew  14936: 
1.41      ng       14937: $r is an Apache Request ref,
                   14938: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14939: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14940: 
                   14941: =cut
                   14942: 
1.144     matthew  14943: ######################################################
                   14944: ######################################################
1.31      albertel 14945: sub csv_print_select_table {
                   14946:     my ($r,$records,$d) = @_;
1.301     albertel 14947:     my $i=0;
                   14948:     my $samples = &get_samples($records,1);
1.144     matthew  14949:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14950: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14951:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14952:               '<th>'.&mt('Column').'</th>'.
                   14953:               &end_data_table_header_row()."\n");
1.356     albertel 14954:     foreach my $array_ref (@$d) {
                   14955: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14956: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14957: 
1.875     bisitz   14958: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14959: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14960: 	$r->print('<option value="none"></option>');
1.356     albertel 14961: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14962: 	    $r->print('<option value="'.$sample.'"'.
                   14963:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14964:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14965: 	}
1.594     raeburn  14966: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14967: 	$i++;
                   14968:     }
1.594     raeburn  14969:     $r->print(&end_data_table());
1.31      albertel 14970:     $i--;
                   14971:     return $i;
                   14972: }
1.56      matthew  14973: 
1.144     matthew  14974: ######################################################
                   14975: ######################################################
                   14976: 
1.56      matthew  14977: =pod
1.31      albertel 14978: 
1.648     raeburn  14979: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14980: 
                   14981: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14982: 
                   14983: $r is an Apache Request ref,
                   14984: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14985: $d is an array of 2 element arrays (internal name, displayed name)
                   14986: 
                   14987: =cut
                   14988: 
1.144     matthew  14989: ######################################################
                   14990: ######################################################
1.31      albertel 14991: sub csv_samples_select_table {
                   14992:     my ($r,$records,$d) = @_;
                   14993:     my $i=0;
1.144     matthew  14994:     #
1.662     bisitz   14995:     my $max_samples = 5;
                   14996:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14997:     $r->print(&start_data_table().
                   14998:               &start_data_table_header_row().'<th>'.
                   14999:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15000:               &end_data_table_header_row());
1.301     albertel 15001: 
                   15002:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15003: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15004: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15005: 	foreach my $option (@$d) {
                   15006: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15007: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15008:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15009:                       $display.'</option>');
1.31      albertel 15010: 	}
                   15011: 	$r->print('</select></td><td>');
1.662     bisitz   15012: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15013: 	    if (defined($samples->[$line]{$key})) { 
                   15014: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15015: 	    }
                   15016: 	}
1.594     raeburn  15017: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15018: 	$i++;
                   15019:     }
1.594     raeburn  15020:     $r->print(&end_data_table());
1.31      albertel 15021:     $i--;
                   15022:     return($i);
1.115     matthew  15023: }
                   15024: 
1.144     matthew  15025: ######################################################
                   15026: ######################################################
                   15027: 
1.115     matthew  15028: =pod
                   15029: 
1.648     raeburn  15030: =item * &clean_excel_name($name)
1.115     matthew  15031: 
                   15032: Returns a replacement for $name which does not contain any illegal characters.
                   15033: 
                   15034: =cut
                   15035: 
1.144     matthew  15036: ######################################################
                   15037: ######################################################
1.115     matthew  15038: sub clean_excel_name {
                   15039:     my ($name) = @_;
                   15040:     $name =~ s/[:\*\?\/\\]//g;
                   15041:     if (length($name) > 31) {
                   15042:         $name = substr($name,0,31);
                   15043:     }
                   15044:     return $name;
1.25      albertel 15045: }
1.84      albertel 15046: 
1.85      albertel 15047: =pod
                   15048: 
1.648     raeburn  15049: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15050: 
                   15051: Returns either 1 or undef
                   15052: 
                   15053: 1 if the part is to be hidden, undef if it is to be shown
                   15054: 
                   15055: Arguments are:
                   15056: 
                   15057: $id the id of the part to be checked
                   15058: $symb, optional the symb of the resource to check
                   15059: $udom, optional the domain of the user to check for
                   15060: $uname, optional the username of the user to check for
                   15061: 
                   15062: =cut
1.84      albertel 15063: 
                   15064: sub check_if_partid_hidden {
                   15065:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15066:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15067: 					 $symb,$udom,$uname);
1.141     albertel 15068:     my $truth=1;
                   15069:     #if the string starts with !, then the list is the list to show not hide
                   15070:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15071:     my @hiddenlist=split(/,/,$hiddenparts);
                   15072:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15073: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15074:     }
1.141     albertel 15075:     return !$truth;
1.84      albertel 15076: }
1.127     matthew  15077: 
1.138     matthew  15078: 
                   15079: ############################################################
                   15080: ############################################################
                   15081: 
                   15082: =pod
                   15083: 
1.157     matthew  15084: =back 
                   15085: 
1.138     matthew  15086: =head1 cgi-bin script and graphing routines
                   15087: 
1.157     matthew  15088: =over 4
                   15089: 
1.648     raeburn  15090: =item * &get_cgi_id()
1.138     matthew  15091: 
                   15092: Inputs: none
                   15093: 
                   15094: Returns an id which can be used to pass environment variables
                   15095: to various cgi-bin scripts.  These environment variables will
                   15096: be removed from the users environment after a given time by
                   15097: the routine &Apache::lonnet::transfer_profile_to_env.
                   15098: 
                   15099: =cut
                   15100: 
                   15101: ############################################################
                   15102: ############################################################
1.152     albertel 15103: my $uniq=0;
1.136     matthew  15104: sub get_cgi_id {
1.154     albertel 15105:     $uniq=($uniq+1)%100000;
1.280     albertel 15106:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15107: }
                   15108: 
1.127     matthew  15109: ############################################################
                   15110: ############################################################
                   15111: 
                   15112: =pod
                   15113: 
1.648     raeburn  15114: =item * &DrawBarGraph()
1.127     matthew  15115: 
1.138     matthew  15116: Facilitates the plotting of data in a (stacked) bar graph.
                   15117: Puts plot definition data into the users environment in order for 
                   15118: graph.png to plot it.  Returns an <img> tag for the plot.
                   15119: The bars on the plot are labeled '1','2',...,'n'.
                   15120: 
                   15121: Inputs:
                   15122: 
                   15123: =over 4
                   15124: 
                   15125: =item $Title: string, the title of the plot
                   15126: 
                   15127: =item $xlabel: string, text describing the X-axis of the plot
                   15128: 
                   15129: =item $ylabel: string, text describing the Y-axis of the plot
                   15130: 
                   15131: =item $Max: scalar, the maximum Y value to use in the plot
                   15132: If $Max is < any data point, the graph will not be rendered.
                   15133: 
1.140     matthew  15134: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15135: they are plotted.  If undefined, default values will be used.
                   15136: 
1.178     matthew  15137: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15138: 
1.138     matthew  15139: =item @Values: An array of array references.  Each array reference holds data
                   15140: to be plotted in a stacked bar chart.
                   15141: 
1.239     matthew  15142: =item If the final element of @Values is a hash reference the key/value
                   15143: pairs will be added to the graph definition.
                   15144: 
1.138     matthew  15145: =back
                   15146: 
                   15147: Returns:
                   15148: 
                   15149: An <img> tag which references graph.png and the appropriate identifying
                   15150: information for the plot.
                   15151: 
1.127     matthew  15152: =cut
                   15153: 
                   15154: ############################################################
                   15155: ############################################################
1.134     matthew  15156: sub DrawBarGraph {
1.178     matthew  15157:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15158:     #
                   15159:     if (! defined($colors)) {
                   15160:         $colors = ['#33ff00', 
                   15161:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15162:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15163:                   ]; 
                   15164:     }
1.228     matthew  15165:     my $extra_settings = {};
                   15166:     if (ref($Values[-1]) eq 'HASH') {
                   15167:         $extra_settings = pop(@Values);
                   15168:     }
1.127     matthew  15169:     #
1.136     matthew  15170:     my $identifier = &get_cgi_id();
                   15171:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15172:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15173:         return '';
                   15174:     }
1.225     matthew  15175:     #
                   15176:     my @Labels;
                   15177:     if (defined($labels)) {
                   15178:         @Labels = @$labels;
                   15179:     } else {
                   15180:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  15181:             push(@Labels,$i+1);
1.225     matthew  15182:         }
                   15183:     }
                   15184:     #
1.129     matthew  15185:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15186:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15187:     my %ValuesHash;
                   15188:     my $NumSets=1;
                   15189:     foreach my $array (@Values) {
                   15190:         next if (! ref($array));
1.136     matthew  15191:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15192:             join(',',@$array);
1.129     matthew  15193:     }
1.127     matthew  15194:     #
1.136     matthew  15195:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15196:     if ($NumBars < 3) {
                   15197:         $width = 120+$NumBars*32;
1.220     matthew  15198:         $xskip = 1;
1.225     matthew  15199:         $bar_width = 30;
                   15200:     } elsif ($NumBars < 5) {
                   15201:         $width = 120+$NumBars*20;
                   15202:         $xskip = 1;
                   15203:         $bar_width = 20;
1.220     matthew  15204:     } elsif ($NumBars < 10) {
1.136     matthew  15205:         $width = 120+$NumBars*15;
                   15206:         $xskip = 1;
                   15207:         $bar_width = 15;
                   15208:     } elsif ($NumBars <= 25) {
                   15209:         $width = 120+$NumBars*11;
                   15210:         $xskip = 5;
                   15211:         $bar_width = 8;
                   15212:     } elsif ($NumBars <= 50) {
                   15213:         $width = 120+$NumBars*8;
                   15214:         $xskip = 5;
                   15215:         $bar_width = 4;
                   15216:     } else {
                   15217:         $width = 120+$NumBars*8;
                   15218:         $xskip = 5;
                   15219:         $bar_width = 4;
                   15220:     }
                   15221:     #
1.137     matthew  15222:     $Max = 1 if ($Max < 1);
                   15223:     if ( int($Max) < $Max ) {
                   15224:         $Max++;
                   15225:         $Max = int($Max);
                   15226:     }
1.127     matthew  15227:     $Title  = '' if (! defined($Title));
                   15228:     $xlabel = '' if (! defined($xlabel));
                   15229:     $ylabel = '' if (! defined($ylabel));
1.369     www      15230:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15231:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15232:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15233:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15234:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15235:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15236:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15237:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15238:     $ValuesHash{$id.'.height'}   = $height;
                   15239:     $ValuesHash{$id.'.width'}    = $width;
                   15240:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15241:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15242:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15243:     #
1.228     matthew  15244:     # Deal with other parameters
                   15245:     while (my ($key,$value) = each(%$extra_settings)) {
                   15246:         $ValuesHash{$id.'.'.$key} = $value;
                   15247:     }
                   15248:     #
1.646     raeburn  15249:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15250:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15251: }
                   15252: 
                   15253: ############################################################
                   15254: ############################################################
                   15255: 
                   15256: =pod
                   15257: 
1.648     raeburn  15258: =item * &DrawXYGraph()
1.137     matthew  15259: 
1.138     matthew  15260: Facilitates the plotting of data in an XY graph.
                   15261: Puts plot definition data into the users environment in order for 
                   15262: graph.png to plot it.  Returns an <img> tag for the plot.
                   15263: 
                   15264: Inputs:
                   15265: 
                   15266: =over 4
                   15267: 
                   15268: =item $Title: string, the title of the plot
                   15269: 
                   15270: =item $xlabel: string, text describing the X-axis of the plot
                   15271: 
                   15272: =item $ylabel: string, text describing the Y-axis of the plot
                   15273: 
                   15274: =item $Max: scalar, the maximum Y value to use in the plot
                   15275: If $Max is < any data point, the graph will not be rendered.
                   15276: 
                   15277: =item $colors: Array ref containing the hex color codes for the data to be 
                   15278: plotted in.  If undefined, default values will be used.
                   15279: 
                   15280: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15281: 
                   15282: =item $Ydata: Array ref containing Array refs.  
1.185     www      15283: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15284: 
                   15285: =item %Values: hash indicating or overriding any default values which are 
                   15286: passed to graph.png.  
                   15287: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15288: 
                   15289: =back
                   15290: 
                   15291: Returns:
                   15292: 
                   15293: An <img> tag which references graph.png and the appropriate identifying
                   15294: information for the plot.
                   15295: 
1.137     matthew  15296: =cut
                   15297: 
                   15298: ############################################################
                   15299: ############################################################
                   15300: sub DrawXYGraph {
                   15301:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15302:     #
                   15303:     # Create the identifier for the graph
                   15304:     my $identifier = &get_cgi_id();
                   15305:     my $id = 'cgi.'.$identifier;
                   15306:     #
                   15307:     $Title  = '' if (! defined($Title));
                   15308:     $xlabel = '' if (! defined($xlabel));
                   15309:     $ylabel = '' if (! defined($ylabel));
                   15310:     my %ValuesHash = 
                   15311:         (
1.369     www      15312:          $id.'.title'  => &escape($Title),
                   15313:          $id.'.xlabel' => &escape($xlabel),
                   15314:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15315:          $id.'.y_max_value'=> $Max,
                   15316:          $id.'.labels'     => join(',',@$Xlabels),
                   15317:          $id.'.PlotType'   => 'XY',
                   15318:          );
                   15319:     #
                   15320:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15321:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15322:     }
                   15323:     #
                   15324:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15325:         return '';
                   15326:     }
                   15327:     my $NumSets=1;
1.138     matthew  15328:     foreach my $array (@{$Ydata}){
1.137     matthew  15329:         next if (! ref($array));
                   15330:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15331:     }
1.138     matthew  15332:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15333:     #
                   15334:     # Deal with other parameters
                   15335:     while (my ($key,$value) = each(%Values)) {
                   15336:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15337:     }
                   15338:     #
1.646     raeburn  15339:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15340:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15341: }
                   15342: 
                   15343: ############################################################
                   15344: ############################################################
                   15345: 
                   15346: =pod
                   15347: 
1.648     raeburn  15348: =item * &DrawXYYGraph()
1.138     matthew  15349: 
                   15350: Facilitates the plotting of data in an XY graph with two Y axes.
                   15351: Puts plot definition data into the users environment in order for 
                   15352: graph.png to plot it.  Returns an <img> tag for the plot.
                   15353: 
                   15354: Inputs:
                   15355: 
                   15356: =over 4
                   15357: 
                   15358: =item $Title: string, the title of the plot
                   15359: 
                   15360: =item $xlabel: string, text describing the X-axis of the plot
                   15361: 
                   15362: =item $ylabel: string, text describing the Y-axis of the plot
                   15363: 
                   15364: =item $colors: Array ref containing the hex color codes for the data to be 
                   15365: plotted in.  If undefined, default values will be used.
                   15366: 
                   15367: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15368: 
                   15369: =item $Ydata1: The first data set
                   15370: 
                   15371: =item $Min1: The minimum value of the left Y-axis
                   15372: 
                   15373: =item $Max1: The maximum value of the left Y-axis
                   15374: 
                   15375: =item $Ydata2: The second data set
                   15376: 
                   15377: =item $Min2: The minimum value of the right Y-axis
                   15378: 
                   15379: =item $Max2: The maximum value of the left Y-axis
                   15380: 
                   15381: =item %Values: hash indicating or overriding any default values which are 
                   15382: passed to graph.png.  
                   15383: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15384: 
                   15385: =back
                   15386: 
                   15387: Returns:
                   15388: 
                   15389: An <img> tag which references graph.png and the appropriate identifying
                   15390: information for the plot.
1.136     matthew  15391: 
                   15392: =cut
                   15393: 
                   15394: ############################################################
                   15395: ############################################################
1.137     matthew  15396: sub DrawXYYGraph {
                   15397:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15398:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15399:     #
                   15400:     # Create the identifier for the graph
                   15401:     my $identifier = &get_cgi_id();
                   15402:     my $id = 'cgi.'.$identifier;
                   15403:     #
                   15404:     $Title  = '' if (! defined($Title));
                   15405:     $xlabel = '' if (! defined($xlabel));
                   15406:     $ylabel = '' if (! defined($ylabel));
                   15407:     my %ValuesHash = 
                   15408:         (
1.369     www      15409:          $id.'.title'  => &escape($Title),
                   15410:          $id.'.xlabel' => &escape($xlabel),
                   15411:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15412:          $id.'.labels' => join(',',@$Xlabels),
                   15413:          $id.'.PlotType' => 'XY',
                   15414:          $id.'.NumSets' => 2,
1.137     matthew  15415:          $id.'.two_axes' => 1,
                   15416:          $id.'.y1_max_value' => $Max1,
                   15417:          $id.'.y1_min_value' => $Min1,
                   15418:          $id.'.y2_max_value' => $Max2,
                   15419:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15420:          );
                   15421:     #
1.137     matthew  15422:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15423:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15424:     }
                   15425:     #
                   15426:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15427:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15428:         return '';
                   15429:     }
                   15430:     my $NumSets=1;
1.137     matthew  15431:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15432:         next if (! ref($array));
                   15433:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15434:     }
                   15435:     #
                   15436:     # Deal with other parameters
                   15437:     while (my ($key,$value) = each(%Values)) {
                   15438:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15439:     }
                   15440:     #
1.646     raeburn  15441:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15442:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15443: }
                   15444: 
                   15445: ############################################################
                   15446: ############################################################
                   15447: 
                   15448: =pod
                   15449: 
1.157     matthew  15450: =back 
                   15451: 
1.139     matthew  15452: =head1 Statistics helper routines?  
                   15453: 
                   15454: Bad place for them but what the hell.
                   15455: 
1.157     matthew  15456: =over 4
                   15457: 
1.648     raeburn  15458: =item * &chartlink()
1.139     matthew  15459: 
                   15460: Returns a link to the chart for a specific student.  
                   15461: 
                   15462: Inputs:
                   15463: 
                   15464: =over 4
                   15465: 
                   15466: =item $linktext: The text of the link
                   15467: 
                   15468: =item $sname: The students username
                   15469: 
                   15470: =item $sdomain: The students domain
                   15471: 
                   15472: =back
                   15473: 
1.157     matthew  15474: =back
                   15475: 
1.139     matthew  15476: =cut
                   15477: 
                   15478: ############################################################
                   15479: ############################################################
                   15480: sub chartlink {
                   15481:     my ($linktext, $sname, $sdomain) = @_;
                   15482:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15483:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15484:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15485:        '">'.$linktext.'</a>';
1.153     matthew  15486: }
                   15487: 
                   15488: #######################################################
                   15489: #######################################################
                   15490: 
                   15491: =pod
                   15492: 
                   15493: =head1 Course Environment Routines
1.157     matthew  15494: 
                   15495: =over 4
1.153     matthew  15496: 
1.648     raeburn  15497: =item * &restore_course_settings()
1.153     matthew  15498: 
1.648     raeburn  15499: =item * &store_course_settings()
1.153     matthew  15500: 
                   15501: Restores/Store indicated form parameters from the course environment.
                   15502: Will not overwrite existing values of the form parameters.
                   15503: 
                   15504: Inputs: 
                   15505: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15506: 
                   15507: a hash ref describing the data to be stored.  For example:
                   15508:    
                   15509: %Save_Parameters = ('Status' => 'scalar',
                   15510:     'chartoutputmode' => 'scalar',
                   15511:     'chartoutputdata' => 'scalar',
                   15512:     'Section' => 'array',
1.373     raeburn  15513:     'Group' => 'array',
1.153     matthew  15514:     'StudentData' => 'array',
                   15515:     'Maps' => 'array');
                   15516: 
                   15517: Returns: both routines return nothing
                   15518: 
1.631     raeburn  15519: =back
                   15520: 
1.153     matthew  15521: =cut
                   15522: 
                   15523: #######################################################
                   15524: #######################################################
                   15525: sub store_course_settings {
1.496     albertel 15526:     return &store_settings($env{'request.course.id'},@_);
                   15527: }
                   15528: 
                   15529: sub store_settings {
1.153     matthew  15530:     # save to the environment
                   15531:     # appenv the same items, just to be safe
1.300     albertel 15532:     my $udom  = $env{'user.domain'};
                   15533:     my $uname = $env{'user.name'};
1.496     albertel 15534:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15535:     my %SaveHash;
                   15536:     my %AppHash;
                   15537:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15538:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15539:         my $envname = 'environment.'.$basename;
1.258     albertel 15540:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15541:             # Save this value away
                   15542:             if ($type eq 'scalar' &&
1.258     albertel 15543:                 (! exists($env{$envname}) || 
                   15544:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15545:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15546:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15547:             } elsif ($type eq 'array') {
                   15548:                 my $stored_form;
1.258     albertel 15549:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15550:                     $stored_form = join(',',
                   15551:                                         map {
1.369     www      15552:                                             &escape($_);
1.258     albertel 15553:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15554:                 } else {
                   15555:                     $stored_form = 
1.369     www      15556:                         &escape($env{'form.'.$setting});
1.153     matthew  15557:                 }
                   15558:                 # Determine if the array contents are the same.
1.258     albertel 15559:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15560:                     $SaveHash{$basename} = $stored_form;
                   15561:                     $AppHash{$envname}   = $stored_form;
                   15562:                 }
                   15563:             }
                   15564:         }
                   15565:     }
                   15566:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15567:                                           $udom,$uname);
1.153     matthew  15568:     if ($put_result !~ /^(ok|delayed)/) {
                   15569:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15570:                                  'got error:'.$put_result);
                   15571:     }
                   15572:     # Make sure these settings stick around in this session, too
1.646     raeburn  15573:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15574:     return;
                   15575: }
                   15576: 
                   15577: sub restore_course_settings {
1.499     albertel 15578:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15579: }
                   15580: 
                   15581: sub restore_settings {
                   15582:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15583:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15584:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15585:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15586:             '.'.$setting;
1.258     albertel 15587:         if (exists($env{$envname})) {
1.153     matthew  15588:             if ($type eq 'scalar') {
1.258     albertel 15589:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15590:             } elsif ($type eq 'array') {
1.258     albertel 15591:                 $env{'form.'.$setting} = [ 
1.153     matthew  15592:                                            map { 
1.369     www      15593:                                                &unescape($_); 
1.258     albertel 15594:                                            } split(',',$env{$envname})
1.153     matthew  15595:                                            ];
                   15596:             }
                   15597:         }
                   15598:     }
1.127     matthew  15599: }
                   15600: 
1.618     raeburn  15601: #######################################################
                   15602: #######################################################
                   15603: 
                   15604: =pod
                   15605: 
                   15606: =head1 Domain E-mail Routines  
                   15607: 
                   15608: =over 4
                   15609: 
1.648     raeburn  15610: =item * &build_recipient_list()
1.618     raeburn  15611: 
1.1075.2.44  raeburn  15612: Build recipient lists for following types of e-mail:
1.766     raeburn  15613: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15614: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15615: module change checking, student/employee ID conflict checks, as
                   15616: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15617: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15618: 
                   15619: Inputs:
1.1075.2.44  raeburn  15620: defmail (scalar - email address of default recipient),
                   15621: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15622: requestsmail, updatesmail, or idconflictsmail).
                   15623: 
1.619     raeburn  15624: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15625: 
                   15626: origmail (scalar - email address of recipient from loncapa.conf,
                   15627: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15628: 
1.1075.2.139  raeburn  15629: $requname username of requester (if mailing type is helpdeskmail)
                   15630: 
                   15631: $requdom domain of requester (if mailing type is helpdeskmail)
                   15632: 
                   15633: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15634: 
1.655     raeburn  15635: Returns: comma separated list of addresses to which to send e-mail.
                   15636: 
                   15637: =back
1.618     raeburn  15638: 
                   15639: =cut
                   15640: 
                   15641: ############################################################
                   15642: ############################################################
                   15643: sub build_recipient_list {
1.1075.2.139  raeburn  15644:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15645:     my @recipients;
1.1075.2.122  raeburn  15646:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15647:     my %domconfig =
1.1075.2.122  raeburn  15648:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15649:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15650:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15651:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15652:                 my @contacts = ('adminemail','supportemail');
                   15653:                 foreach my $item (@contacts) {
                   15654:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15655:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15656:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15657:                             push(@recipients,$addr);
                   15658:                         }
1.619     raeburn  15659:                     }
1.1075.2.122  raeburn  15660:                 }
                   15661:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15662:                 if ($mailing eq 'helpdeskmail') {
                   15663:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15664:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15665:                         my @ok_bccs;
                   15666:                         foreach my $bcc (@bccs) {
                   15667:                             $bcc =~ s/^\s+//g;
                   15668:                             $bcc =~ s/\s+$//g;
                   15669:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15670:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15671:                                     push(@ok_bccs,$bcc);
                   15672:                                 }
                   15673:                             }
                   15674:                         }
                   15675:                         if (@ok_bccs > 0) {
                   15676:                             $allbcc = join(', ',@ok_bccs);
                   15677:                         }
                   15678:                     }
                   15679:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15680:                 }
                   15681:             }
1.766     raeburn  15682:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15683:             $lastresort = $origmail;
1.618     raeburn  15684:         }
1.1075.2.139  raeburn  15685:         if ($mailing eq 'helpdeskmail') {
                   15686:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15687:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15688:                 my ($inststatus,$inststatus_checked);
                   15689:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15690:                     ($env{'user.domain'} ne 'public')) {
                   15691:                     $inststatus_checked = 1;
                   15692:                     $inststatus = $env{'environment.inststatus'};
                   15693:                 }
                   15694:                 unless ($inststatus_checked) {
                   15695:                     if (($requname ne '') && ($requdom ne '')) {
                   15696:                         if (($requname =~ /^$match_username$/) &&
                   15697:                             ($requdom =~ /^$match_domain$/) &&
                   15698:                             (&Apache::lonnet::domain($requdom))) {
                   15699:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15700:                                                                       $requdom);
                   15701:                             unless ($requhome eq 'no_host') {
                   15702:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15703:                                 $inststatus = $userenv{'inststatus'};
                   15704:                                 $inststatus_checked = 1;
                   15705:                             }
                   15706:                         }
                   15707:                     }
                   15708:                 }
                   15709:                 unless ($inststatus_checked) {
                   15710:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15711:                         my %srch = (srchby     => 'email',
                   15712:                                     srchdomain => $defdom,
                   15713:                                     srchterm   => $reqemail,
                   15714:                                     srchtype   => 'exact');
                   15715:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15716:                         foreach my $uname (keys(%srch_results)) {
                   15717:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15718:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15719:                                 $inststatus_checked = 1;
                   15720:                                 last;
                   15721:                             }
                   15722:                         }
                   15723:                         unless ($inststatus_checked) {
                   15724:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15725:                             if ($dirsrchres eq 'ok') {
                   15726:                                 foreach my $uname (keys(%srch_results)) {
                   15727:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15728:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15729:                                         $inststatus_checked = 1;
                   15730:                                         last;
                   15731:                                     }
                   15732:                                 }
                   15733:                             }
                   15734:                         }
                   15735:                     }
                   15736:                 }
                   15737:                 if ($inststatus ne '') {
                   15738:                     foreach my $status (split(/\:/,$inststatus)) {
                   15739:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15740:                             my @contacts = ('adminemail','supportemail');
                   15741:                             foreach my $item (@contacts) {
                   15742:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15743:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15744:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15745:                                         push(@recipients,$addr);
                   15746:                                     }
                   15747:                                 }
                   15748:                             }
                   15749:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15750:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15751:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15752:                                 my @ok_bccs;
                   15753:                                 foreach my $bcc (@bccs) {
                   15754:                                     $bcc =~ s/^\s+//g;
                   15755:                                     $bcc =~ s/\s+$//g;
                   15756:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15757:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15758:                                             push(@ok_bccs,$bcc);
                   15759:                                         }
                   15760:                                     }
                   15761:                                 }
                   15762:                                 if (@ok_bccs > 0) {
                   15763:                                     $allbcc = join(', ',@ok_bccs);
                   15764:                                 }
                   15765:                             }
                   15766:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15767:                             last;
                   15768:                         }
                   15769:                     }
                   15770:                 }
                   15771:             }
                   15772:         }
1.619     raeburn  15773:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15774:         $lastresort = $origmail;
                   15775:     }
1.1075.2.128  raeburn  15776:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15777:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15778:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15779:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15780:             my %what = (
                   15781:                           perlvar => 1,
                   15782:                        );
                   15783:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15784:             if ($primary) {
                   15785:                 my $gotaddr;
                   15786:                 my ($result,$returnhash) =
                   15787:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15788:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15789:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15790:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15791:                         $gotaddr = 1;
                   15792:                     }
                   15793:                 }
                   15794:                 unless ($gotaddr) {
                   15795:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15796:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15797:                     unless ($uintdom eq $intdom) {
                   15798:                         my %domconfig =
                   15799:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15800:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15801:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15802:                                 my @contacts = ('adminemail','supportemail');
                   15803:                                 foreach my $item (@contacts) {
                   15804:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15805:                                         my $addr = $domconfig{'contacts'}{$item};
                   15806:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15807:                                             push(@recipients,$addr);
                   15808:                                         }
                   15809:                                     }
                   15810:                                 }
                   15811:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15812:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15813:                                 }
                   15814:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15815:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15816:                                     my @ok_bccs;
                   15817:                                     foreach my $bcc (@bccs) {
                   15818:                                         $bcc =~ s/^\s+//g;
                   15819:                                         $bcc =~ s/\s+$//g;
                   15820:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15821:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15822:                                                 push(@ok_bccs,$bcc);
                   15823:                                             }
                   15824:                                         }
                   15825:                                     }
                   15826:                                     if (@ok_bccs > 0) {
                   15827:                                         $allbcc = join(', ',@ok_bccs);
                   15828:                                     }
                   15829:                                 }
                   15830:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15831:                             }
                   15832:                         }
                   15833:                     }
                   15834:                 }
                   15835:             }
                   15836:         }
1.618     raeburn  15837:     }
1.688     raeburn  15838:     if (defined($defmail)) {
                   15839:         if ($defmail ne '') {
                   15840:             push(@recipients,$defmail);
                   15841:         }
1.618     raeburn  15842:     }
                   15843:     if ($otheremails) {
1.619     raeburn  15844:         my @others;
                   15845:         if ($otheremails =~ /,/) {
                   15846:             @others = split(/,/,$otheremails);
1.618     raeburn  15847:         } else {
1.619     raeburn  15848:             push(@others,$otheremails);
                   15849:         }
                   15850:         foreach my $addr (@others) {
                   15851:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15852:                 push(@recipients,$addr);
                   15853:             }
1.618     raeburn  15854:         }
                   15855:     }
1.1075.2.128  raeburn  15856:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15857:         if ((!@recipients) && ($lastresort ne '')) {
                   15858:             push(@recipients,$lastresort);
                   15859:         }
                   15860:     } elsif ($lastresort ne '') {
                   15861:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15862:             push(@recipients,$lastresort);
                   15863:         }
                   15864:     }
                   15865:     my $recipientlist = join(',',@recipients);
                   15866:     if (wantarray) {
                   15867:         return ($recipientlist,$allbcc,$addtext);
                   15868:     } else {
                   15869:         return $recipientlist;
                   15870:     }
1.618     raeburn  15871: }
                   15872: 
1.127     matthew  15873: ############################################################
                   15874: ############################################################
1.154     albertel 15875: 
1.655     raeburn  15876: =pod
                   15877: 
                   15878: =head1 Course Catalog Routines
                   15879: 
                   15880: =over 4
                   15881: 
                   15882: =item * &gather_categories()
                   15883: 
                   15884: Converts category definitions - keys of categories hash stored in  
                   15885: coursecategories in configuration.db on the primary library server in a 
                   15886: domain - to an array.  Also generates javascript and idx hash used to 
                   15887: generate Domain Coordinator interface for editing Course Categories.
                   15888: 
                   15889: Inputs:
1.663     raeburn  15890: 
1.655     raeburn  15891: categories (reference to hash of category definitions).
1.663     raeburn  15892: 
1.655     raeburn  15893: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15894:       categories and subcategories).
1.663     raeburn  15895: 
1.655     raeburn  15896: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15897:       editing Course Categories).
1.663     raeburn  15898: 
1.655     raeburn  15899: jsarray (reference to array of categories used to create Javascript arrays for
                   15900:          Domain Coordinator interface for editing Course Categories).
                   15901: 
                   15902: Returns: nothing
                   15903: 
                   15904: Side effects: populates cats, idx and jsarray. 
                   15905: 
                   15906: =cut
                   15907: 
                   15908: sub gather_categories {
                   15909:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15910:     my %counters;
                   15911:     my $num = 0;
                   15912:     foreach my $item (keys(%{$categories})) {
                   15913:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15914:         if ($container eq '' && $depth == 0) {
                   15915:             $cats->[$depth][$categories->{$item}] = $cat;
                   15916:         } else {
                   15917:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15918:         }
                   15919:         my ($escitem,$tail) = split(/:/,$item,2);
                   15920:         if ($counters{$tail} eq '') {
                   15921:             $counters{$tail} = $num;
                   15922:             $num ++;
                   15923:         }
                   15924:         if (ref($idx) eq 'HASH') {
                   15925:             $idx->{$item} = $counters{$tail};
                   15926:         }
                   15927:         if (ref($jsarray) eq 'ARRAY') {
                   15928:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15929:         }
                   15930:     }
                   15931:     return;
                   15932: }
                   15933: 
                   15934: =pod
                   15935: 
                   15936: =item * &extract_categories()
                   15937: 
                   15938: Used to generate breadcrumb trails for course categories.
                   15939: 
                   15940: Inputs:
1.663     raeburn  15941: 
1.655     raeburn  15942: categories (reference to hash of category definitions).
1.663     raeburn  15943: 
1.655     raeburn  15944: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15945:       categories and subcategories).
1.663     raeburn  15946: 
1.655     raeburn  15947: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15948: 
1.655     raeburn  15949: allitems (reference to hash - key is category key 
                   15950:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15951: 
1.655     raeburn  15952: idx (reference to hash of counters used in Domain Coordinator interface for
                   15953:       editing Course Categories).
1.663     raeburn  15954: 
1.655     raeburn  15955: jsarray (reference to array of categories used to create Javascript arrays for
                   15956:          Domain Coordinator interface for editing Course Categories).
                   15957: 
1.665     raeburn  15958: subcats (reference to hash of arrays containing all subcategories within each 
                   15959:          category, -recursive)
                   15960: 
1.1075.2.132  raeburn  15961: maxd (reference to hash used to hold max depth for all top-level categories).
                   15962: 
1.655     raeburn  15963: Returns: nothing
                   15964: 
                   15965: Side effects: populates trails and allitems hash references.
                   15966: 
                   15967: =cut
                   15968: 
                   15969: sub extract_categories {
1.1075.2.132  raeburn  15970:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15971:     if (ref($categories) eq 'HASH') {
                   15972:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15973:         if (ref($cats->[0]) eq 'ARRAY') {
                   15974:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15975:                 my $name = $cats->[0][$i];
                   15976:                 my $item = &escape($name).'::0';
                   15977:                 my $trailstr;
                   15978:                 if ($name eq 'instcode') {
                   15979:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15980:                 } elsif ($name eq 'communities') {
                   15981:                     $trailstr = &mt('Communities');
1.655     raeburn  15982:                 } else {
                   15983:                     $trailstr = $name;
                   15984:                 }
                   15985:                 if ($allitems->{$item} eq '') {
                   15986:                     push(@{$trails},$trailstr);
                   15987:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15988:                 }
                   15989:                 my @parents = ($name);
                   15990:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15991:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15992:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15993:                         if (ref($subcats) eq 'HASH') {
                   15994:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15995:                         }
1.1075.2.132  raeburn  15996:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15997:                     }
                   15998:                 } else {
                   15999:                     if (ref($subcats) eq 'HASH') {
                   16000:                         $subcats->{$item} = [];
1.655     raeburn  16001:                     }
1.1075.2.132  raeburn  16002:                     if (ref($maxd) eq 'HASH') {
                   16003:                         $maxd->{$name} = 1;
                   16004:                     }
1.655     raeburn  16005:                 }
                   16006:             }
                   16007:         }
                   16008:     }
                   16009:     return;
                   16010: }
                   16011: 
                   16012: =pod
                   16013: 
1.1075.2.56  raeburn  16014: =item * &recurse_categories()
1.655     raeburn  16015: 
                   16016: Recursively used to generate breadcrumb trails for course categories.
                   16017: 
                   16018: Inputs:
1.663     raeburn  16019: 
1.655     raeburn  16020: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16021:       categories and subcategories).
1.663     raeburn  16022: 
1.655     raeburn  16023: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16024: 
                   16025: category (current course category, for which breadcrumb trail is being generated).
                   16026: 
                   16027: trails (reference to array of breadcrumb trails for each category).
                   16028: 
1.655     raeburn  16029: allitems (reference to hash - key is category key
                   16030:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16031: 
1.655     raeburn  16032: parents (array containing containers directories for current category, 
                   16033:          back to top level). 
                   16034: 
                   16035: Returns: nothing
                   16036: 
                   16037: Side effects: populates trails and allitems hash references
                   16038: 
                   16039: =cut
                   16040: 
                   16041: sub recurse_categories {
1.1075.2.132  raeburn  16042:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16043:     my $shallower = $depth - 1;
                   16044:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16045:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16046:             my $name = $cats->[$depth]{$category}[$k];
                   16047:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 16048:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16049:             if ($allitems->{$item} eq '') {
                   16050:                 push(@{$trails},$trailstr);
                   16051:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16052:             }
                   16053:             my $deeper = $depth+1;
                   16054:             push(@{$parents},$category);
1.665     raeburn  16055:             if (ref($subcats) eq 'HASH') {
                   16056:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16057:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16058:                     my $higher;
                   16059:                     if ($j > 0) {
                   16060:                         $higher = &escape($parents->[$j]).':'.
                   16061:                                   &escape($parents->[$j-1]).':'.$j;
                   16062:                     } else {
                   16063:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16064:                     }
                   16065:                     push(@{$subcats->{$higher}},$subcat);
                   16066:                 }
                   16067:             }
                   16068:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  16069:                                 $subcats,$maxd);
1.655     raeburn  16070:             pop(@{$parents});
                   16071:         }
                   16072:     } else {
                   16073:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  16074:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16075:         if ($allitems->{$item} eq '') {
                   16076:             push(@{$trails},$trailstr);
                   16077:             $allitems->{$item} = scalar(@{$trails})-1;
                   16078:         }
1.1075.2.132  raeburn  16079:         if (ref($maxd) eq 'HASH') {
                   16080:             if ($depth > $maxd->{$parents->[0]}) {
                   16081:                 $maxd->{$parents->[0]} = $depth;
                   16082:             }
                   16083:         }
1.655     raeburn  16084:     }
                   16085:     return;
                   16086: }
                   16087: 
1.663     raeburn  16088: =pod
                   16089: 
1.1075.2.56  raeburn  16090: =item * &assign_categories_table()
1.663     raeburn  16091: 
                   16092: Create a datatable for display of hierarchical categories in a domain,
                   16093: with checkboxes to allow a course to be categorized. 
                   16094: 
                   16095: Inputs:
                   16096: 
                   16097: cathash - reference to hash of categories defined for the domain (from
                   16098:           configuration.db)
                   16099: 
                   16100: currcat - scalar with an & separated list of categories assigned to a course. 
                   16101: 
1.919     raeburn  16102: type    - scalar contains course type (Course or Community).
                   16103: 
1.1075.2.117  raeburn  16104: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16105:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16106: 
1.663     raeburn  16107: Returns: $output (markup to be displayed) 
                   16108: 
                   16109: =cut
                   16110: 
                   16111: sub assign_categories_table {
1.1075.2.117  raeburn  16112:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16113:     my $output;
                   16114:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  16115:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16116:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16117:         $maxdepth = scalar(@cats);
                   16118:         if (@cats > 0) {
                   16119:             my $itemcount = 0;
                   16120:             if (ref($cats[0]) eq 'ARRAY') {
                   16121:                 my @currcategories;
                   16122:                 if ($currcat ne '') {
                   16123:                     @currcategories = split('&',$currcat);
                   16124:                 }
1.919     raeburn  16125:                 my $table;
1.663     raeburn  16126:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16127:                     my $parent = $cats[0][$i];
1.919     raeburn  16128:                     next if ($parent eq 'instcode');
                   16129:                     if ($type eq 'Community') {
                   16130:                         next unless ($parent eq 'communities');
                   16131:                     } else {
                   16132:                         next if ($parent eq 'communities');
                   16133:                     }
1.663     raeburn  16134:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16135:                     my $item = &escape($parent).'::0';
                   16136:                     my $checked = '';
                   16137:                     if (@currcategories > 0) {
                   16138:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16139:                             $checked = ' checked="checked"';
1.663     raeburn  16140:                         }
                   16141:                     }
1.919     raeburn  16142:                     my $parent_title = $parent;
                   16143:                     if ($parent eq 'communities') {
                   16144:                         $parent_title = &mt('Communities');
                   16145:                     }
                   16146:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16147:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16148:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16149:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16150:                     my $depth = 1;
                   16151:                     push(@path,$parent);
1.1075.2.117  raeburn  16152:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16153:                     pop(@path);
1.919     raeburn  16154:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16155:                     $itemcount ++;
                   16156:                 }
1.919     raeburn  16157:                 if ($itemcount) {
                   16158:                     $output = &Apache::loncommon::start_data_table().
                   16159:                               $table.
                   16160:                               &Apache::loncommon::end_data_table();
                   16161:                 }
1.663     raeburn  16162:             }
                   16163:         }
                   16164:     }
                   16165:     return $output;
                   16166: }
                   16167: 
                   16168: =pod
                   16169: 
1.1075.2.56  raeburn  16170: =item * &assign_category_rows()
1.663     raeburn  16171: 
                   16172: Create a datatable row for display of nested categories in a domain,
                   16173: with checkboxes to allow a course to be categorized,called recursively.
                   16174: 
                   16175: Inputs:
                   16176: 
                   16177: itemcount - track row number for alternating colors
                   16178: 
                   16179: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16180:       categories and subcategories.
                   16181: 
                   16182: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16183: 
                   16184: parent - parent of current category item
                   16185: 
                   16186: path - Array containing all categories back up through the hierarchy from the
                   16187:        current category to the top level.
                   16188: 
                   16189: currcategories - reference to array of current categories assigned to the course
                   16190: 
1.1075.2.117  raeburn  16191: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16192:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16193: 
1.663     raeburn  16194: Returns: $output (markup to be displayed).
                   16195: 
                   16196: =cut
                   16197: 
                   16198: sub assign_category_rows {
1.1075.2.117  raeburn  16199:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16200:     my ($text,$name,$item,$chgstr);
                   16201:     if (ref($cats) eq 'ARRAY') {
                   16202:         my $maxdepth = scalar(@{$cats});
                   16203:         if (ref($cats->[$depth]) eq 'HASH') {
                   16204:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16205:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16206:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  16207:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16208:                 for (my $j=0; $j<$numchildren; $j++) {
                   16209:                     $name = $cats->[$depth]{$parent}[$j];
                   16210:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16211:                     my $deeper = $depth+1;
                   16212:                     my $checked = '';
                   16213:                     if (ref($currcategories) eq 'ARRAY') {
                   16214:                         if (@{$currcategories} > 0) {
                   16215:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16216:                                 $checked = ' checked="checked"';
1.663     raeburn  16217:                             }
                   16218:                         }
                   16219:                     }
1.664     raeburn  16220:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16221:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16222:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16223:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16224:                              '</td><td>';
1.663     raeburn  16225:                     if (ref($path) eq 'ARRAY') {
                   16226:                         push(@{$path},$name);
1.1075.2.117  raeburn  16227:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16228:                         pop(@{$path});
                   16229:                     }
                   16230:                     $text .= '</td></tr>';
                   16231:                 }
                   16232:                 $text .= '</table></td>';
                   16233:             }
                   16234:         }
                   16235:     }
                   16236:     return $text;
                   16237: }
                   16238: 
1.1075.2.69  raeburn  16239: =pod
                   16240: 
                   16241: =back
                   16242: 
                   16243: =cut
                   16244: 
1.655     raeburn  16245: ############################################################
                   16246: ############################################################
                   16247: 
                   16248: 
1.443     albertel 16249: sub commit_customrole {
1.664     raeburn  16250:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16251:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16252:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16253:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16254:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16255:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16256:                  '</b><br />';
                   16257:     return $output;
                   16258: }
                   16259: 
                   16260: sub commit_standardrole {
1.1075.2.31  raeburn  16261:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16262:     my ($output,$logmsg,$linefeed);
                   16263:     if ($context eq 'auto') {
                   16264:         $linefeed = "\n";
                   16265:     } else {
                   16266:         $linefeed = "<br />\n";
                   16267:     }  
1.443     albertel 16268:     if ($three eq 'st') {
1.541     raeburn  16269:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  16270:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16271:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16272:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16273:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16274:         } else {
1.541     raeburn  16275:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16276:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16277:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16278:             if ($context eq 'auto') {
                   16279:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16280:             } else {
                   16281:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16282:                &mt('Add to classlist').': <b>ok</b>';
                   16283:             }
                   16284:             $output .= $linefeed;
1.443     albertel 16285:         }
                   16286:     } else {
                   16287:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16288:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16289:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16290:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16291:         if ($context eq 'auto') {
                   16292:             $output .= $result.$linefeed;
                   16293:         } else {
                   16294:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16295:         }
1.443     albertel 16296:     }
                   16297:     return $output;
                   16298: }
                   16299: 
                   16300: sub commit_studentrole {
1.1075.2.31  raeburn  16301:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16302:         $credits) = @_;
1.626     raeburn  16303:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16304:     if ($context eq 'auto') {
                   16305:         $linefeed = "\n";
                   16306:     } else {
                   16307:         $linefeed = '<br />'."\n";
                   16308:     }
1.443     albertel 16309:     if (defined($one) && defined($two)) {
                   16310:         my $cid=$one.'_'.$two;
                   16311:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16312:         my $secchange = 0;
                   16313:         my $expire_role_result;
                   16314:         my $modify_section_result;
1.628     raeburn  16315:         if ($oldsec ne '-1') { 
                   16316:             if ($oldsec ne $sec) {
1.443     albertel 16317:                 $secchange = 1;
1.628     raeburn  16318:                 my $now = time;
1.443     albertel 16319:                 my $uurl='/'.$cid;
                   16320:                 $uurl=~s/\_/\//g;
                   16321:                 if ($oldsec) {
                   16322:                     $uurl.='/'.$oldsec;
                   16323:                 }
1.626     raeburn  16324:                 $oldsecurl = $uurl;
1.628     raeburn  16325:                 $expire_role_result = 
1.1075.2.161.  .14(raeb 16326:-23):                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
1.628     raeburn  16327:                 if ($env{'request.course.sec'} ne '') { 
                   16328:                     if ($expire_role_result eq 'refused') {
                   16329:                         my @roles = ('st');
                   16330:                         my @statuses = ('previous');
                   16331:                         my @roledoms = ($one);
                   16332:                         my $withsec = 1;
                   16333:                         my %roleshash = 
                   16334:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16335:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16336:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16337:                             my ($oldstart,$oldend) = 
                   16338:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16339:                             if ($oldend > 0 && $oldend <= $now) {
                   16340:                                 $expire_role_result = 'ok';
                   16341:                             }
                   16342:                         }
                   16343:                     }
                   16344:                 }
1.443     albertel 16345:                 $result = $expire_role_result;
                   16346:             }
                   16347:         }
                   16348:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  16349:             $modify_section_result = 
                   16350:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16351:                                                            undef,undef,undef,$sec,
                   16352:                                                            $end,$start,'','',$cid,
                   16353:                                                            '',$context,$credits);
1.443     albertel 16354:             if ($modify_section_result =~ /^ok/) {
                   16355:                 if ($secchange == 1) {
1.628     raeburn  16356:                     if ($sec eq '') {
                   16357:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16358:                     } else {
                   16359:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16360:                     }
1.443     albertel 16361:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16362:                     if ($sec eq '') {
                   16363:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16364:                     } else {
                   16365:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16366:                     }
1.443     albertel 16367:                 } else {
1.628     raeburn  16368:                     if ($sec eq '') {
                   16369:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16370:                     } else {
                   16371:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16372:                     }
1.443     albertel 16373:                 }
                   16374:             } else {
1.628     raeburn  16375:                 if ($secchange) {       
                   16376:                     $$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;
                   16377:                 } else {
                   16378:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16379:                 }
1.443     albertel 16380:             }
                   16381:             $result = $modify_section_result;
                   16382:         } elsif ($secchange == 1) {
1.628     raeburn  16383:             if ($oldsec eq '') {
1.1075.2.20  raeburn  16384:                 $$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  16385:             } else {
                   16386:                 $$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;
                   16387:             }
1.626     raeburn  16388:             if ($expire_role_result eq 'refused') {
                   16389:                 my $newsecurl = '/'.$cid;
                   16390:                 $newsecurl =~ s/\_/\//g;
                   16391:                 if ($sec ne '') {
                   16392:                     $newsecurl.='/'.$sec;
                   16393:                 }
                   16394:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16395:                     if ($sec eq '') {
                   16396:                         $$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;
                   16397:                     } else {
                   16398:                         $$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;
                   16399:                     }
                   16400:                 }
                   16401:             }
1.443     albertel 16402:         }
                   16403:     } else {
1.626     raeburn  16404:         $$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 16405:         $result = "error: incomplete course id\n";
                   16406:     }
                   16407:     return $result;
                   16408: }
                   16409: 
1.1075.2.25  raeburn  16410: sub show_role_extent {
                   16411:     my ($scope,$context,$role) = @_;
                   16412:     $scope =~ s{^/}{};
                   16413:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16414:     push(@courseroles,'co');
                   16415:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16416:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16417:         $scope =~ s{/}{_};
                   16418:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16419:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16420:         my ($audom,$auname) = split(/\//,$scope);
                   16421:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16422:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16423:     } else {
                   16424:         $scope =~ s{/$}{};
                   16425:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16426:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16427:     }
                   16428: }
                   16429: 
1.443     albertel 16430: ############################################################
                   16431: ############################################################
                   16432: 
1.566     albertel 16433: sub check_clone {
1.578     raeburn  16434:     my ($args,$linefeed) = @_;
1.566     albertel 16435:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16436:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16437:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 16438:21):     my $clonetitle;
                   16439:21):     my @clonemsg;
1.566     albertel 16440:     my $can_clone = 0;
1.944     raeburn  16441:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16442:     if ($lctype ne 'community') {
                   16443:         $lctype = 'course';
                   16444:     }
1.566     albertel 16445:     if ($clonehome eq 'no_host') {
1.944     raeburn  16446:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16447:21):             push(@clonemsg,({
                   16448:21):                               mt => 'No new community created.',
                   16449:21):                               args => [],
                   16450:21):                             },
                   16451:21):                             {
                   16452:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16453:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16454:21):                             }));
1.908     raeburn  16455:         } else {
1.1075.2.161.  .1(raebu 16456:21):             push(@clonemsg,({
                   16457:21):                               mt => 'No new course created.',
                   16458:21):                               args => [],
                   16459:21):                             },
                   16460:21):                             {
                   16461:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16462:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16463:21):                             }));
                   16464:21):         }
1.566     albertel 16465:     } else {
                   16466: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 16467:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16468:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16469:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 16470:21):                 push(@clonemsg,({
                   16471:21):                                   mt => 'No new community created.',
                   16472:21):                                   args => [],
                   16473:21):                                 },
                   16474:21):                                 {
                   16475:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16476:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16477:21):                                 }));
                   16478:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16479:             }
                   16480:         }
1.1075.2.119  raeburn  16481: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16482:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16483: 	    $can_clone = 1;
                   16484: 	} else {
1.1075.2.95  raeburn  16485: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16486: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  16487:             if ($clonehash{'cloners'} eq '') {
                   16488:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16489:                 if ($domdefs{'canclone'}) {
                   16490:                     unless ($domdefs{'canclone'} eq 'none') {
                   16491:                         if ($domdefs{'canclone'} eq 'domain') {
                   16492:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16493:                                 $can_clone = 1;
                   16494:                             }
                   16495:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16496:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16497:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16498:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16499:                                 $can_clone = 1;
                   16500:                             }
                   16501:                         }
                   16502:                     }
1.908     raeburn  16503:                 }
1.1075.2.95  raeburn  16504:             } else {
                   16505: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16506:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16507:                     $can_clone = 1;
1.1075.2.95  raeburn  16508:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16509:                     $can_clone = 1;
1.1075.2.96  raeburn  16510:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16511:                     $can_clone = 1;
1.1075.2.95  raeburn  16512:                 }
                   16513:                 unless ($can_clone) {
1.1075.2.96  raeburn  16514:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16515:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  16516:                         my (%gotdomdefaults,%gotcodedefaults);
                   16517:                         foreach my $cloner (@cloners) {
                   16518:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16519:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16520:                                 my (%codedefaults,@code_order);
                   16521:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16522:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16523:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16524:                                     }
                   16525:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16526:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16527:                                     }
                   16528:                                 } else {
                   16529:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16530:                                                                             \%codedefaults,
                   16531:                                                                             \@code_order);
                   16532:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16533:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16534:                                 }
                   16535:                                 if (@code_order > 0) {
                   16536:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16537:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16538:                                                                                 $args->{'crscode'})) {
                   16539:                                         $can_clone = 1;
                   16540:                                         last;
                   16541:                                     }
                   16542:                                 }
                   16543:                             }
                   16544:                         }
                   16545:                     }
1.1075.2.96  raeburn  16546:                 }
                   16547:             }
                   16548:             unless ($can_clone) {
                   16549:                 my $ccrole = 'cc';
                   16550:                 if ($args->{'crstype'} eq 'Community') {
                   16551:                     $ccrole = 'co';
                   16552:                 }
                   16553:                 my %roleshash =
                   16554:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16555:                                                   $args->{'ccdomain'},
                   16556:                                                   'userroles',['active'],[$ccrole],
                   16557:                                                   [$args->{'clonedomain'}]);
                   16558:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16559:                     $can_clone = 1;
                   16560:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16561:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16562:                     $can_clone = 1;
1.1075.2.95  raeburn  16563:                 }
                   16564:             }
                   16565:             unless ($can_clone) {
                   16566:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16567:21):                     push(@clonemsg,({
                   16568:21):                                       mt => 'No new community created.',
                   16569:21):                                       args => [],
                   16570:21):                                     },
                   16571:21):                                     {
                   16572: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]).',
                   16573:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16574:21):                                     }));
1.1075.2.95  raeburn  16575:                 } else {
1.1075.2.161.  .1(raebu 16576:21):                     push(@clonemsg,({
                   16577:21):                                       mt => 'No new course created.',
                   16578:21):                                       args => [],
                   16579:21):                                     },
                   16580:21):                                     {
                   16581: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]).',
                   16582:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16583:21):                                     }));
1.578     raeburn  16584: 	        }
1.566     albertel 16585: 	    }
1.578     raeburn  16586:         }
1.566     albertel 16587:     }
1.1075.2.161.  .1(raebu 16588:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16589: }
                   16590: 
1.444     albertel 16591: sub construct_course {
1.1075.2.119  raeburn  16592:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16593:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16594:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16595:     my $linefeed =  '<br />'."\n";
                   16596:     if ($context eq 'auto') {
                   16597:         $linefeed = "\n";
                   16598:     }
1.566     albertel 16599: 
                   16600: #
                   16601: # Are we cloning?
                   16602: #
1.1075.2.161.  .1(raebu 16603:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16604:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16605:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16606:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16607:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16608: 	}
                   16609:     }
                   16610: 
1.444     albertel 16611: #
                   16612: # Open course
                   16613: #
                   16614:     my $crstype = lc($args->{'crstype'});
                   16615:     my %cenv=();
                   16616:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16617:                                              $args->{'cdescr'},
                   16618:                                              $args->{'curl'},
                   16619:                                              $args->{'course_home'},
                   16620:                                              $args->{'nonstandard'},
                   16621:                                              $args->{'crscode'},
                   16622:                                              $args->{'ccuname'}.':'.
                   16623:                                              $args->{'ccdomain'},
1.882     raeburn  16624:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16625:21):                                              $cnum,$context,$category,
                   16626:21):                                              $callercontext);
1.444     albertel 16627: 
                   16628:     # Note: The testing routines depend on this being output; see 
                   16629:     # Utils::Course. This needs to at least be output as a comment
                   16630:     # if anyone ever decides to not show this, and Utils::Course::new
                   16631:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16632:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16633:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16634:21):     } else {
                   16635:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16636:21):     }
1.943     raeburn  16637:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16638:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16639:     }
                   16640: 
1.444     albertel 16641: #
                   16642: # Check if created correctly
                   16643: #
1.479     albertel 16644:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16645:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16646:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16647:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16648:21):             $outcome .= &mt_user($user_lh,
                   16649:21):                             'Course creation failed, unrecognized course home server.');
                   16650:21):         } else {
                   16651:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16652:21):         }
                   16653:21):         $outcome .= $linefeed;
                   16654:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16655:     }
1.541     raeburn  16656:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16657: 
1.444     albertel 16658: #
1.566     albertel 16659: # Do the cloning
1.1075.2.161.  .1(raebu 16660:21): #
                   16661:21):     my @clonemsg;
1.566     albertel 16662:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16663:21):         push(@clonemsg,
                   16664:21):                       {
                   16665:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16666:21):                           args => [$crstype,$clonetitle],
                   16667:21):                       });
1.566     albertel 16668: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16669: # Copy all files
1.1075.2.161.  .1(raebu 16670:21):         my @info =
                   16671:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16672:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16673:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16674:21):                                                      $args->{'tinyurls'});
                   16675:21):         if (@info) {
                   16676:21):             push(@clonemsg,@info);
                   16677:21):         }
1.444     albertel 16678: # Restore URL
1.566     albertel 16679: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16680: # Restore title
1.566     albertel 16681: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16682: # Restore creation date, creator and creation context.
                   16683:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16684:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16685:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16686: # Mark as cloned
1.566     albertel 16687: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16688: # Need to clone grading mode
                   16689:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16690:         $cenv{'grading'}=$newenv{'grading'};
                   16691: # Do not clone these environment entries
                   16692:         &Apache::lonnet::del('environment',
                   16693:                   ['default_enrollment_start_date',
                   16694:                    'default_enrollment_end_date',
                   16695:                    'question.email',
                   16696:                    'policy.email',
                   16697:                    'comment.email',
                   16698:                    'pch.users.denied',
1.725     raeburn  16699:                    'plc.users.denied',
                   16700:                    'hidefromcat',
1.1075.2.36  raeburn  16701:                    'checkforpriv',
1.1075.2.158  raeburn  16702:                    'categories'],
1.638     www      16703:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16704:         if ($args->{'textbook'}) {
                   16705:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16706:         }
1.444     albertel 16707:     }
1.566     albertel 16708: 
1.444     albertel 16709: #
                   16710: # Set environment (will override cloned, if existing)
                   16711: #
                   16712:     my @sections = ();
                   16713:     my @xlists = ();
                   16714:     if ($args->{'crstype'}) {
                   16715:         $cenv{'type'}=$args->{'crstype'};
                   16716:     }
1.1075.2.161.  .17(raeb 16717:-23):     if ($args->{'lti'}) {
                   16718:-23):         $cenv{'internal.lti'}=$args->{'lti'};
                   16719:-23):     }
1.444     albertel 16720:     if ($args->{'crsid'}) {
                   16721:         $cenv{'courseid'}=$args->{'crsid'};
                   16722:     }
                   16723:     if ($args->{'crscode'}) {
                   16724:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16725:     }
                   16726:     if ($args->{'crsquota'} ne '') {
                   16727:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16728:     } else {
                   16729:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16730:     }
                   16731:     if ($args->{'ccuname'}) {
                   16732:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16733:                                         ':'.$args->{'ccdomain'};
                   16734:     } else {
                   16735:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16736:     }
1.1075.2.31  raeburn  16737:     if ($args->{'defaultcredits'}) {
                   16738:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16739:     }
1.444     albertel 16740:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1075.2.161.  .20(raeb 16741:-23):     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 16742:     if ($args->{'crssections'}) {
                   16743:         $cenv{'internal.sectionnums'} = '';
                   16744:         if ($args->{'crssections'} =~ m/,/) {
                   16745:             @sections = split/,/,$args->{'crssections'};
                   16746:         } else {
                   16747:             $sections[0] = $args->{'crssections'};
                   16748:         }
                   16749:         if (@sections > 0) {
                   16750:             foreach my $item (@sections) {
                   16751:                 my ($sec,$gp) = split/:/,$item;
                   16752:                 my $class = $args->{'crscode'}.$sec;
                   16753:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16754:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1075.2.161.  .20(raeb 16755:-23):                 if ($addcheck eq 'ok') {
                   16756:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16757:-23):                         push(@oklcsecs,$gp);
                   16758:-23):                     }
                   16759:-23):                 } else {
1.1075.2.119  raeburn  16760:                     push(@badclasses,$class);
1.444     albertel 16761:                 }
                   16762:             }
                   16763:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16764:         }
                   16765:     }
                   16766: # do not hide course coordinator from staff listing, 
                   16767: # even if privileged
                   16768:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16769: # add course coordinator's domain to domains to check for privileged users
                   16770: # if different to course domain
                   16771:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16772:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16773:     }
1.444     albertel 16774: # add crosslistings
                   16775:     if ($args->{'crsxlist'}) {
                   16776:         $cenv{'internal.crosslistings'}='';
                   16777:         if ($args->{'crsxlist'} =~ m/,/) {
                   16778:             @xlists = split/,/,$args->{'crsxlist'};
                   16779:         } else {
                   16780:             $xlists[0] = $args->{'crsxlist'};
                   16781:         }
                   16782:         if (@xlists > 0) {
                   16783:             foreach my $item (@xlists) {
                   16784:                 my ($xl,$gp) = split/:/,$item;
                   16785:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16786:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1075.2.161.  .20(raeb 16787:-23):                 if ($addcheck eq 'ok') {
                   16788:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16789:-23):                         push(@oklcsecs,$gp);
                   16790:-23):                     }
                   16791:-23):                 } else {
1.1075.2.119  raeburn  16792:                     push(@badclasses,$xl);
1.444     albertel 16793:                 }
                   16794:             }
                   16795:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16796:         }
                   16797:     }
                   16798:     if ($args->{'autoadds'}) {
                   16799:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16800:     }
                   16801:     if ($args->{'autodrops'}) {
                   16802:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16803:     }
                   16804: # check for notification of enrollment changes
                   16805:     my @notified = ();
                   16806:     if ($args->{'notify_owner'}) {
                   16807:         if ($args->{'ccuname'} ne '') {
                   16808:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16809:         }
                   16810:     }
                   16811:     if ($args->{'notify_dc'}) {
                   16812:         if ($uname ne '') { 
1.630     raeburn  16813:             push(@notified,$uname.':'.$udom);
1.444     albertel 16814:         }
                   16815:     }
                   16816:     if (@notified > 0) {
                   16817:         my $notifylist;
                   16818:         if (@notified > 1) {
                   16819:             $notifylist = join(',',@notified);
                   16820:         } else {
                   16821:             $notifylist = $notified[0];
                   16822:         }
                   16823:         $cenv{'internal.notifylist'} = $notifylist;
                   16824:     }
                   16825:     if (@badclasses > 0) {
                   16826:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16827:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16828:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16829:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16830:         );
1.1075.2.119  raeburn  16831:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16832:                            &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  16833:         if ($context eq 'auto') {
                   16834:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16835:         } else {
1.566     albertel 16836:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16837:         }
                   16838:         foreach my $item (@badclasses) {
1.541     raeburn  16839:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16840:                 $outcome .= " - $item\n";
1.541     raeburn  16841:             } else {
1.1075.2.119  raeburn  16842:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16843:             }
1.1075.2.119  raeburn  16844:         }
                   16845:         if ($context eq 'auto') {
                   16846:             $outcome .= $linefeed;
                   16847:         } else {
                   16848:             $outcome .= "</ul><br /><br /></div>\n";
                   16849:         }
1.444     albertel 16850:     }
                   16851:     if ($args->{'no_end_date'}) {
                   16852:         $args->{'endaccess'} = 0;
                   16853:     }
1.1075.2.161.  .20(raeb 16854:-23): #  If an official course with institutional sections is created by cloning
                   16855:-23): #  an existing course, section-specific hiding of course totals in student's
                   16856:-23): #  view of grades as copied from cloned course, will be checked for valid
                   16857:-23): #  sections.
                   16858:-23):     if (($can_clone && $cloneid) &&
                   16859:-23):         ($cenv{'internal.coursecode'} ne '') &&
                   16860:-23):         ($cenv{'grading'} eq 'standard') &&
                   16861:-23):         ($cenv{'hidetotals'} ne '') &&
                   16862:-23):         ($cenv{'hidetotals'} ne 'all')) {
                   16863:-23):         my @hidesecs;
                   16864:-23):         my $deletehidetotals;
                   16865:-23):         if (@oklcsecs) {
                   16866:-23):             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   16867:-23):                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   16868:-23):                     push(@hidesecs,$sec);
                   16869:-23):                 }
                   16870:-23):             }
                   16871:-23):             if (@hidesecs) {
                   16872:-23):                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   16873:-23):             } else {
                   16874:-23):                 $deletehidetotals = 1;
                   16875:-23):             }
                   16876:-23):         } else {
                   16877:-23):             $deletehidetotals = 1;
                   16878:-23):         }
                   16879:-23):         if ($deletehidetotals) {
                   16880:-23):             delete($cenv{'hidetotals'});
                   16881:-23):             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   16882:-23):         }
                   16883:-23):     }
1.444     albertel 16884:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16885:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16886:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16887:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16888:     if ($args->{'showphotos'}) {
                   16889:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16890:     }
                   16891:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16892:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16893:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16894:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16895:             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'); 
                   16896:             if ($context eq 'auto') {
                   16897:                 $outcome .= $krb_msg;
                   16898:             } else {
1.566     albertel 16899:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16900:             }
                   16901:             $outcome .= $linefeed;
1.444     albertel 16902:         }
                   16903:     }
                   16904:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16905:        if ($args->{'setpolicy'}) {
                   16906:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16907:        }
                   16908:        if ($args->{'setcontent'}) {
                   16909:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16910:        }
1.1075.2.110  raeburn  16911:        if ($args->{'setcomment'}) {
                   16912:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16913:        }
1.444     albertel 16914:     }
                   16915:     if ($args->{'reshome'}) {
                   16916: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16917: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16918:     }
                   16919: #
                   16920: # course has keyed access
                   16921: #
                   16922:     if ($args->{'setkeys'}) {
                   16923:        $cenv{'keyaccess'}='yes';
                   16924:     }
                   16925: # if specified, key authority is not course, but user
                   16926: # only active if keyaccess is yes
                   16927:     if ($args->{'keyauth'}) {
1.487     albertel 16928: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16929: 	$user = &LONCAPA::clean_username($user);
                   16930: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16931: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16932: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16933: 	}
                   16934:     }
                   16935: 
1.1075.2.59  raeburn  16936: #
                   16937: #  generate and store uniquecode (available to course requester), if course should have one.
                   16938: #
                   16939:     if ($args->{'uniquecode'}) {
                   16940:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16941:         if ($code) {
                   16942:             $cenv{'internal.uniquecode'} = $code;
                   16943:             my %crsinfo =
                   16944:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16945:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16946:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16947:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16948:             }
                   16949:             if (ref($coderef)) {
                   16950:                 $$coderef = $code;
                   16951:             }
                   16952:         }
                   16953:     }
                   16954: 
1.444     albertel 16955:     if ($args->{'disresdis'}) {
                   16956:         $cenv{'pch.roles.denied'}='st';
                   16957:     }
                   16958:     if ($args->{'disablechat'}) {
                   16959:         $cenv{'plc.roles.denied'}='st';
                   16960:     }
                   16961: 
                   16962:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16963:     # course
                   16964:     $cenv{'course.helper.not.run'} = 1;
                   16965:     #
                   16966:     # Use new Randomseed
                   16967:     #
                   16968:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16969:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16970:     #
                   16971:     # The encryption code and receipt prefix for this course
                   16972:     #
                   16973:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16974:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16975:     #
                   16976:     # By default, use standard grading
                   16977:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16978: 
1.541     raeburn  16979:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16980:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16981: #
                   16982: # Open all assignments
                   16983: #
                   16984:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16985:        my $opendate = time;
                   16986:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16987:            $opendate = $args->{'openallfrom'};
                   16988:        }
1.444     albertel 16989:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16990:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16991:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16992:        $outcome .= &mt('All assignments open starting [_1]',
                   16993:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16994:                    &Apache::lonnet::cput
                   16995:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16996:    }
                   16997: #
                   16998: # Set first page
                   16999: #
                   17000:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17001: 	    || ($cloneid)) {
                   17002: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17003: 
                   17004: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17005:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17006: 
1.444     albertel 17007:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17008:         my $title; my $url;
                   17009:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17010: 	    $title=&mt('Syllabus');
1.444     albertel 17011:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17012:         } else {
1.963     raeburn  17013:             $title=&mt('Table of Contents');
1.444     albertel 17014:             $url='/adm/navmaps';
                   17015:         }
1.445     albertel 17016: 
                   17017:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17018: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17019: 
                   17020: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17021:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17022:     }
1.566     albertel 17023: 
1.1075.2.161.  .1(raebu 17024:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 17025: }
                   17026: 
1.1075.2.59  raeburn  17027: sub make_unique_code {
                   17028:     my ($cdom,$cnum) = @_;
                   17029:     # get lock on uniquecodes db
                   17030:     my $lockhash = {
                   17031:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17032:                                                   ':'.$env{'user.domain'},
                   17033:                    };
                   17034:     my $tries = 0;
                   17035:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17036:     my ($code,$error);
                   17037: 
                   17038:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17039:         $tries ++;
                   17040:         sleep 1;
                   17041:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17042:     }
                   17043:     if ($gotlock eq 'ok') {
                   17044:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17045:         my $gotcode;
                   17046:         my $attempts = 0;
                   17047:         while ((!$gotcode) && ($attempts < 100)) {
                   17048:             $code = &generate_code();
                   17049:             if (!exists($currcodes{$code})) {
                   17050:                 $gotcode = 1;
                   17051:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17052:                     $error = 'nostore';
                   17053:                 }
                   17054:             }
                   17055:             $attempts ++;
                   17056:         }
                   17057:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17058:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17059:     } else {
                   17060:         $error = 'nolock';
                   17061:     }
                   17062:     return ($code,$error);
                   17063: }
                   17064: 
                   17065: sub generate_code {
                   17066:     my $code;
                   17067:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17068:     for (my $i=0; $i<6; $i++) {
                   17069:         my $lettnum = int (rand 2);
                   17070:         my $item = '';
                   17071:         if ($lettnum) {
                   17072:             $item = $letts[int( rand(18) )];
                   17073:         } else {
                   17074:             $item = 1+int( rand(8) );
                   17075:         }
                   17076:         $code .= $item;
                   17077:     }
                   17078:     return $code;
                   17079: }
                   17080: 
1.444     albertel 17081: ############################################################
                   17082: ############################################################
                   17083: 
1.953     droeschl 17084: #SD
                   17085: # only Community and Course, or anything else?
1.378     raeburn  17086: sub course_type {
                   17087:     my ($cid) = @_;
                   17088:     if (!defined($cid)) {
                   17089:         $cid = $env{'request.course.id'};
                   17090:     }
1.404     albertel 17091:     if (defined($env{'course.'.$cid.'.type'})) {
                   17092:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17093:     } else {
                   17094:         return 'Course';
1.377     raeburn  17095:     }
                   17096: }
1.156     albertel 17097: 
1.406     raeburn  17098: sub group_term {
                   17099:     my $crstype = &course_type();
                   17100:     my %names = (
                   17101:                   'Course' => 'group',
1.865     raeburn  17102:                   'Community' => 'group',
1.406     raeburn  17103:                 );
                   17104:     return $names{$crstype};
                   17105: }
                   17106: 
1.902     raeburn  17107: sub course_types {
1.1075.2.161.  .17(raeb 17108:-23):     my @types = ('official','unofficial','community','textbook','lti');
1.902     raeburn  17109:     my %typename = (
                   17110:                          official   => 'Official course',
                   17111:                          unofficial => 'Unofficial course',
                   17112:                          community  => 'Community',
1.1075.2.59  raeburn  17113:                          textbook   => 'Textbook course',
1.1075.2.161.  .17(raeb 17114:-23):                          lti        => 'LTI provider',
1.902     raeburn  17115:                    );
                   17116:     return (\@types,\%typename);
                   17117: }
                   17118: 
1.156     albertel 17119: sub icon {
                   17120:     my ($file)=@_;
1.505     albertel 17121:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17122:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17123:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17124:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17125: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17126: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17127: 	            $curfext.".gif") {
                   17128: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17129: 		$curfext.".gif";
                   17130: 	}
                   17131:     }
1.249     albertel 17132:     return &lonhttpdurl($iconname);
1.154     albertel 17133: } 
1.84      albertel 17134: 
1.575     albertel 17135: sub lonhttpdurl {
1.692     www      17136: #
                   17137: # Had been used for "small fry" static images on separate port 8080.
                   17138: # Modify here if lightweight http functionality desired again.
                   17139: # Currently eliminated due to increasing firewall issues.
                   17140: #
1.575     albertel 17141:     my ($url)=@_;
1.692     www      17142:     return $url;
1.215     albertel 17143: }
                   17144: 
1.213     albertel 17145: sub connection_aborted {
                   17146:     my ($r)=@_;
                   17147:     $r->print(" ");$r->rflush();
                   17148:     my $c = $r->connection;
                   17149:     return $c->aborted();
                   17150: }
                   17151: 
1.221     foxr     17152: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17153: #    strings as 'strings'.
                   17154: sub escape_single {
1.221     foxr     17155:     my ($input) = @_;
1.223     albertel 17156:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17157:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17158:     return $input;
                   17159: }
1.223     albertel 17160: 
1.222     foxr     17161: #  Same as escape_single, but escape's "'s  This 
                   17162: #  can be used for  "strings"
                   17163: sub escape_double {
                   17164:     my ($input) = @_;
                   17165:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17166:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17167:     return $input;
                   17168: }
1.223     albertel 17169:  
1.222     foxr     17170: #   Escapes the last element of a full URL.
                   17171: sub escape_url {
                   17172:     my ($url)   = @_;
1.238     raeburn  17173:     my @urlslices = split(/\//, $url,-1);
1.369     www      17174:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  17175:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17176: }
1.462     albertel 17177: 
1.820     raeburn  17178: sub compare_arrays {
                   17179:     my ($arrayref1,$arrayref2) = @_;
                   17180:     my (@difference,%count);
                   17181:     @difference = ();
                   17182:     %count = ();
                   17183:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17184:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17185:         foreach my $element (keys(%count)) {
                   17186:             if ($count{$element} == 1) {
                   17187:                 push(@difference,$element);
                   17188:             }
                   17189:         }
                   17190:     }
                   17191:     return @difference;
                   17192: }
                   17193: 
1.1075.2.152  raeburn  17194: sub lon_status_items {
                   17195:     my %defaults = (
                   17196:                      E         => 100,
                   17197:                      W         => 4,
                   17198:                      N         => 1,
                   17199:                      U         => 5,
                   17200:                      threshold => 200,
                   17201:                      sysmail   => 2500,
                   17202:                    );
                   17203:     my %names = (
                   17204:                    E => 'Errors',
                   17205:                    W => 'Warnings',
                   17206:                    N => 'Notices',
                   17207:                    U => 'Unsent',
                   17208:                 );
                   17209:     return (\%defaults,\%names);
                   17210: }
                   17211: 
1.817     bisitz   17212: # -------------------------------------------------------- Initialize user login
1.462     albertel 17213: sub init_user_environment {
1.463     albertel 17214:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17215:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17216: 
                   17217:     my $public=($username eq 'public' && $domain eq 'public');
                   17218: 
                   17219: # See if old ID present, if so, remove
                   17220: 
1.1075.2.161.  .22(raeb 17221:-24):     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17222:-24):         $coauthorenv);
1.462     albertel 17223:     my $now=time;
                   17224: 
                   17225:     if ($public) {
                   17226: 	my $max_public=100;
                   17227: 	my $oldest;
                   17228: 	my $oldest_time=0;
                   17229: 	for(my $next=1;$next<=$max_public;$next++) {
                   17230: 	    if (-e $lonids."/publicuser_$next.id") {
                   17231: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17232: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17233: 		    $oldest_time=$mtime;
                   17234: 		    $oldest=$next;
                   17235: 		}
                   17236: 	    } else {
                   17237: 		$cookie="publicuser_$next";
                   17238: 		last;
                   17239: 	    }
                   17240: 	}
                   17241: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17242:     } else {
1.463     albertel 17243: 	# if this isn't a robot, kill any existing non-robot sessions
                   17244: 	if (!$args->{'robot'}) {
                   17245: 	    opendir(DIR,$lonids);
                   17246: 	    while ($filename=readdir(DIR)) {
                   17247: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  17248:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17249:                             &GDBM_READER(),0640)) {
                   17250:                         my $linkedfile;
                   17251:                         if (exists($oldenv{'user.linkedenv'})) {
                   17252:                             $linkedfile = $oldenv{'user.linkedenv'};
                   17253:                         }
                   17254:                         untie(%oldenv);
                   17255:                         if (unlink("$lonids/$filename")) {
                   17256:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17257:                                 if (-l "$lonids/$linkedfile.id") {
                   17258:                                     unlink("$lonids/$linkedfile.id");
                   17259:                                 }
                   17260:                             }
                   17261:                         }
                   17262:                     } else {
                   17263:                         unlink($lonids.'/'.$filename);
                   17264:                     }
1.463     albertel 17265: 		}
1.462     albertel 17266: 	    }
1.463     albertel 17267: 	    closedir(DIR);
1.1075.2.84  raeburn  17268: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17269:             my $namespace = 'nohist_courseeditor';
                   17270:             my $lockingkey = 'paste'."\0".'locked_num';
                   17271:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17272:                                                 $domain,$username);
                   17273:             if (exists($lockhash{$lockingkey})) {
                   17274:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17275:                 unless ($delresult eq 'ok') {
                   17276:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17277:                 }
                   17278:             }
1.462     albertel 17279: 	}
                   17280: # Give them a new cookie
1.463     albertel 17281: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17282: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17283: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17284:     
                   17285: # Initialize roles
                   17286: 
1.1075.2.161.  .22(raeb 17287:-24): 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17288:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17289:     }
                   17290: # ------------------------------------ Check browser type and MathML capability
                   17291: 
1.1075.2.77  raeburn  17292:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17293:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17294: 
                   17295: # ------------------------------------------------------------- Get environment
                   17296: 
                   17297:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17298:     my ($tmp) = keys(%userenv);
                   17299:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   17300:     } else {
                   17301: 	undef(%userenv);
                   17302:     }
                   17303:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17304: 	$form->{'interface'}=$userenv{'interface'};
                   17305:     }
                   17306:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17307: 
                   17308: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17309:     foreach my $option ('interface','localpath','localres') {
                   17310:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17311:     }
                   17312: # --------------------------------------------------------- Write first profile
                   17313: 
                   17314:     {
1.1075.2.150  raeburn  17315:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 17316: 	my %initial_env = 
                   17317: 	    ("user.name"          => $username,
                   17318: 	     "user.domain"        => $domain,
                   17319: 	     "user.home"          => $authhost,
                   17320: 	     "browser.type"       => $clientbrowser,
                   17321: 	     "browser.version"    => $clientversion,
                   17322: 	     "browser.mathml"     => $clientmathml,
                   17323: 	     "browser.unicode"    => $clientunicode,
                   17324: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  17325:              "browser.mobile"     => $clientmobile,
                   17326:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  17327:              "browser.osversion"  => $clientosversion,
1.462     albertel 17328: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17329: 	     "request.course.fn"  => '',
                   17330: 	     "request.course.uri" => '',
                   17331: 	     "request.course.sec" => '',
                   17332: 	     "request.role"       => 'cm',
                   17333: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  17334: 	     "request.host"       => $ip,);
1.462     albertel 17335: 
                   17336:         if ($form->{'localpath'}) {
                   17337: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17338: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17339:         }
                   17340: 	
                   17341: 	if ($form->{'interface'}) {
                   17342: 	    $form->{'interface'}=~s/\W//gs;
                   17343: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17344: 	    $env{'browser.interface'}=$form->{'interface'};
                   17345: 	}
                   17346: 
1.1075.2.54  raeburn  17347:         if ($form->{'iptoken'}) {
                   17348:             my $lonhost = $r->dir_config('lonHostID');
                   17349:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17350:             $env{'user.noloadbalance'} = $lonhost;
                   17351:         }
                   17352: 
1.1075.2.120  raeburn  17353:         if ($form->{'noloadbalance'}) {
                   17354:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17355:             my $hosthere = $form->{'noloadbalance'};
                   17356:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17357:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17358:                 $env{'user.noloadbalance'} = $hosthere;
                   17359:             }
                   17360:         }
                   17361: 
1.1016    raeburn  17362:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  17363:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17364:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  17365: 
1.1075.2.161.  .28(raeb 17366:-24):             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   17367:-24):                 $userenv{'availabletools.'.$tool} =
1.1075.2.125  raeburn  17368:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17369:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17370:             }
1.724     raeburn  17371: 
1.1075.2.161.  .17(raeb 17372:-23):             foreach my $crstype ('official','unofficial','community','textbook','lti') {
1.1075.2.125  raeburn  17373:                 $userenv{'canrequest.'.$crstype} =
                   17374:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17375:                                                       'reload','requestcourses',
                   17376:                                                       \%userenv,\%domdef,\%is_adv);
                   17377:             }
1.765     raeburn  17378: 
1.1075.2.161.  .21(raeb 17379:-24):             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   17380:-24):                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   17381:-24):                 if ($userenv{'authoreditors'}) {
                   17382:-24):                     $userenv{'editors'} = $userenv{'authoreditors'};
                   17383:-24):                 } elsif ($domdef{'editors'} ne '') {
                   17384:-24):                     $userenv{'editors'} = $domdef{'editors'};
                   17385:-24):                 } else {
                   17386:-24):                     $userenv{'editors'} = 'edit,xml';
                   17387:-24):                 }
          .25(raeb 17388:-24):                 if ($userenv{'authorarchive'}) {
                   17389:-24):                     $userenv{'canarchive'} = 1;
                   17390:-24):                 } elsif (($userenv{'authorarchive'} eq '') &&
                   17391:-24):                          ($domdef{'archive'})) {
                   17392:-24):                     $userenv{'canarchive'} = 1;
                   17393:-24):                 }
          .21(raeb 17394:-24):             }
                   17395:-24): 
1.1075.2.125  raeburn  17396:             $userenv{'canrequest.author'} =
                   17397:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17398:                                                   'reload','requestauthor',
                   17399:                                                   \%userenv,\%domdef,\%is_adv);
                   17400:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17401:                                                  $domain,$username);
                   17402:             my $reqstatus = $reqauthor{'author_status'};
                   17403:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   17404:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17405:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17406:                                                       $reqauthor{'author'}{'timestamp'};
                   17407:                 }
1.1075.2.14  raeburn  17408:             }
                   17409:         }
                   17410: 
1.462     albertel 17411: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17412: 
1.462     albertel 17413: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17414: 		 &GDBM_WRCREAT(),0640)) {
                   17415: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17416: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17417: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17418:             if (ref($firstaccenv) eq 'HASH') {
                   17419:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17420:             }
                   17421:             if (ref($timerintenv) eq 'HASH') {
                   17422:                 &_add_to_env(\%disk_env,$timerintenv);
                   17423:             }
1.1075.2.161.  .22(raeb 17424:-24):             if (ref($coauthorenv) eq 'HASH') {
                   17425:-24):                 if (keys(%{$coauthorenv})) {
                   17426:-24):                     &_add_to_env(\%disk_env,$coauthorenv);
                   17427:-24):                 }
                   17428:-24):             }
1.463     albertel 17429: 	    if (ref($args->{'extra_env'})) {
                   17430: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17431: 	    }
1.462     albertel 17432: 	    untie(%disk_env);
                   17433: 	} else {
1.705     tempelho 17434: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17435: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17436: 	    return 'error: '.$!;
                   17437: 	}
                   17438:     }
                   17439:     $env{'request.role'}='cm';
                   17440:     $env{'request.role.adv'}=$env{'user.adv'};
                   17441:     $env{'browser.type'}=$clientbrowser;
                   17442: 
                   17443:     return $cookie;
                   17444: 
                   17445: }
                   17446: 
                   17447: sub _add_to_env {
                   17448:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17449:     if (ref($env_data) eq 'HASH') {
                   17450:         while (my ($key,$value) = each(%$env_data)) {
                   17451: 	    $idf->{$prefix.$key} = $value;
                   17452: 	    $env{$prefix.$key}   = $value;
                   17453:         }
1.462     albertel 17454:     }
                   17455: }
                   17456: 
1.685     tempelho 17457: # --- Get the symbolic name of a problem and the url
                   17458: sub get_symb {
                   17459:     my ($request,$silent) = @_;
1.726     raeburn  17460:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17461:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17462:     if ($symb eq '') {
                   17463:         if (!$silent) {
1.1071    raeburn  17464:             if (ref($request)) { 
                   17465:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17466:             }
1.685     tempelho 17467:             return ();
                   17468:         }
                   17469:     }
                   17470:     &Apache::lonenc::check_decrypt(\$symb);
                   17471:     return ($symb);
                   17472: }
                   17473: 
                   17474: # --------------------------------------------------------------Get annotation
                   17475: 
                   17476: sub get_annotation {
                   17477:     my ($symb,$enc) = @_;
                   17478: 
                   17479:     my $key = $symb;
                   17480:     if (!$enc) {
                   17481:         $key =
                   17482:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17483:     }
                   17484:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17485:     return $annotation{$key};
                   17486: }
                   17487: 
                   17488: sub clean_symb {
1.731     raeburn  17489:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17490: 
                   17491:     &Apache::lonenc::check_decrypt(\$symb);
                   17492:     my $enc = $env{'request.enc'};
1.731     raeburn  17493:     if ($delete_enc) {
1.730     raeburn  17494:         delete($env{'request.enc'});
                   17495:     }
1.685     tempelho 17496: 
                   17497:     return ($symb,$enc);
                   17498: }
1.462     albertel 17499: 
1.1075.2.69  raeburn  17500: ############################################################
                   17501: ############################################################
                   17502: 
                   17503: =pod
                   17504: 
                   17505: =head1 Routines for building display used to search for courses
                   17506: 
                   17507: 
                   17508: =over 4
                   17509: 
                   17510: =item * &build_filters()
                   17511: 
                   17512: Create markup for a table used to set filters to use when selecting
                   17513: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17514: and quotacheck.pl
                   17515: 
                   17516: 
                   17517: Inputs:
                   17518: 
                   17519: filterlist - anonymous array of fields to include as potential filters
                   17520: 
                   17521: crstype - course type
                   17522: 
                   17523: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17524:               to pop-open a course selector (will contain "extra element").
                   17525: 
                   17526: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17527: 
                   17528: filter - anonymous hash of criteria and their values
                   17529: 
                   17530: action - form action
                   17531: 
                   17532: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17533: 
                   17534: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   17535: 
                   17536: cloneruname - username of owner of new course who wants to clone
                   17537: 
                   17538: clonerudom - domain of owner of new course who wants to clone
                   17539: 
                   17540: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   17541: 
                   17542: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17543: 
                   17544: codedom - domain
                   17545: 
                   17546: formname - value of form element named "form".
                   17547: 
                   17548: fixeddom - domain, if fixed.
                   17549: 
                   17550: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   17551: 
                   17552: cnameelement - name of form element in form on opener page which will receive title of selected course
                   17553: 
                   17554: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17555: 
                   17556: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17557: 
                   17558: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17559: 
                   17560: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17561: 
                   17562: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17563: 
                   17564: 
                   17565: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17566: 
                   17567: 
                   17568: Side Effects: None
                   17569: 
                   17570: =cut
                   17571: 
                   17572: # ---------------------------------------------- search for courses based on last activity etc.
                   17573: 
                   17574: sub build_filters {
                   17575:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17576:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17577:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17578:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17579:         $clonetext,$clonewarning) = @_;
                   17580:     my ($list,$jscript);
                   17581:     my $onchange = 'javascript:updateFilters(this)';
                   17582:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17583:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17584:         $typeselectform,$instcodetitle);
                   17585:     if ($formname eq '') {
                   17586:         $formname = $caller;
                   17587:     }
                   17588:     foreach my $item (@{$filterlist}) {
                   17589:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17590:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17591:             if ($item eq 'domainfilter') {
                   17592:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17593:             } elsif ($item eq 'coursefilter') {
                   17594:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17595:             } elsif ($item eq 'ownerfilter') {
                   17596:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17597:             } elsif ($item eq 'ownerdomfilter') {
                   17598:                 $filter->{'ownerdomfilter'} =
                   17599:                     &LONCAPA::clean_domain($filter->{$item});
                   17600:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17601:                                                        'ownerdomfilter',1);
                   17602:             } elsif ($item eq 'personfilter') {
                   17603:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17604:             } elsif ($item eq 'persondomfilter') {
                   17605:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17606:                                                         'persondomfilter',1);
                   17607:             } else {
                   17608:                 $filter->{$item} =~ s/\W//g;
                   17609:             }
                   17610:             if (!$filter->{$item}) {
                   17611:                 $filter->{$item} = '';
                   17612:             }
                   17613:         }
                   17614:         if ($item eq 'domainfilter') {
                   17615:             my $allow_blank = 1;
                   17616:             if ($formname eq 'portform') {
                   17617:                 $allow_blank=0;
                   17618:             } elsif ($formname eq 'studentform') {
                   17619:                 $allow_blank=0;
                   17620:             }
                   17621:             if ($fixeddom) {
                   17622:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17623:                                     ' value="'.$codedom.'" />'.
                   17624:                                     &Apache::lonnet::domain($codedom,'description');
                   17625:             } else {
                   17626:                 $domainselectform = &select_dom_form($filter->{$item},
                   17627:                                                      'domainfilter',
                   17628:                                                       $allow_blank,'',$onchange);
                   17629:             }
                   17630:         } else {
                   17631:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17632:         }
                   17633:     }
                   17634: 
                   17635:     # last course activity filter and selection
                   17636:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17637: 
                   17638:     # course created filter and selection
                   17639:     if (exists($filter->{'createdfilter'})) {
                   17640:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17641:     }
                   17642: 
                   17643:     my %lt = &Apache::lonlocal::texthash(
                   17644:                 'cac' => "$crstype Activity",
                   17645:                 'ccr' => "$crstype Created",
                   17646:                 'cde' => "$crstype Title",
                   17647:                 'cdo' => "$crstype Domain",
                   17648:                 'ins' => 'Institutional Code',
                   17649:                 'inc' => 'Institutional Categorization',
                   17650:                 'cow' => "$crstype Owner/Co-owner",
                   17651:                 'cop' => "$crstype Personnel Includes",
                   17652:                 'cog' => 'Type',
                   17653:              );
                   17654: 
                   17655:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17656:         my $typeval = 'Course';
                   17657:         if ($crstype eq 'Community') {
                   17658:             $typeval = 'Community';
                   17659:         }
                   17660:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17661:     } else {
                   17662:         $typeselectform =  '<select name="type" size="1"';
                   17663:         if ($onchange) {
                   17664:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17665:         }
                   17666:         $typeselectform .= '>'."\n";
                   17667:         foreach my $posstype ('Course','Community') {
                   17668:             $typeselectform.='<option value="'.$posstype.'"'.
                   17669:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17670:         }
                   17671:         $typeselectform.="</select>";
                   17672:     }
                   17673: 
                   17674:     my ($cloneableonlyform,$cloneabletitle);
                   17675:     if (exists($filter->{'cloneableonly'})) {
                   17676:         my $cloneableon = '';
                   17677:         my $cloneableoff = ' checked="checked"';
                   17678:         if ($filter->{'cloneableonly'}) {
                   17679:             $cloneableon = $cloneableoff;
                   17680:             $cloneableoff = '';
                   17681:         }
                   17682:         $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>';
                   17683:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17684:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17685:         } else {
                   17686:             $cloneabletitle = &mt('Cloneable by you');
                   17687:         }
                   17688:     }
                   17689:     my $officialjs;
                   17690:     if ($crstype eq 'Course') {
                   17691:         if (exists($filter->{'instcodefilter'})) {
                   17692: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17693: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17694:             if ($codedom) {
                   17695:                 $officialjs = 1;
                   17696:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17697:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17698:                                                                   $officialjs,$codetitlesref);
                   17699:                 if ($jscript) {
                   17700:                     $jscript = '<script type="text/javascript">'."\n".
                   17701:                                '// <![CDATA['."\n".
                   17702:                                $jscript."\n".
                   17703:                                '// ]]>'."\n".
                   17704:                                '</script>'."\n";
                   17705:                 }
                   17706:             }
                   17707:             if ($instcodeform eq '') {
                   17708:                 $instcodeform =
                   17709:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17710:                     $list->{'instcodefilter'}.'" />';
                   17711:                 $instcodetitle = $lt{'ins'};
                   17712:             } else {
                   17713:                 $instcodetitle = $lt{'inc'};
                   17714:             }
                   17715:             if ($fixeddom) {
                   17716:                 $instcodetitle .= '<br />('.$codedom.')';
                   17717:             }
                   17718:         }
                   17719:     }
                   17720:     my $output = qq|
                   17721: <form method="post" name="filterpicker" action="$action">
                   17722: <input type="hidden" name="form" value="$formname" />
                   17723: |;
                   17724:     if ($formname eq 'modifycourse') {
                   17725:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17726:                    '<input type="hidden" name="prevphase" value="'.
                   17727:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17728:     } elsif ($formname eq 'quotacheck') {
                   17729:         $output .= qq|
                   17730: <input type="hidden" name="sortby" value="" />
                   17731: <input type="hidden" name="sortorder" value="" />
                   17732: |;
                   17733:     } else {
1.1075.2.69  raeburn  17734:         my $name_input;
                   17735:         if ($cnameelement ne '') {
                   17736:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17737:                           $cnameelement.'" />';
                   17738:         }
                   17739:         $output .= qq|
                   17740: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17741: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17742: $name_input
                   17743: $roleelement
                   17744: $multelement
                   17745: $typeelement
                   17746: |;
                   17747:         if ($formname eq 'portform') {
                   17748:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17749:         }
                   17750:     }
                   17751:     if ($fixeddom) {
                   17752:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17753:     }
                   17754:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17755:     if ($sincefilterform) {
                   17756:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17757:                   .$sincefilterform
                   17758:                   .&Apache::lonhtmlcommon::row_closure();
                   17759:     }
                   17760:     if ($createdfilterform) {
                   17761:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17762:                   .$createdfilterform
                   17763:                   .&Apache::lonhtmlcommon::row_closure();
                   17764:     }
                   17765:     if ($domainselectform) {
                   17766:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17767:                   .$domainselectform
                   17768:                   .&Apache::lonhtmlcommon::row_closure();
                   17769:     }
                   17770:     if ($typeselectform) {
                   17771:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17772:             $output .= $typeselectform;
                   17773:         } else {
                   17774:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17775:                       .$typeselectform
                   17776:                       .&Apache::lonhtmlcommon::row_closure();
                   17777:         }
                   17778:     }
                   17779:     if ($instcodeform) {
                   17780:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17781:                   .$instcodeform
                   17782:                   .&Apache::lonhtmlcommon::row_closure();
                   17783:     }
                   17784:     if (exists($filter->{'ownerfilter'})) {
                   17785:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17786:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17787:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17788:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17789:                    $ownerdomselectform.'</td></tr></table>'.
                   17790:                    &Apache::lonhtmlcommon::row_closure();
                   17791:     }
                   17792:     if (exists($filter->{'personfilter'})) {
                   17793:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17794:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17795:                    '<input type="text" name="personfilter" size="20" value="'.
                   17796:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17797:                    $persondomselectform.'</td></tr></table>'.
                   17798:                    &Apache::lonhtmlcommon::row_closure();
                   17799:     }
                   17800:     if (exists($filter->{'coursefilter'})) {
                   17801:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17802:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17803:                   .$list->{'coursefilter'}.'" />'
                   17804:                   .&Apache::lonhtmlcommon::row_closure();
                   17805:     }
                   17806:     if ($cloneableonlyform) {
                   17807:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17808:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17809:     }
                   17810:     if (exists($filter->{'descriptfilter'})) {
                   17811:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17812:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17813:                   .$list->{'descriptfilter'}.'" />'
                   17814:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17815:     }
                   17816:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17817:                '<input type="hidden" name="updater" value="" />'."\n".
                   17818:                '<input type="submit" name="gosearch" value="'.
                   17819:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17820:     return $jscript.$clonewarning.$output;
                   17821: }
                   17822: 
                   17823: =pod
                   17824: 
                   17825: =item * &timebased_select_form()
                   17826: 
                   17827: Create markup for a dropdown list used to select a time-based
                   17828: filter e.g., Course Activity, Course Created, when searching for courses
                   17829: or communities
                   17830: 
                   17831: Inputs:
                   17832: 
                   17833: item - name of form element (sincefilter or createdfilter)
                   17834: 
                   17835: filter - anonymous hash of criteria and their values
                   17836: 
                   17837: Returns: HTML for a select box contained a blank, then six time selections,
                   17838:          with value set in incoming form variables currently selected.
                   17839: 
                   17840: Side Effects: None
                   17841: 
                   17842: =cut
                   17843: 
                   17844: sub timebased_select_form {
                   17845:     my ($item,$filter) = @_;
                   17846:     if (ref($filter) eq 'HASH') {
                   17847:         $filter->{$item} =~ s/[^\d-]//g;
                   17848:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17849:         return &select_form(
                   17850:                             $filter->{$item},
                   17851:                             $item,
                   17852:                             {      '-1' => '',
                   17853:                                 '86400' => &mt('today'),
                   17854:                                '604800' => &mt('last week'),
                   17855:                               '2592000' => &mt('last month'),
                   17856:                               '7776000' => &mt('last three months'),
                   17857:                              '15552000' => &mt('last six months'),
                   17858:                              '31104000' => &mt('last year'),
                   17859:                     'select_form_order' =>
                   17860:                            ['-1','86400','604800','2592000','7776000',
                   17861:                             '15552000','31104000']});
                   17862:     }
                   17863: }
                   17864: 
                   17865: =pod
                   17866: 
                   17867: =item * &js_changer()
                   17868: 
                   17869: Create script tag containing Javascript used to submit course search form
                   17870: when course type or domain is changed, and also to hide 'Searching ...' on
                   17871: page load completion for page showing search result.
                   17872: 
                   17873: Inputs: None
                   17874: 
                   17875: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17876: 
                   17877: Side Effects: None
                   17878: 
                   17879: =cut
                   17880: 
                   17881: sub js_changer {
                   17882:     return <<ENDJS;
                   17883: <script type="text/javascript">
                   17884: // <![CDATA[
                   17885: function updateFilters(caller) {
                   17886:     if (typeof(caller) != "undefined") {
                   17887:         document.filterpicker.updater.value = caller.name;
                   17888:     }
                   17889:     document.filterpicker.submit();
                   17890: }
                   17891: 
                   17892: function hideSearching() {
                   17893:     if (document.getElementById('searching')) {
                   17894:         document.getElementById('searching').style.display = 'none';
                   17895:     }
                   17896:     return;
                   17897: }
                   17898: 
                   17899: // ]]>
                   17900: </script>
                   17901: 
                   17902: ENDJS
                   17903: }
                   17904: 
                   17905: =pod
                   17906: 
                   17907: =item * &search_courses()
                   17908: 
                   17909: Process selected filters form course search form and pass to lonnet::courseiddump
                   17910: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17911: 
                   17912: Inputs:
                   17913: 
                   17914: dom - domain being searched
                   17915: 
                   17916: type - course type ('Course' or 'Community' or '.' if any).
                   17917: 
                   17918: filter - anonymous hash of criteria and their values
                   17919: 
                   17920: numtitles - for institutional codes - number of categories
                   17921: 
                   17922: cloneruname - optional username of new course owner
                   17923: 
                   17924: clonerudom - optional domain of new course owner
                   17925: 
1.1075.2.95  raeburn  17926: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17927:             (used when DC is using course creation form)
                   17928: 
                   17929: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17930: 
1.1075.2.95  raeburn  17931: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17932:            (and so can clone automatically)
                   17933: 
                   17934: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17935: 
                   17936: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17937:               courses to clone
1.1075.2.69  raeburn  17938: 
                   17939: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17940: 
                   17941: 
                   17942: Side Effects: None
                   17943: 
                   17944: =cut
                   17945: 
                   17946: 
                   17947: sub search_courses {
1.1075.2.95  raeburn  17948:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17949:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17950:     my (%courses,%showcourses,$cloner);
                   17951:     if (($filter->{'ownerfilter'} ne '') ||
                   17952:         ($filter->{'ownerdomfilter'} ne '')) {
                   17953:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17954:                                        $filter->{'ownerdomfilter'};
                   17955:     }
                   17956:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17957:         if (!$filter->{$item}) {
                   17958:             $filter->{$item}='.';
                   17959:         }
                   17960:     }
                   17961:     my $now = time;
                   17962:     my $timefilter =
                   17963:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17964:     my ($createdbefore,$createdafter);
                   17965:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17966:         $createdbefore = $now;
                   17967:         $createdafter = $now-$filter->{'createdfilter'};
                   17968:     }
                   17969:     my ($instcodefilter,$regexpok);
                   17970:     if ($numtitles) {
                   17971:         if ($env{'form.official'} eq 'on') {
                   17972:             $instcodefilter =
                   17973:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17974:             $regexpok = 1;
                   17975:         } elsif ($env{'form.official'} eq 'off') {
                   17976:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17977:             unless ($instcodefilter eq '') {
                   17978:                 $regexpok = -1;
                   17979:             }
                   17980:         }
                   17981:     } else {
                   17982:         $instcodefilter = $filter->{'instcodefilter'};
                   17983:     }
                   17984:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17985:     if ($type eq '') { $type = '.'; }
                   17986: 
                   17987:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17988:         $cloner = $cloneruname.':'.$clonerudom;
                   17989:     }
                   17990:     %courses = &Apache::lonnet::courseiddump($dom,
                   17991:                                              $filter->{'descriptfilter'},
                   17992:                                              $timefilter,
                   17993:                                              $instcodefilter,
                   17994:                                              $filter->{'combownerfilter'},
                   17995:                                              $filter->{'coursefilter'},
                   17996:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17997:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17998:                                              $filter->{'cloneableonly'},
                   17999:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  18000:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  18001:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18002:         my $ccrole;
                   18003:         if ($type eq 'Community') {
                   18004:             $ccrole = 'co';
                   18005:         } else {
                   18006:             $ccrole = 'cc';
                   18007:         }
                   18008:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18009:                                                      $filter->{'persondomfilter'},
                   18010:                                                      'userroles',undef,
                   18011:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18012:                                                      $dom);
                   18013:         foreach my $role (keys(%rolehash)) {
                   18014:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18015:             my $cid = $cdom.'_'.$cnum;
                   18016:             if (exists($courses{$cid})) {
                   18017:                 if (ref($courses{$cid}) eq 'HASH') {
                   18018:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18019:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  18020:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  18021:                         }
                   18022:                     } else {
                   18023:                         $courses{$cid}{roles} = [$courserole];
                   18024:                     }
                   18025:                     $showcourses{$cid} = $courses{$cid};
                   18026:                 }
                   18027:             }
                   18028:         }
                   18029:         %courses = %showcourses;
                   18030:     }
                   18031:     return %courses;
                   18032: }
                   18033: 
                   18034: =pod
                   18035: 
                   18036: =back
                   18037: 
1.1075.2.88  raeburn  18038: =head1 Routines for version requirements for current course.
                   18039: 
                   18040: =over 4
                   18041: 
                   18042: =item * &check_release_required()
                   18043: 
                   18044: Compares required LON-CAPA version with version on server, and
                   18045: if required version is newer looks for a server with the required version.
                   18046: 
                   18047: Looks first at servers in user's owen domain; if none suitable, looks at
                   18048: servers in course's domain are permitted to host sessions for user's domain.
                   18049: 
                   18050: Inputs:
                   18051: 
                   18052: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18053: 
                   18054: $courseid - Course ID of current course
                   18055: 
                   18056: $rolecode - User's current role in course (for switchserver query string).
                   18057: 
                   18058: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18059: 
                   18060: 
                   18061: Returns:
                   18062: 
                   18063: $switchserver - query string tp append to /adm/switchserver call (if
                   18064:                 current server's LON-CAPA version is too old.
                   18065: 
                   18066: $warning - Message is displayed if no suitable server could be found.
                   18067: 
                   18068: =cut
                   18069: 
                   18070: sub check_release_required {
                   18071:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18072:     my ($switchserver,$warning);
                   18073:     if ($required ne '') {
                   18074:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18075:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18076:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18077:             my $otherserver;
                   18078:             if (($major eq '' && $minor eq '') ||
                   18079:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18080:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18081:                 my $switchlcrev =
                   18082:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18083:                                                            $userdomserver);
                   18084:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18085:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18086:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18087:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18088:                     if ($cdom ne $env{'user.domain'}) {
                   18089:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18090:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18091:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18092:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18093:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18094:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18095:                         my $canhost =
                   18096:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18097:                                                               $coursedomserver,
                   18098:                                                               $remoterev,
                   18099:                                                               $udomdefaults{'remotesessions'},
                   18100:                                                               $defdomdefaults{'hostedsessions'});
                   18101: 
                   18102:                         if ($canhost) {
                   18103:                             $otherserver = $coursedomserver;
                   18104:                         } else {
                   18105:                             $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.");
                   18106:                         }
                   18107:                     } else {
                   18108:                         $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).");
                   18109:                     }
                   18110:                 } else {
                   18111:                     $otherserver = $userdomserver;
                   18112:                 }
                   18113:             }
                   18114:             if ($otherserver ne '') {
                   18115:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18116:             }
                   18117:         }
                   18118:     }
                   18119:     return ($switchserver,$warning);
                   18120: }
                   18121: 
                   18122: =pod
                   18123: 
                   18124: =item * &check_release_result()
                   18125: 
                   18126: Inputs:
                   18127: 
                   18128: $switchwarning - Warning message if no suitable server found to host session.
                   18129: 
                   18130: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18131:                 and current role.
                   18132: 
                   18133: Returns: HTML to display with information about requirement to switch server.
                   18134:          Either displaying warning with link to Roles/Courses screen or
                   18135:          display link to switchserver.
                   18136: 
1.1075.2.69  raeburn  18137: =cut
                   18138: 
1.1075.2.88  raeburn  18139: sub check_release_result {
                   18140:     my ($switchwarning,$switchserver) = @_;
                   18141:     my $output = &start_page('Selected course unavailable on this server').
                   18142:                  '<p class="LC_warning">';
                   18143:     if ($switchwarning) {
                   18144:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18145:         if (&show_course()) {
                   18146:             $output .= &mt('Display courses');
                   18147:         } else {
                   18148:             $output .= &mt('Display roles');
                   18149:         }
                   18150:         $output .= '</a>';
                   18151:     } elsif ($switchserver) {
                   18152:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18153:                    '<br />'.
                   18154:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18155:                    &mt('Switch Server').
                   18156:                    '</a>';
                   18157:     }
                   18158:     $output .= '</p>'.&end_page();
                   18159:     return $output;
                   18160: }
                   18161: 
                   18162: =pod
                   18163: 
                   18164: =item * &needs_coursereinit()
                   18165: 
                   18166: Determine if course contents stored for user's session needs to be
                   18167: refreshed, because content has changed since "Big Hash" last tied.
                   18168: 
                   18169: Check for change is made if time last checked is more than 10 minutes ago
                   18170: (by default).
                   18171: 
                   18172: Inputs:
                   18173: 
                   18174: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18175: 
                   18176: $interval (optional) - Time which may elapse (in s) between last check for content
                   18177:                        change in current course. (default: 600 s).
                   18178: 
                   18179: Returns: an array; first element is:
                   18180: 
                   18181: =over 4
                   18182: 
                   18183: 'switch' - if content updates mean user's session
                   18184:            needs to be switched to a server running a newer LON-CAPA version
                   18185: 
                   18186: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18187:            on current server hosting user's session
                   18188: 
                   18189: ''       - if no action required.
                   18190: 
                   18191: =back
                   18192: 
                   18193: If first item element is 'switch':
                   18194: 
                   18195: second item is $switchwarning - Warning message if no suitable server found to host session.
                   18196: 
                   18197: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18198:                               and current role.
                   18199: 
                   18200: otherwise: no other elements returned.
                   18201: 
                   18202: =back
                   18203: 
                   18204: =cut
                   18205: 
                   18206: sub needs_coursereinit {
                   18207:     my ($loncaparev,$interval) = @_;
                   18208:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18209:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18210:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18211:     my $now = time;
                   18212:     if ($interval eq '') {
                   18213:         $interval = 600;
                   18214:     }
                   18215:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   18216:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 18217:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 18218:21):         if ($blocked) {
                   18219:21):             return ();
                   18220:21):         }
          .13(raeb 18221:-23):         my $update;
                   18222:-23):         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18223:-23):         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18224:-23):         if ($lastmainchange > $env{'request.course.tied'}) {
                   18225:-23):             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18226:-23):             if ($needswitch) {
                   18227:-23):                 return ('switch',$switchwarning,$switchserver);
                   18228:-23):             }
                   18229:-23):             $update = 'main';
                   18230:-23):         }
                   18231:-23):         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18232:-23):             if ($update) {
                   18233:-23):                 $update = 'both';
                   18234:-23):             } else {
                   18235:-23):                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18236:-23):                 if ($needswitch) {
                   18237:-23):                     return ('switch',$switchwarning,$switchserver);
                   18238:-23):                 } else {
                   18239:-23):                     $update = 'supp';
1.1075.2.88  raeburn  18240:                 }
                   18241:             }
1.1075.2.161.  .13(raeb 18242:-23):             return ($update);
                   18243:-23):         }
                   18244:-23):     }
                   18245:-23):     return ();
                   18246:-23): }
                   18247:-23): 
                   18248:-23): sub switch_for_update {
                   18249:-23):     my ($loncaparev,$cdom,$cnum) = @_;
                   18250:-23):     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18251:-23):     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18252:-23):         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18253:-23):         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18254:-23):             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18255:-23):                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18256:-23):             my ($switchserver,$switchwarning) =
                   18257:-23):                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18258:-23):                                         $curr_reqd_hash{'internal.releaserequired'});
                   18259:-23):             if ($switchwarning ne '' || $switchserver ne '') {
                   18260:-23):                 return ('switch',$switchwarning,$switchserver);
                   18261:-23):             }
1.1075.2.88  raeburn  18262:         }
                   18263:     }
                   18264:     return ();
                   18265: }
1.1075.2.69  raeburn  18266: 
1.1075.2.11  raeburn  18267: sub update_content_constraints {
                   18268:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18269:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18270:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   18271:     my %checkresponsetypes;
                   18272:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   18273:         my ($item,$name,$value) = split(/:/,$key);
                   18274:         if ($item eq 'resourcetag') {
                   18275:             if ($name eq 'responsetype') {
                   18276:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18277:             }
                   18278:         }
                   18279:     }
                   18280:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18281:     if (defined($navmap)) {
                   18282:         my %allresponses;
                   18283:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   18284:             my %responses = $res->responseTypes();
                   18285:             foreach my $key (keys(%responses)) {
                   18286:                 next unless(exists($checkresponsetypes{$key}));
                   18287:                 $allresponses{$key} += $responses{$key};
                   18288:             }
                   18289:         }
                   18290:         foreach my $key (keys(%allresponses)) {
                   18291:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18292:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18293:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18294:             }
                   18295:         }
                   18296:         undef($navmap);
                   18297:     }
                   18298:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18299:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18300:     }
                   18301:     return;
                   18302: }
                   18303: 
1.1075.2.27  raeburn  18304: sub allmaps_incourse {
                   18305:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18306:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18307:         $cid = $env{'request.course.id'};
                   18308:         $cdom = $env{'course.'.$cid.'.domain'};
                   18309:         $cnum = $env{'course.'.$cid.'.num'};
                   18310:         $chome = $env{'course.'.$cid.'.home'};
                   18311:     }
                   18312:     my %allmaps = ();
                   18313:     my $lastchange =
                   18314:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18315:     if ($lastchange > $env{'request.course.tied'}) {
                   18316:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18317:         unless ($ferr) {
                   18318:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   18319:         }
                   18320:     }
                   18321:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18322:     if (defined($navmap)) {
                   18323:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18324:             $allmaps{$res->src()} = 1;
                   18325:         }
                   18326:     }
                   18327:     return \%allmaps;
                   18328: }
                   18329: 
1.1075.2.11  raeburn  18330: sub parse_supplemental_title {
                   18331:     my ($title) = @_;
                   18332: 
                   18333:     my ($foldertitle,$renametitle);
                   18334:     if ($title =~ /&amp;&amp;&amp;/) {
                   18335:         $title = &HTML::Entites::decode($title);
                   18336:     }
                   18337:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18338:         $renametitle=$4;
                   18339:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18340:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18341:         my $name =  &plainname($uname,$udom);
                   18342:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18343:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1075.2.161.  .16(raeb 18344:-23):         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
                   18345:-23):         if ($foldertitle ne '') {
                   18346:-23):             $title .= ': <br />'.$foldertitle;
                   18347:-23):         }
1.1075.2.11  raeburn  18348:     }
                   18349:     if (wantarray) {
                   18350:         return ($title,$foldertitle,$renametitle);
                   18351:     }
                   18352:     return $title;
                   18353: }
                   18354: 
1.1075.2.161.  .13(raeb 18355:-23): sub get_supplemental {
                   18356:-23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18357:-23):     my $hashid=$cnum.':'.$cdom;
                   18358:-23):     my ($supplemental,$cached,$set_httprefs);
                   18359:-23):     unless ($ignorecache) {
                   18360:-23):         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18361:-23):     }
                   18362:-23):     unless (defined($cached)) {
                   18363:-23):         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18364:-23):         unless ($chome eq 'no_host') {
                   18365:-23):             my @order = @LONCAPA::map::order;
                   18366:-23):             my @resources = @LONCAPA::map::resources;
                   18367:-23):             my @resparms = @LONCAPA::map::resparms;
                   18368:-23):             my @zombies = @LONCAPA::map::zombies;
                   18369:-23):             my ($errors,%ids,%hidden);
                   18370:-23):             $errors =
                   18371:-23):                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   18372:-23):                                       $errors,$possdel,\%ids,\%hidden);
                   18373:-23):             @LONCAPA::map::order = @order;
                   18374:-23):             @LONCAPA::map::resources = @resources;
                   18375:-23):             @LONCAPA::map::resparms = @resparms;
                   18376:-23):             @LONCAPA::map::zombies = @zombies;
                   18377:-23):             $set_httprefs = 1;
                   18378:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18379:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18380:-23):             }
                   18381:-23):             $supplemental = {
                   18382:-23):                                ids => \%ids,
                   18383:-23):                                hidden => \%hidden,
                   18384:-23):                             };
                   18385:-23):             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   18386:-23):         }
                   18387:-23):     }
                   18388:-23):     return ($supplemental,$set_httprefs);
                   18389:-23): }
                   18390:-23): 
1.1075.2.43  raeburn  18391: sub recurse_supplemental {
1.1075.2.161.  .13(raeb 18392:-23):     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18393:-23):     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18394:-23):         my $mapnum;
                   18395:-23):         if ($suppmap eq 'supplemental.sequence') {
                   18396:-23):             $mapnum = 0;
                   18397:-23):         } else {
                   18398:-23):             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18399:-23):         }
1.1075.2.43  raeburn  18400:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18401:         if ($fatal) {
                   18402:             $errors ++;
                   18403:         } else {
1.1075.2.161.  .13(raeb 18404:-23):             my @order = @LONCAPA::map::order;
                   18405:-23):             if (@order > 0) {
                   18406:-23):                 my @resources = @LONCAPA::map::resources;
                   18407:-23):                 my @resparms = @LONCAPA::map::resparms;
                   18408:-23):                 foreach my $idx (@order) {
                   18409:-23):                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1075.2.43  raeburn  18410:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.161.  .13(raeb 18411:-23):                         my $id = $mapnum.':'.$idx;
                   18412:-23):                         push(@{$suppids->{$src}},$id);
                   18413:-23):                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18414:-23):                             $hiddensupp->{$id} = 1;
                   18415:-23):                         }
1.1075.2.46  raeburn  18416:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1075.2.161.  .13(raeb 18417:-23):                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18418:-23):                                                             $hiddensupp,$hiddensupp->{$id});
1.1075.2.43  raeburn  18419:                         } else {
1.1075.2.161.  .13(raeb 18420:-23):                             my $allowed;
                   18421:-23):                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18422:-23):                                 $allowed = 1;
                   18423:-23):                             } elsif ($possdel) {
                   18424:-23):                                 foreach my $item (@{$suppids->{$src}}) {
                   18425:-23):                                     next if ($item eq $id);
                   18426:-23):                                     unless ($hiddensupp->{$item}) {
                   18427:-23):                                        $allowed = 1;
                   18428:-23):                                        last;
                   18429:-23):                                     }
                   18430:-23):                                 }
                   18431:-23):                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18432:-23):                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18433:-23):                                 }
                   18434:-23):                             }
                   18435:-23):                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18436:-23):                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18437:-23):                             }
                   18438:-23):                         }
                   18439:-23):                     }
                   18440:-23):                 }
                   18441:-23):             }
                   18442:-23):         }
                   18443:-23):     }
                   18444:-23):     return $errors;
                   18445:-23): }
                   18446:-23): 
                   18447:-23): sub set_supp_httprefs {
                   18448:-23):     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18449:-23):     if (ref($supplemental) eq 'HASH') {
                   18450:-23):         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18451:-23):             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18452:-23):                 next if ($src =~ /\.sequence$/);
                   18453:-23):                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18454:-23):                     my $allowed;
                   18455:-23):                     if ($env{'request.role.adv'}) {
                   18456:-23):                         $allowed = 1;
                   18457:-23):                     } else {
                   18458:-23):                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18459:-23):                             unless ($supplemental->{'hidden'}->{$id}) {
                   18460:-23):                                 $allowed = 1;
                   18461:-23):                                 last;
                   18462:-23):                             }
                   18463:-23):                         }
                   18464:-23):                     }
                   18465:-23):                     if (exists($env{'httpref.'.$src})) {
                   18466:-23):                         if ($possdel) {
                   18467:-23):                             unless ($allowed) {
                   18468:-23):                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18469:-23):                             }
1.1075.2.43  raeburn  18470:                         }
1.1075.2.161.  .13(raeb 18471:-23):                     } elsif ($allowed) {
                   18472:-23):                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1075.2.43  raeburn  18473:                     }
                   18474:                 }
                   18475:             }
1.1075.2.161.  .13(raeb 18476:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18477:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18478:-23):             }
1.1075.2.43  raeburn  18479:         }
                   18480:     }
1.1075.2.161.  .13(raeb 18481:-23): }
                   18482:-23): 
                   18483:-23): sub get_supp_parameter {
                   18484:-23):     my ($resparm,$name)=@_;
                   18485:-23):     return if ($resparm eq '');
                   18486:-23):     my $value=undef;
                   18487:-23):     my $ptype=undef;
                   18488:-23):     foreach (split('&&&',$resparm)) {
                   18489:-23):         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18490:-23):         if ($thisname eq $name) {
                   18491:-23):             $value=$thisvalue;
                   18492:-23):             $ptype=$thistype;
                   18493:-23):         }
                   18494:-23):     }
                   18495:-23):     return $value;
1.1075.2.43  raeburn  18496: }
                   18497: 
1.1075.2.18  raeburn  18498: sub symb_to_docspath {
1.1075.2.119  raeburn  18499:     my ($symb,$navmapref) = @_;
                   18500:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  18501:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18502:     if ($resurl=~/\.(sequence|page)$/) {
                   18503:         $mapurl=$resurl;
                   18504:     } elsif ($resurl eq 'adm/navmaps') {
                   18505:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18506:     }
                   18507:     my $mapresobj;
1.1075.2.119  raeburn  18508:     unless (ref($$navmapref)) {
                   18509:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18510:     }
                   18511:     if (ref($$navmapref)) {
                   18512:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  18513:     }
                   18514:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18515:     my $type=$2;
                   18516:     my $path;
                   18517:     if (ref($mapresobj)) {
                   18518:         my $pcslist = $mapresobj->map_hierarchy();
                   18519:         if ($pcslist ne '') {
                   18520:             foreach my $pc (split(/,/,$pcslist)) {
                   18521:                 next if ($pc <= 1);
1.1075.2.119  raeburn  18522:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  18523:                 if (ref($res)) {
                   18524:                     my $thisurl = $res->src();
                   18525:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18526:                     my $thistitle = $res->title();
                   18527:                     $path .= '&'.
                   18528:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  18529:                              &escape($thistitle).
1.1075.2.18  raeburn  18530:                              ':'.$res->randompick().
                   18531:                              ':'.$res->randomout().
                   18532:                              ':'.$res->encrypted().
                   18533:                              ':'.$res->randomorder().
                   18534:                              ':'.$res->is_page();
                   18535:                 }
                   18536:             }
                   18537:         }
                   18538:         $path =~ s/^\&//;
                   18539:         my $maptitle = $mapresobj->title();
                   18540:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18541:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18542:         }
                   18543:         $path .= (($path ne '')? '&' : '').
                   18544:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18545:                  &escape($maptitle).
1.1075.2.18  raeburn  18546:                  ':'.$mapresobj->randompick().
                   18547:                  ':'.$mapresobj->randomout().
                   18548:                  ':'.$mapresobj->encrypted().
                   18549:                  ':'.$mapresobj->randomorder().
                   18550:                  ':'.$mapresobj->is_page();
                   18551:     } else {
                   18552:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18553:         my $ispage = (($type eq 'page')? 1 : '');
                   18554:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18555:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18556:         }
                   18557:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18558:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  18559:     }
                   18560:     unless ($mapurl eq 'default') {
                   18561:         $path = 'default&'.
1.1075.2.46  raeburn  18562:                 &escape('Main Content').
1.1075.2.18  raeburn  18563:                 ':::::&'.$path;
                   18564:     }
                   18565:     return $path;
                   18566: }
                   18567: 
1.1075.2.161.  .13(raeb 18568:-23): sub validate_folderpath {
                   18569:-23):     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18570:-23):     if ($env{'form.folderpath'} ne '') {
                   18571:-23):         my @items = split(/\&/,$env{'form.folderpath'});
                   18572:-23):         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
                   18573:-23):         for (my $i=0; $i<@items; $i++) {
                   18574:-23):             my $odd = $i%2;
                   18575:-23):             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18576:-23):                 $badpath = 1;
                   18577:-23):             } elsif ($odd && $supplementalflag) {
                   18578:-23):                 my $idx = $i-1;
                   18579:-23):                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18580:-23):                     my $esc_name = $1;
                   18581:-23):                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18582:-23):                         $supppath .= '&'.$esc_name;
                   18583:-23):                         $changed = 1;
                   18584:-23):                     } else {
                   18585:-23):                         $supppath .= '&'.$items[$i];
                   18586:-23):                     }
                   18587:-23):                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18588:-23):                     $changed = 1;
                   18589:-23):                     my $is_hidden;
                   18590:-23):                     unless ($got_supp) {
                   18591:-23):                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
                   18592:-23):                         if (ref($supplemental) eq 'HASH') {
                   18593:-23):                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18594:-23):                                 %supphidden = %{$supplemental->{'hidden'}};
                   18595:-23):                             }
                   18596:-23):                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18597:-23):                                 %suppids = %{$supplemental->{'ids'}};
                   18598:-23):                             }
                   18599:-23):                         }
                   18600:-23):                         $got_supp = 1;
                   18601:-23):                     }
                   18602:-23):                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18603:-23):                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18604:-23):                         if ($supphidden{$mapid}) {
                   18605:-23):                             $is_hidden = 1;
                   18606:-23):                         }
                   18607:-23):                     }
                   18608:-23):                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18609:-23):                 } else {
                   18610:-23):                     $supppath .= '&'.$items[$i];
                   18611:-23):                 }
                   18612:-23):             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18613:-23):                 $badpath = 1;
                   18614:-23):             } elsif ($supplementalflag) {
                   18615:-23):                 $supppath .= '&'.$items[$i];
                   18616:-23):             }
                   18617:-23):             last if ($badpath);
                   18618:-23):         }
                   18619:-23):         if ($badpath) {
                   18620:-23):             delete($env{'form.folderpath'});
                   18621:-23):         } elsif ($changed && $supplementalflag) {
                   18622:-23):             $supppath =~ s/^\&//;
                   18623:-23):             $env{'form.folderpath'} = $supppath;
                   18624:-23):         }
                   18625:-23):     }
                   18626:-23):     return;
                   18627:-23): }
                   18628:-23): 
1.1075.2.14  raeburn  18629: sub captcha_display {
1.1075.2.137  raeburn  18630:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18631:     my ($output,$error);
1.1075.2.107  raeburn  18632:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  18633:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18634:     if ($captcha eq 'original') {
                   18635:         $output = &create_captcha();
                   18636:         unless ($output) {
                   18637:             $error = 'captcha';
                   18638:         }
                   18639:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18640:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  18641:         unless ($output) {
                   18642:             $error = 'recaptcha';
                   18643:         }
                   18644:     }
1.1075.2.107  raeburn  18645:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  18646: }
                   18647: 
                   18648: sub captcha_response {
1.1075.2.137  raeburn  18649:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18650:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  18651:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18652:     if ($captcha eq 'original') {
                   18653:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18654:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18655:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  18656:     } else {
                   18657:         $captcha_chk = 1;
                   18658:     }
                   18659:     return ($captcha_chk,$captcha_error);
                   18660: }
                   18661: 
                   18662: sub get_captcha_config {
1.1075.2.137  raeburn  18663:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  18664:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  18665:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18666:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18667:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18668:     if ($context eq 'usercreation') {
                   18669:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18670:         if (ref($domconfig{$context}) eq 'HASH') {
                   18671:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18672:             if (ref($hashtocheck) eq 'HASH') {
                   18673:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18674:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18675:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18676:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18677:                     }
                   18678:                     if ($privkey && $pubkey) {
                   18679:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  18680:                         $version = $hashtocheck->{'recaptchaversion'};
                   18681:                         if ($version ne '2') {
                   18682:                             $version = 1;
                   18683:                         }
1.1075.2.14  raeburn  18684:                     } else {
                   18685:                         $captcha = 'original';
                   18686:                     }
                   18687:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18688:                     $captcha = 'original';
                   18689:                 }
                   18690:             }
                   18691:         } else {
                   18692:             $captcha = 'captcha';
                   18693:         }
                   18694:     } elsif ($context eq 'login') {
                   18695:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18696:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18697:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18698:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   18699:             if ($privkey && $pubkey) {
                   18700:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  18701:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18702:                 if ($version ne '2') {
                   18703:                     $version = 1;
                   18704:                 }
1.1075.2.14  raeburn  18705:             } else {
                   18706:                 $captcha = 'original';
                   18707:             }
                   18708:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18709:             $captcha = 'original';
                   18710:         }
1.1075.2.137  raeburn  18711:     } elsif ($context eq 'passwords') {
                   18712:         if ($dom_in_effect) {
                   18713:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18714:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18715:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18716:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18717:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18718:                 }
                   18719:                 if ($privkey && $pubkey) {
                   18720:                     $captcha = 'recaptcha';
                   18721:                     $version = $passwdconf{'recaptchaversion'};
                   18722:                     if ($version ne '2') {
                   18723:                         $version = 1;
                   18724:                     }
                   18725:                 } else {
                   18726:                     $captcha = 'original';
                   18727:                 }
                   18728:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18729:                 $captcha = 'original';
                   18730:             }
                   18731:         }
1.1075.2.14  raeburn  18732:     }
1.1075.2.107  raeburn  18733:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  18734: }
                   18735: 
                   18736: sub create_captcha {
                   18737:     my %captcha_params = &captcha_settings();
                   18738:     my ($output,$maxtries,$tries) = ('',10,0);
                   18739:     while ($tries < $maxtries) {
                   18740:         $tries ++;
                   18741:         my $captcha = Authen::Captcha->new (
                   18742:                                            output_folder => $captcha_params{'output_dir'},
                   18743:                                            data_folder   => $captcha_params{'db_dir'},
                   18744:                                           );
                   18745:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18746: 
                   18747:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18748:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  18749:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  18750:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.161.  .15(raeb 18751:-23):                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1075.2.158  raeburn  18752:                       '</span><br />'.
1.1075.2.66  raeburn  18753:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  18754:             last;
                   18755:         }
                   18756:     }
1.1075.2.158  raeburn  18757:     if ($output eq '') {
                   18758:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18759:     }
1.1075.2.14  raeburn  18760:     return $output;
                   18761: }
                   18762: 
                   18763: sub captcha_settings {
                   18764:     my %captcha_params = (
                   18765:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18766:                            www_output_dir => "/captchaspool",
                   18767:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18768:                            numchars       => '5',
                   18769:                          );
                   18770:     return %captcha_params;
                   18771: }
                   18772: 
                   18773: sub check_captcha {
                   18774:     my ($captcha_chk,$captcha_error);
                   18775:     my $code = $env{'form.code'};
                   18776:     my $md5sum = $env{'form.crypt'};
                   18777:     my %captcha_params = &captcha_settings();
                   18778:     my $captcha = Authen::Captcha->new(
                   18779:                       output_folder => $captcha_params{'output_dir'},
                   18780:                       data_folder   => $captcha_params{'db_dir'},
                   18781:                   );
1.1075.2.26  raeburn  18782:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  18783:     my %captcha_hash = (
                   18784:                         0       => 'Code not checked (file error)',
                   18785:                        -1      => 'Failed: code expired',
                   18786:                        -2      => 'Failed: invalid code (not in database)',
                   18787:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18788:     );
                   18789:     if ($captcha_chk != 1) {
                   18790:         $captcha_error = $captcha_hash{$captcha_chk}
                   18791:     }
                   18792:     return ($captcha_chk,$captcha_error);
                   18793: }
                   18794: 
                   18795: sub create_recaptcha {
1.1075.2.107  raeburn  18796:     my ($pubkey,$version) = @_;
                   18797:     if ($version >= 2) {
1.1075.2.158  raeburn  18798:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18799:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  18800:     } else {
                   18801:         my $use_ssl;
                   18802:         if ($ENV{'SERVER_PORT'} == 443) {
                   18803:             $use_ssl = 1;
                   18804:         }
                   18805:         my $captcha = Captcha::reCAPTCHA->new;
                   18806:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18807:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18808:                &mt('If the text is hard to read, [_1] will replace them.',
                   18809:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18810:                '<br /><br />';
                   18811:      }
1.1075.2.14  raeburn  18812: }
                   18813: 
                   18814: sub check_recaptcha {
1.1075.2.107  raeburn  18815:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  18816:     my $captcha_chk;
1.1075.2.150  raeburn  18817:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  18818:     if ($version >= 2) {
                   18819:         my $ua = LWP::UserAgent->new;
                   18820:         $ua->timeout(10);
                   18821:         my %info = (
                   18822:                      secret   => $privkey,
                   18823:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  18824:                      remoteip => $ip,
1.1075.2.107  raeburn  18825:                    );
                   18826:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   18827:         if ($response->is_success)  {
                   18828:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18829:             if (ref($data) eq 'HASH') {
                   18830:                 if ($data->{'success'}) {
                   18831:                     $captcha_chk = 1;
                   18832:                 }
                   18833:             }
                   18834:         }
                   18835:     } else {
                   18836:         my $captcha = Captcha::reCAPTCHA->new;
                   18837:         my $captcha_result =
                   18838:             $captcha->check_answer(
                   18839:                                     $privkey,
1.1075.2.150  raeburn  18840:                                     $ip,
1.1075.2.107  raeburn  18841:                                     $env{'form.recaptcha_challenge_field'},
                   18842:                                     $env{'form.recaptcha_response_field'},
                   18843:                                   );
                   18844:         if ($captcha_result->{is_valid}) {
                   18845:             $captcha_chk = 1;
                   18846:         }
1.1075.2.14  raeburn  18847:     }
                   18848:     return $captcha_chk;
                   18849: }
                   18850: 
1.1075.2.64  raeburn  18851: sub emailusername_info {
1.1075.2.103  raeburn  18852:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18853:     my %titles = &Apache::lonlocal::texthash (
                   18854:                      lastname      => 'Last Name',
                   18855:                      firstname     => 'First Name',
                   18856:                      institution   => 'School/college/university',
                   18857:                      location      => "School's city, state/province, country",
                   18858:                      web           => "School's web address",
                   18859:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18860:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18861:                  );
                   18862:     return (\@fields,\%titles);
                   18863: }
                   18864: 
1.1075.2.56  raeburn  18865: sub cleanup_html {
                   18866:     my ($incoming) = @_;
                   18867:     my $outgoing;
                   18868:     if ($incoming ne '') {
                   18869:         $outgoing = $incoming;
                   18870:         $outgoing =~ s/;/&#059;/g;
                   18871:         $outgoing =~ s/\#/&#035;/g;
                   18872:         $outgoing =~ s/\&/&#038;/g;
                   18873:         $outgoing =~ s/</&#060;/g;
                   18874:         $outgoing =~ s/>/&#062;/g;
                   18875:         $outgoing =~ s/\(/&#040/g;
                   18876:         $outgoing =~ s/\)/&#041;/g;
                   18877:         $outgoing =~ s/"/&#034;/g;
                   18878:         $outgoing =~ s/'/&#039;/g;
                   18879:         $outgoing =~ s/\$/&#036;/g;
                   18880:         $outgoing =~ s{/}{&#047;}g;
                   18881:         $outgoing =~ s/=/&#061;/g;
                   18882:         $outgoing =~ s/\\/&#092;/g
                   18883:     }
                   18884:     return $outgoing;
                   18885: }
                   18886: 
1.1075.2.74  raeburn  18887: # Checks for critical messages and returns a redirect url if one exists.
                   18888: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18889:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18890: sub critical_redirect {
1.1075.2.161.  .1(raebu 18891:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18892:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18893:         return ();
                   18894:     }
1.1075.2.74  raeburn  18895:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18896:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18897:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18898:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18899:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18900:21):             if ($blocked) {
                   18901:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18902:21):                 if ($env{'request.course.sec'} ne '') {
                   18903:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18904:21):                 }
                   18905:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18906:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18907:21):                     return;
                   18908:21):                 }
                   18909:21):             }
                   18910:21):         }
1.1075.2.74  raeburn  18911:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18912:                                         $env{'user.name'});
                   18913:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18914:         my $redirecturl;
                   18915:         if ($what[0]) {
1.1075.2.158  raeburn  18916:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18917:                 $redirecturl='/adm/email?critical=display';
                   18918:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18919:                 return (1, $url);
                   18920:             }
                   18921:         }
                   18922:     }
                   18923:     return ();
                   18924: }
                   18925: 
1.1075.2.64  raeburn  18926: # Use:
                   18927: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18928: #
                   18929: ##################################################
                   18930: #          password associated functions         #
                   18931: ##################################################
                   18932: sub des_keys {
                   18933:     # Make a new key for DES encryption.
                   18934:     # Each key has two parts which are returned separately.
                   18935:     # Please note:  Each key must be passed through the &hex function
                   18936:     # before it is output to the web browser.  The hex versions cannot
                   18937:     # be used to decrypt.
                   18938:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18939:                 '8','9','a','b','c','d','e','f');
                   18940:     my $lkey='';
                   18941:     for (0..7) {
                   18942:         $lkey.=$hexstr[rand(15)];
                   18943:     }
                   18944:     my $ukey='';
                   18945:     for (0..7) {
                   18946:         $ukey.=$hexstr[rand(15)];
                   18947:     }
                   18948:     return ($lkey,$ukey);
                   18949: }
                   18950: 
                   18951: sub des_decrypt {
                   18952:     my ($key,$cyphertext) = @_;
                   18953:     my $keybin=pack("H16",$key);
                   18954:     my $cypher;
                   18955:     if ($Crypt::DES::VERSION>=2.03) {
                   18956:         $cypher=new Crypt::DES $keybin;
                   18957:     } else {
                   18958:         $cypher=new DES $keybin;
                   18959:     }
1.1075.2.106  raeburn  18960:     my $plaintext='';
                   18961:     my $cypherlength = length($cyphertext);
                   18962:     my $numchunks = int($cypherlength/32);
                   18963:     for (my $j=0; $j<$numchunks; $j++) {
                   18964:         my $start = $j*32;
                   18965:         my $cypherblock = substr($cyphertext,$start,32);
                   18966:         my $chunk =
                   18967:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18968:         $chunk .=
                   18969:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18970:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18971:         $plaintext .= $chunk;
                   18972:     }
1.1075.2.64  raeburn  18973:     return $plaintext;
                   18974: }
                   18975: 
1.1075.2.161.  .1(raebu 18976:21): sub get_requested_shorturls {
                   18977:21):     my ($cdom,$cnum,$navmap) = @_;
                   18978:21):     return unless (ref($navmap));
                   18979:21):     my ($numnew,$errors);
                   18980:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18981:21):     if (@toshorten) {
                   18982:21):         my (%maps,%resources,%titles);
                   18983:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18984:21):                                                                'shorturls',$cdom,$cnum);
                   18985:21):         if (keys(%resources)) {
                   18986:21):             my %tocreate;
                   18987:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18988:21):                 my $symb = $resources{$item};
                   18989:21):                 if ($symb) {
                   18990:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18991:21):                 }
                   18992:21):             }
                   18993:21):             if (keys(%tocreate)) {
                   18994:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18995:21):                                                       \%tocreate);
                   18996:21):             }
                   18997:21):         }
                   18998:21):     }
                   18999:21):     return ($numnew,$errors);
                   19000:21): }
                   19001:21): 
                   19002:21): sub make_short_symbs {
                   19003:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19004:21):     my ($numnew,@errors);
                   19005:21):     if (ref($tocreateref) eq 'HASH') {
                   19006:21):         my %tocreate = %{$tocreateref};
                   19007:21):         if (keys(%tocreate)) {
                   19008:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19009:21):             my $su = Short::URL->new(no_vowels => 1);
                   19010:21):             my $init = '';
                   19011:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   19012:21):             # get lock on tiny db
                   19013:21):             my $now = time;
                   19014:21):             if ($lockuser eq '') {
                   19015:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19016:21):             }
                   19017:21):             my $lockhash = {
                   19018:21):                                 "lock\0$now" => $lockuser,
                   19019:21):                             };
                   19020:21):             my $tries = 0;
                   19021:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19022:21):             my ($code,$error);
                   19023:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   19024:21):                 $tries ++;
                   19025:21):                 sleep 1;
                   19026:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19027:21):             }
                   19028:21):             if ($gotlock eq 'ok') {
                   19029:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19030:21):                                        \%addcourse,\%courseonly,\%failed);
                   19031:21):                 if (keys(%failed)) {
                   19032:21):                     my $numfailed = scalar(keys(%failed));
                   19033:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19034:21):                 }
                   19035:21):                 if (keys(%newunique)) {
                   19036:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19037:21):                     if ($putres eq 'ok') {
                   19038:21):                         $numnew = scalar(keys(%newunique));
                   19039:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19040:21):                         unless ($newputres eq 'ok') {
                   19041:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19042:21):                         }
                   19043:21):                     } else {
                   19044:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19045:21):                     }
                   19046:21):                 }
                   19047:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19048:21):                 unless ($dellockres eq 'ok') {
                   19049:21):                     push(@errors,&mt('error: could not release lockfile'));
                   19050:21):                 }
                   19051:21):             } else {
                   19052:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   19053:21):             }
                   19054:21):             if (keys(%courseonly)) {
                   19055:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19056:21):                 if ($result ne 'ok') {
                   19057:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19058:21):                 }
                   19059:21):             }
                   19060:21):         }
                   19061:21):     }
                   19062:21):     return ($numnew,\@errors);
                   19063:21): }
                   19064:21): 
                   19065:21): sub shorten_symbs {
                   19066:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19067:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19068:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19069:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19070:21):     my (%possibles,%collisions);
                   19071:21):     foreach my $key (keys(%{$tocreate})) {
                   19072:21):         my $num = String::CRC32::crc32($key);
                   19073:21):         my $tiny = $su->encode($num,$init);
                   19074:21):         if ($tiny) {
                   19075:21):             $possibles{$tiny} = $key;
                   19076:21):         }
                   19077:21):     }
                   19078:21):     if (!$init) {
                   19079:21):         $init = 1;
                   19080:21):     } else {
                   19081:21):         $init ++;
                   19082:21):     }
                   19083:21):     if (keys(%possibles)) {
                   19084:21):         my @posstiny = keys(%possibles);
                   19085:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19086:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19087:21):         if (keys(%currtiny)) {
                   19088:21):             foreach my $key (keys(%currtiny)) {
                   19089:21):                 next if ($currtiny{$key} eq '');
                   19090:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   19091:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19092:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19093:21):                         $courseonly->{$tsymb} = $key;
                   19094:21):                     }
                   19095:21):                 } else {
                   19096:21):                     $collisions{$possibles{$key}} = 1;
                   19097:21):                 }
                   19098:21):                 delete($possibles{$key});
                   19099:21):             }
                   19100:21):         }
                   19101:21):         foreach my $key (keys(%possibles)) {
                   19102:21):             $newunique->{$key} = $possibles{$key};
                   19103:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19104:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19105:21):                 $addcourse->{$tsymb} = $key;
                   19106:21):             }
                   19107:21):         }
                   19108:21):     }
                   19109:21):     if (keys(%collisions)) {
                   19110:21):         if ($init <5) {
                   19111:21):             if (!$init) {
                   19112:21):                 $init = 1;
                   19113:21):             } else {
                   19114:21):                 $init ++;
                   19115:21):             }
                   19116:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19117:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   19118:21):         } else {
                   19119:21):             foreach my $key (keys(%collisions)) {
                   19120:21):                 $failed->{$key} = 1;
                   19121:21):                 $failed->{$key} = 1;
                   19122:21):             }
                   19123:21):         }
                   19124:21):     }
                   19125:21):     return $init;
                   19126:21): }
                   19127:21): 
1.1075.2.135  raeburn  19128: sub is_nonframeable {
                   19129:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19130:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   19131:     return if (($remprotocol eq '') || ($remhost eq ''));
                   19132: 
                   19133:     $remprotocol = lc($remprotocol);
                   19134:     $remhost = lc($remhost);
                   19135:     my $remport = 80;
                   19136:     if ($remprotocol eq 'https') {
                   19137:         $remport = 443;
                   19138:     }
                   19139:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   19140:     if ($cached) {
                   19141:         unless ($nocache) {
                   19142:             if ($result) {
                   19143:                 return 1;
                   19144:             } else {
                   19145:                 return 0;
                   19146:             }
                   19147:         }
                   19148:     }
                   19149:     my $uselink;
                   19150:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  19151:     my $ua = LWP::UserAgent->new;
                   19152:     $ua->timeout(5);
                   19153:     my $response=$ua->request($request);
1.1075.2.135  raeburn  19154:     if ($response->is_success()) {
                   19155:         my $secpolicy = lc($response->header('content-security-policy'));
                   19156:         my $xframeop = lc($response->header('x-frame-options'));
                   19157:         $secpolicy =~ s/^\s+|\s+$//g;
                   19158:         $xframeop =~ s/^\s+|\s+$//g;
                   19159:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   19160:             my $remotehost = $remprotocol.'://'.$remhost;
                   19161:             my ($origin,$protocol,$port);
                   19162:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19163:                 $port = $ENV{'SERVER_PORT'};
                   19164:             } else {
                   19165:                 $port = 80;
                   19166:             }
                   19167:             if ($absolute eq '') {
                   19168:                 $protocol = 'http:';
                   19169:                 if ($port == 443) {
                   19170:                     $protocol = 'https:';
                   19171:                 }
                   19172:                 $origin = $protocol.'//'.lc($hostname);
                   19173:             } else {
                   19174:                 $origin = lc($absolute);
                   19175:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19176:             }
                   19177:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19178:                 my $framepolicy = $1;
                   19179:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19180:                 my @policies = split(/\s+/,$framepolicy);
                   19181:                 if (@policies) {
                   19182:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19183:                         $uselink = 1;
                   19184:                     } else {
                   19185:                         $uselink = 1;
                   19186:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19187:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19188:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19189:                             undef($uselink);
                   19190:                         }
                   19191:                         if ($uselink) {
                   19192:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19193:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19194:                                     undef($uselink);
                   19195:                                 }
                   19196:                             }
                   19197:                         }
                   19198:                         if ($uselink) {
                   19199:                             my @possok;
                   19200:                             if ($ip ne '') {
                   19201:                                 push(@possok,$ip);
                   19202:                             }
                   19203:                             my $hoststr = '';
                   19204:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19205:                                 if ($hoststr eq '') {
                   19206:                                     $hoststr = $part;
                   19207:                                 } else {
                   19208:                                     $hoststr = "$part.$hoststr";
                   19209:                                 }
                   19210:                                 if ($hoststr eq $hostname) {
                   19211:                                     push(@possok,$hostname);
                   19212:                                 } else {
                   19213:                                     push(@possok,"*.$hoststr");
                   19214:                                 }
                   19215:                             }
                   19216:                             if (@possok) {
                   19217:                                 foreach my $poss (@possok) {
                   19218:                                     last if (!$uselink);
                   19219:                                     foreach my $policy (@policies) {
                   19220:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19221:                                             undef($uselink);
                   19222:                                             last;
                   19223:                                         }
                   19224:                                     }
                   19225:                                 }
                   19226:                             }
                   19227:                         }
                   19228:                     }
                   19229:                 }
                   19230:             } elsif ($xframeop ne '') {
                   19231:                 $uselink = 1;
                   19232:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19233:                 if (@policies) {
                   19234:                     unless (grep(/^deny$/,@policies)) {
                   19235:                         if ($origin ne '') {
                   19236:                             if (grep(/^sameorigin$/,@policies)) {
                   19237:                                 if ($remotehost eq $origin) {
                   19238:                                     undef($uselink);
                   19239:                                 }
                   19240:                             }
                   19241:                             if ($uselink) {
                   19242:                                 foreach my $policy (@policies) {
                   19243:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19244:                                         my $allowfrom = $1;
                   19245:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19246:                                             undef($uselink);
                   19247:                                             last;
                   19248:                                         }
                   19249:                                     }
                   19250:                                 }
                   19251:                             }
                   19252:                         }
                   19253:                     }
                   19254:                 }
                   19255:             }
                   19256:         }
                   19257:     }
                   19258:     if ($nocache) {
                   19259:         if ($cached) {
                   19260:             my $devalidate;
                   19261:             if ($uselink && !$result) {
                   19262:                 $devalidate = 1;
                   19263:             } elsif (!$uselink && $result) {
                   19264:                 $devalidate = 1;
                   19265:             }
                   19266:             if ($devalidate) {
                   19267:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19268:             }
                   19269:         }
                   19270:     } else {
                   19271:         if ($uselink) {
                   19272:             $result = 1;
                   19273:         } else {
                   19274:             $result = 0;
                   19275:         }
                   19276:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19277:     }
                   19278:     return $uselink;
                   19279: }
                   19280: 
1.1075.2.161.  .1(raebu 19281:21): sub page_menu {
                   19282:21):     my ($menucolls,$menunum) = @_;
                   19283:21):     my %menu;
                   19284:21):     foreach my $item (split(/;/,$menucolls)) {
                   19285:21):         my ($num,$value) = split(/\%/,$item);
                   19286:21):         if ($num eq $menunum) {
                   19287:21):             my @entries = split(/\&/,$value);
                   19288:21):             foreach my $entry (@entries) {
                   19289:21):                 my ($name,$fields) = split(/=/,$entry);
                   19290:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   19291:21):                     $menu{$name} = $fields;
                   19292:21):                 } else {
                   19293:21):                     my @shown;
                   19294:21):                     if ($fields =~ /,/) {
                   19295:21):                         @shown = split(/,/,$fields);
                   19296:21):                     } else {
                   19297:21):                         @shown = ($fields);
                   19298:21):                     }
                   19299:21):                     if (@shown) {
                   19300:21):                         foreach my $field (@shown) {
                   19301:21):                             next if ($field eq '');
                   19302:21):                             $menu{$field} = 1;
                   19303:21):                         }
                   19304:21):                     }
                   19305:21):                 }
                   19306:21):             }
                   19307:21):         }
                   19308:21):     }
                   19309:21):     return %menu;
                   19310:21): }
                   19311:21): 
1.112     bowersj2 19312: 1;
                   19313: __END__;
1.41      ng       19314: 

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