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

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.157! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.156 2021/09/11 15:57:33 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1048    foxr      170: my %latex_language;		# For choosing hyphenation in <transl..>
                    171: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  172: my %cprtag;
1.192     taceyjo1  173: my %scprtag;
1.351     www       174: my %fe; my %fd; my %fm;
1.41      ng        175: my %category_extensions;
1.12      harris41  176: 
1.46      matthew   177: # ---------------------------------------------- Thesaurus variables
1.144     matthew   178: #
                    179: # %Keywords:
                    180: #      A hash used by &keyword to determine if a word is considered a keyword.
                    181: # $thesaurus_db_file 
                    182: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   183: 
                    184: my %Keywords;
                    185: my $thesaurus_db_file;
                    186: 
1.144     matthew   187: #
                    188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    189: # thesaurus.tab, and filecategories.tab.
                    190: #
1.18      www       191: BEGIN {
1.46      matthew   192:     # Variable initialization
                    193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    194:     #
1.22      www       195:     unless ($readit) {
1.12      harris41  196: # ------------------------------------------------------------------- languages
                    197:     {
1.158     raeburn   198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    199:                                    '/language.tab';
1.1075.2.128  raeburn   200:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  201:             while (my $line = <$fh>) {
                    202:                 next if ($line=~/^\#/);
                    203:                 chomp($line);
1.1048    foxr      204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   205:                 $language{$key}=$val.' - '.$enc;
                    206:                 if ($sup) {
                    207:                     $supported_language{$key}=$sup;
                    208:                 }
1.1048    foxr      209: 		if ($latex) {
                    210: 		    $latex_language_bykey{$key} = $latex;
                    211: 		    $latex_language{$two} = $latex;
                    212: 		}
1.158     raeburn   213:             }
                    214:             close($fh);
                    215:         }
1.12      harris41  216:     }
                    217: # ------------------------------------------------------------------ copyrights
                    218:     {
1.158     raeburn   219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    220:                                   '/copyright.tab';
1.1075.2.128  raeburn   221:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  222:             while (my $line = <$fh>) {
                    223:                 next if ($line=~/^\#/);
                    224:                 chomp($line);
                    225:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   226:                 $cprtag{$key}=$val;
                    227:             }
                    228:             close($fh);
                    229:         }
1.12      harris41  230:     }
1.351     www       231: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  232:     {
                    233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    234:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  236:             while (my $line = <$fh>) {
                    237:                 next if ($line =~ /^\#/);
                    238:                 chomp($line);
                    239:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  240:                 $scprtag{$key}=$val;
                    241:             }
                    242:             close($fh);
                    243:         }
                    244:     }
1.63      www       245: 
1.517     raeburn   246: # -------------------------------------------------------------- default domain designs
1.63      www       247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   248:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   249:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   250:         while (my $line = <$fh>) {
                    251:             next if ($line =~ /^\#/);
                    252:             chomp($line);
                    253:             my ($key,$val)=(split(/\=/,$line));
                    254:             if ($val) { $defaultdesign{$key}=$val; }
                    255:         }
                    256:         close($fh);
1.63      www       257:     }
                    258: 
1.15      harris41  259: # ------------------------------------------------------------- file categories
                    260:     {
1.158     raeburn   261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    262:                                   '/filecategories.tab';
1.1075.2.128  raeburn   263:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  264: 	    while (my $line = <$fh>) {
                    265: 		next if ($line =~ /^\#/);
                    266: 		chomp($line);
                    267:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   268:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   269:             }
                    270:             close($fh);
                    271:         }
                    272: 
1.15      harris41  273:     }
1.12      harris41  274: # ------------------------------------------------------------------ file types
                    275:     {
1.158     raeburn   276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    277:                '/filetypes.tab';
1.1075.2.128  raeburn   278:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  279:             while (my $line = <$fh>) {
                    280: 		next if ($line =~ /^\#/);
                    281: 		chomp($line);
                    282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   283:                 if ($descr ne '') {
                    284:                     $fe{$ending}=lc($emb);
                    285:                     $fd{$ending}=$descr;
1.351     www       286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   287:                 }
                    288:             }
                    289:             close($fh);
                    290:         }
1.12      harris41  291:     }
1.22      www       292:     &Apache::lonnet::logthis(
1.705     tempelho  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       294:     $readit=1;
1.46      matthew   295:     }  # end of unless($readit) 
1.32      matthew   296:     
                    297: }
1.112     bowersj2  298: 
1.42      matthew   299: ###############################################################
                    300: ##           HTML and Javascript Helper Functions            ##
                    301: ###############################################################
                    302: 
                    303: =pod 
                    304: 
1.112     bowersj2  305: =head1 HTML and Javascript Functions
1.42      matthew   306: 
1.112     bowersj2  307: =over 4
                    308: 
1.648     raeburn   309: =item * &browser_and_searcher_javascript()
1.112     bowersj2  310: 
                    311: X<browsing, javascript>X<searching, javascript>Returns a string
                    312: containing javascript with two functions, C<openbrowser> and
                    313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    314: tags.
1.42      matthew   315: 
1.648     raeburn   316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   317: 
                    318: inputs: formname, elementname, only, omit
                    319: 
                    320: formname and elementname indicate the name of the html form and name of
                    321: the element that the results of the browsing selection are to be placed in. 
                    322: 
                    323: Specifying 'only' will restrict the browser to displaying only files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
                    326: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
1.648     raeburn   329: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   330: 
                    331: Inputs: formname, elementname
                    332: 
                    333: formname and elementname specify the name of the html form and the name
                    334: of the element the selection from the search results will be placed in.
1.542     raeburn   335: 
1.42      matthew   336: =cut
                    337: 
                    338: sub browser_and_searcher_javascript {
1.199     albertel  339:     my ($mode)=@_;
                    340:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  341:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   342:     return <<END;
1.219     albertel  343: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   344:     var editbrowser = null;
1.135     albertel  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       346:         var url = '$resurl/?';
1.42      matthew   347:         if (editbrowser == null) {
                    348:             url += 'launch=1&';
                    349:         }
                    350:         url += 'catalogmode=interactive&';
1.199     albertel  351:         url += 'mode=$mode&';
1.611     albertel  352:         url += 'inhibitmenu=yes&';
1.42      matthew   353:         url += 'form=' + formname + '&';
                    354:         if (only != null) {
                    355:             url += 'only=' + only + '&';
1.217     albertel  356:         } else {
                    357:             url += 'only=&';
                    358: 	}
1.42      matthew   359:         if (omit != null) {
                    360:             url += 'omit=' + omit + '&';
1.217     albertel  361:         } else {
                    362:             url += 'omit=&';
                    363: 	}
1.135     albertel  364:         if (titleelement != null) {
                    365:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  366:         } else {
                    367: 	    url += 'titleelement=&';
                    368: 	}
1.42      matthew   369:         url += 'element=' + elementname + '';
                    370:         var title = 'Browser';
1.435     albertel  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   372:         options += ',width=700,height=600';
                    373:         editbrowser = open(url,title,options,'1');
                    374:         editbrowser.focus();
                    375:     }
                    376:     var editsearcher;
1.135     albertel  377:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   378:         var url = '/adm/searchcat?';
                    379:         if (editsearcher == null) {
                    380:             url += 'launch=1&';
                    381:         }
                    382:         url += 'catalogmode=interactive&';
1.199     albertel  383:         url += 'mode=$mode&';
1.42      matthew   384:         url += 'form=' + formname + '&';
1.135     albertel  385:         if (titleelement != null) {
                    386:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  387:         } else {
                    388: 	    url += 'titleelement=&';
                    389: 	}
1.42      matthew   390:         url += 'element=' + elementname + '';
                    391:         var title = 'Search';
1.435     albertel  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   393:         options += ',width=700,height=600';
                    394:         editsearcher = open(url,title,options,'1');
                    395:         editsearcher.focus();
                    396:     }
1.219     albertel  397: // END LON-CAPA Internal -->
1.42      matthew   398: END
1.170     www       399: }
                    400: 
                    401: sub lastresurl {
1.258     albertel  402:     if ($env{'environment.lastresurl'}) {
                    403: 	return $env{'environment.lastresurl'}
1.170     www       404:     } else {
                    405: 	return '/res';
                    406:     }
                    407: }
                    408: 
                    409: sub storeresurl {
                    410:     my $resurl=&Apache::lonnet::clutter(shift);
                    411:     unless ($resurl=~/^\/res/) { return 0; }
                    412:     $resurl=~s/\/$//;
                    413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       415:     return 1;
1.42      matthew   416: }
                    417: 
1.74      www       418: sub studentbrowser_javascript {
1.111     www       419:    unless (
1.258     albertel  420:             (($env{'request.course.id'}) && 
1.302     albertel  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    423: 					  '/'.$env{'request.course.sec'})
                    424: 	      ))
1.258     albertel  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       426:           ) { return ''; }  
1.74      www       427:    return (<<'ENDSTDBRW');
1.776     bisitz    428: <script type="text/javascript" language="Javascript">
1.824     bisitz    429: // <![CDATA[
1.74      www       430:     var stdeditbrowser;
1.1075.2.143  raeburn   431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       432:         var url = '/adm/pickstudent?';
                    433:         var filter;
1.558     albertel  434: 	if (!ignorefilter) {
                    435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    436: 	}
1.74      www       437:         if (filter != null) {
                    438:            if (filter != '') {
                    439:                url += 'filter='+filter+'&';
                    440: 	   }
                    441:         }
                    442:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       443:                                     '&udomelement='+udom+
                    444:                                     '&clicker='+clicker;
1.111     www       445: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   446:         if (courseadv == 'condition') {
                    447:             if (document.getElementById('courseadv')) {
                    448:                 courseadv = document.getElementById('courseadv').value;
                    449:             }
                    450:         }
                    451:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       452:         var title = 'Student_Browser';
1.74      www       453:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    454:         options += ',width=700,height=600';
                    455:         stdeditbrowser = open(url,title,options,'1');
                    456:         stdeditbrowser.focus();
                    457:     }
1.824     bisitz    458: // ]]>
1.74      www       459: </script>
                    460: ENDSTDBRW
                    461: }
1.42      matthew   462: 
1.1003    www       463: sub resourcebrowser_javascript {
                    464:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       465:    return (<<'ENDRESBRW');
1.1003    www       466: <script type="text/javascript" language="Javascript">
                    467: // <![CDATA[
                    468:     var reseditbrowser;
1.1004    www       469:     function openresbrowser(formname,reslink) {
1.1005    www       470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       471:         var title = 'Resource_Browser';
                    472:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       473:         options += ',width=700,height=500';
1.1004    www       474:         reseditbrowser = open(url,title,options,'1');
                    475:         reseditbrowser.focus();
1.1003    www       476:     }
                    477: // ]]>
                    478: </script>
1.1004    www       479: ENDRESBRW
1.1003    www       480: }
                    481: 
1.74      www       482: sub selectstudent_link {
1.1075.2.143  raeburn   483:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  487:    if ($env{'request.course.id'}) {  
1.302     albertel  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    490: 					'/'.$env{'request.course.sec'})) {
1.111     www       491: 	   return '';
                    492:        }
1.999     www       493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   494:        if ($courseadv eq 'only') {
                    495:            $callargs .= ",'',1,'$courseadv'";
                    496:        } elsif ($courseadv eq 'none') {
                    497:            $callargs .= ",'','','$courseadv'";
                    498:        } elsif ($courseadv eq 'condition') {
                    499:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   500:        }
                    501:        return '<span class="LC_nobreak">'.
                    502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    503:               &mt('Select User').'</a></span>';
1.74      www       504:    }
1.258     albertel  505:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       506:        $callargs .= ",'',1"; 
1.793     raeburn   507:        return '<span class="LC_nobreak">'.
                    508:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    509:               &mt('Select User').'</a></span>';
1.111     www       510:    }
                    511:    return '';
1.91      www       512: }
                    513: 
1.1004    www       514: sub selectresource_link {
                    515:    my ($form,$reslink,$arg)=@_;
                    516:    
                    517:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    518:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    519:    unless ($env{'request.course.id'}) { return $arg; }
                    520:    return '<span class="LC_nobreak">'.
                    521:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    522:               $arg.'</a></span>';
                    523: }
                    524: 
                    525: 
                    526: 
1.653     raeburn   527: sub authorbrowser_javascript {
                    528:     return <<"ENDAUTHORBRW";
1.776     bisitz    529: <script type="text/javascript" language="JavaScript">
1.824     bisitz    530: // <![CDATA[
1.653     raeburn   531: var stdeditbrowser;
                    532: 
                    533: function openauthorbrowser(formname,udom) {
                    534:     var url = '/adm/pickauthor?';
                    535:     url += 'form='+formname+'&roledom='+udom;
                    536:     var title = 'Author_Browser';
                    537:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    538:     options += ',width=700,height=600';
                    539:     stdeditbrowser = open(url,title,options,'1');
                    540:     stdeditbrowser.focus();
                    541: }
                    542: 
1.824     bisitz    543: // ]]>
1.653     raeburn   544: </script>
                    545: ENDAUTHORBRW
                    546: }
                    547: 
1.91      www       548: sub coursebrowser_javascript {
1.1075.2.31  raeburn   549:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   550:         $credits_element,$instcode) = @_;
1.932     raeburn   551:     my $wintitle = 'Course_Browser';
1.931     raeburn   552:     if ($crstype eq 'Community') {
1.932     raeburn   553:         $wintitle = 'Community_Browser';
1.909     raeburn   554:     }
1.876     raeburn   555:     my $id_functions = &javascript_index_functions();
                    556:     my $output = '
1.776     bisitz    557: <script type="text/javascript" language="JavaScript">
1.824     bisitz    558: // <![CDATA[
1.468     raeburn   559:     var stdeditbrowser;'."\n";
1.876     raeburn   560: 
                    561:     $output .= <<"ENDSTDBRW";
1.909     raeburn   562:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       563:         var url = '/adm/pickcourse?';
1.895     raeburn   564:         var formid = getFormIdByName(formname);
1.876     raeburn   565:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  566:         if (domainfilter != null) {
                    567:            if (domainfilter != '') {
                    568:                url += 'domainfilter='+domainfilter+'&';
                    569: 	   }
                    570:         }
1.91      www       571:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  572: 	                            '&cdomelement='+udom+
                    573:                                     '&cnameelement='+desc;
1.468     raeburn   574:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   575:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   576:                 url += '&roleelement='+extra_element;
                    577:                 if (domainfilter == null || domainfilter == '') {
                    578:                     url += '&domainfilter='+extra_element;
                    579:                 }
1.234     raeburn   580:             }
1.468     raeburn   581:             else {
                    582:                 if (formname == 'portform') {
                    583:                     url += '&setroles='+extra_element;
1.800     raeburn   584:                 } else {
                    585:                     if (formname == 'rules') {
                    586:                         url += '&fixeddom='+extra_element; 
                    587:                     }
1.468     raeburn   588:                 }
                    589:             }     
1.230     raeburn   590:         }
1.909     raeburn   591:         if (type != null && type != '') {
                    592:             url += '&type='+type;
                    593:         }
                    594:         if (type_elem != null && type_elem != '') {
                    595:             url += '&typeelement='+type_elem;
                    596:         }
1.872     raeburn   597:         if (formname == 'ccrs') {
                    598:             var ownername = document.forms[formid].ccuname.value;
                    599:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   600:             url += '&cloner='+ownername+':'+ownerdom;
                    601:             if (type == 'Course') {
                    602:                 url += '&crscode='+document.forms[formid].crscode.value;
                    603:             }
1.1075.2.95  raeburn   604:         }
                    605:         if (formname == 'requestcrs') {
                    606:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   607:         }
1.293     raeburn   608:         if (multflag !=null && multflag != '') {
                    609:             url += '&multiple='+multflag;
                    610:         }
1.909     raeburn   611:         var title = '$wintitle';
1.91      www       612:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    613:         options += ',width=700,height=600';
                    614:         stdeditbrowser = open(url,title,options,'1');
                    615:         stdeditbrowser.focus();
                    616:     }
1.876     raeburn   617: $id_functions
                    618: ENDSTDBRW
1.1075.2.31  raeburn   619:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    620:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    621:                                       $credits_element);
1.876     raeburn   622:     }
                    623:     $output .= '
                    624: // ]]>
                    625: </script>';
                    626:     return $output;
                    627: }
                    628: 
                    629: sub javascript_index_functions {
                    630:     return <<"ENDJS";
                    631: 
                    632: function getFormIdByName(formname) {
                    633:     for (var i=0;i<document.forms.length;i++) {
                    634:         if (document.forms[i].name == formname) {
                    635:             return i;
                    636:         }
                    637:     }
                    638:     return -1;
                    639: }
                    640: 
                    641: function getIndexByName(formid,item) {
                    642:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    643:         if (document.forms[formid].elements[i].name == item) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
1.468     raeburn   649: 
1.876     raeburn   650: function getDomainFromSelectbox(formname,udom) {
                    651:     var userdom;
                    652:     var formid = getFormIdByName(formname);
                    653:     if (formid > -1) {
                    654:         var domid = getIndexByName(formid,udom);
                    655:         if (domid > -1) {
                    656:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    657:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    658:             }
                    659:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    660:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   661:             }
                    662:         }
                    663:     }
1.876     raeburn   664:     return userdom;
                    665: }
                    666: 
                    667: ENDJS
1.468     raeburn   668: 
1.876     raeburn   669: }
                    670: 
1.1017    raeburn   671: sub javascript_array_indexof {
1.1018    raeburn   672:     return <<ENDJS;
1.1017    raeburn   673: <script type="text/javascript" language="JavaScript">
                    674: // <![CDATA[
                    675: 
                    676: if (!Array.prototype.indexOf) {
                    677:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    678:         "use strict";
                    679:         if (this === void 0 || this === null) {
                    680:             throw new TypeError();
                    681:         }
                    682:         var t = Object(this);
                    683:         var len = t.length >>> 0;
                    684:         if (len === 0) {
                    685:             return -1;
                    686:         }
                    687:         var n = 0;
                    688:         if (arguments.length > 0) {
                    689:             n = Number(arguments[1]);
                    690:             if (n !== n) { // shortcut for verifying if it's NaN
                    691:                 n = 0;
                    692:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    693:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    694:             }
                    695:         }
                    696:         if (n >= len) {
                    697:             return -1;
                    698:         }
                    699:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    700:         for (; k < len; k++) {
                    701:             if (k in t && t[k] === searchElement) {
                    702:                 return k;
                    703:             }
                    704:         }
                    705:         return -1;
                    706:     }
                    707: }
                    708: 
                    709: // ]]>
                    710: </script>
                    711: 
                    712: ENDJS
                    713: 
                    714: }
                    715: 
1.876     raeburn   716: sub userbrowser_javascript {
                    717:     my $id_functions = &javascript_index_functions();
                    718:     return <<"ENDUSERBRW";
                    719: 
1.888     raeburn   720: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   721:     var url = '/adm/pickuser?';
                    722:     var userdom = getDomainFromSelectbox(formname,udom);
                    723:     if (userdom != null) {
                    724:        if (userdom != '') {
                    725:            url += 'srchdom='+userdom+'&';
                    726:        }
                    727:     }
                    728:     url += 'form=' + formname + '&unameelement='+uname+
                    729:                                 '&udomelement='+udom+
                    730:                                 '&ulastelement='+ulast+
                    731:                                 '&ufirstelement='+ufirst+
                    732:                                 '&uemailelement='+uemail+
1.881     raeburn   733:                                 '&hideudomelement='+hideudom+
                    734:                                 '&coursedom='+crsdom;
1.888     raeburn   735:     if ((caller != null) && (caller != undefined)) {
                    736:         url += '&caller='+caller;
                    737:     }
1.876     raeburn   738:     var title = 'User_Browser';
                    739:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    740:     options += ',width=700,height=600';
                    741:     var stdeditbrowser = open(url,title,options,'1');
                    742:     stdeditbrowser.focus();
                    743: }
                    744: 
1.888     raeburn   745: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   746:     var formid = getFormIdByName(formname);
                    747:     if (formid > -1) {
1.888     raeburn   748:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   749:         var domid = getIndexByName(formid,udom);
                    750:         var hidedomid = getIndexByName(formid,origdom);
                    751:         if (hidedomid > -1) {
                    752:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   753:             var unameval = document.forms[formid].elements[unameid].value;
                    754:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    755:                 if (domid > -1) {
                    756:                     var slct = document.forms[formid].elements[domid];
                    757:                     if (slct.type == 'select-one') {
                    758:                         var i;
                    759:                         for (i=0;i<slct.length;i++) {
                    760:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    761:                         }
                    762:                     }
                    763:                     if (slct.type == 'hidden') {
                    764:                         slct.value = fixeddom;
1.876     raeburn   765:                     }
                    766:                 }
1.468     raeburn   767:             }
                    768:         }
                    769:     }
1.876     raeburn   770:     return;
                    771: }
                    772: 
                    773: $id_functions
                    774: ENDUSERBRW
1.468     raeburn   775: }
                    776: 
                    777: sub setsec_javascript {
1.1075.2.31  raeburn   778:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   779:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    780:         $communityrolestr);
                    781:     if ($role_element ne '') {
                    782:         my @allroles = ('st','ta','ep','in','ad');
                    783:         foreach my $crstype ('Course','Community') {
                    784:             if ($crstype eq 'Community') {
                    785:                 foreach my $role (@allroles) {
                    786:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    787:                 }
                    788:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    789:             } else {
                    790:                 foreach my $role (@allroles) {
                    791:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    792:                 }
                    793:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    794:             }
                    795:         }
                    796:         $rolestr = '"'.join('","',@allroles).'"';
                    797:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    798:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    799:     }
1.468     raeburn   800:     my $setsections = qq|
                    801: function setSect(sectionlist) {
1.629     raeburn   802:     var sectionsArray = new Array();
                    803:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    804:         sectionsArray = sectionlist.split(",");
                    805:     }
1.468     raeburn   806:     var numSections = sectionsArray.length;
                    807:     document.$formname.$sec_element.length = 0;
                    808:     if (numSections == 0) {
                    809:         document.$formname.$sec_element.multiple=false;
                    810:         document.$formname.$sec_element.size=1;
                    811:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    812:     } else {
                    813:         if (numSections == 1) {
                    814:             document.$formname.$sec_element.multiple=false;
                    815:             document.$formname.$sec_element.size=1;
                    816:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    817:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    818:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    819:         } else {
                    820:             for (var i=0; i<numSections; i++) {
                    821:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    822:             }
                    823:             document.$formname.$sec_element.multiple=true
                    824:             if (numSections < 3) {
                    825:                 document.$formname.$sec_element.size=numSections;
                    826:             } else {
                    827:                 document.$formname.$sec_element.size=3;
                    828:             }
                    829:             document.$formname.$sec_element.options[0].selected = false
                    830:         }
                    831:     }
1.91      www       832: }
1.905     raeburn   833: 
                    834: function setRole(crstype) {
1.468     raeburn   835: |;
1.905     raeburn   836:     if ($role_element eq '') {
                    837:         $setsections .= '    return;
                    838: }
                    839: ';
                    840:     } else {
                    841:         $setsections .= qq|
                    842:     var elementLength = document.$formname.$role_element.length;
                    843:     var allroles = Array($rolestr);
                    844:     var courserolenames = Array($courserolestr);
                    845:     var communityrolenames = Array($communityrolestr);
                    846:     if (elementLength != undefined) {
                    847:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    848:             if (crstype == 'Course') {
                    849:                 return;
                    850:             } else {
                    851:                 allroles[5] = 'co';
                    852:                 for (var i=0; i<6; i++) {
                    853:                     document.$formname.$role_element.options[i].value = allroles[i];
                    854:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    855:                 }
                    856:             }
                    857:         } else {
                    858:             if (crstype == 'Community') {
                    859:                 return;
                    860:             } else {
                    861:                 allroles[5] = 'cc';
                    862:                 for (var i=0; i<6; i++) {
                    863:                     document.$formname.$role_element.options[i].value = allroles[i];
                    864:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    865:                 }
                    866:             }
                    867:         }
                    868:     }
                    869:     return;
                    870: }
                    871: |;
                    872:     }
1.1075.2.31  raeburn   873:     if ($credits_element) {
                    874:         $setsections .= qq|
                    875: function setCredits(defaultcredits) {
                    876:     document.$formname.$credits_element.value = defaultcredits;
                    877:     return;
                    878: }
                    879: |;
                    880:     }
1.468     raeburn   881:     return $setsections;
                    882: }
                    883: 
1.91      www       884: sub selectcourse_link {
1.909     raeburn   885:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    886:        $typeelement) = @_;
                    887:    my $type = $selecttype;
1.871     raeburn   888:    my $linktext = &mt('Select Course');
                    889:    if ($selecttype eq 'Community') {
1.909     raeburn   890:        $linktext = &mt('Select Community');
1.906     raeburn   891:    } elsif ($selecttype eq 'Course/Community') {
                    892:        $linktext = &mt('Select Course/Community');
1.909     raeburn   893:        $type = '';
1.1019    raeburn   894:    } elsif ($selecttype eq 'Select') {
                    895:        $linktext = &mt('Select');
                    896:        $type = '';
1.871     raeburn   897:    }
1.787     bisitz    898:    return '<span class="LC_nobreak">'
                    899:          ."<a href='"
                    900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   903:          ."'>".$linktext.'</a>'
1.787     bisitz    904:          .'</span>';
1.74      www       905: }
1.42      matthew   906: 
1.653     raeburn   907: sub selectauthor_link {
                    908:    my ($form,$udom)=@_;
                    909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    910:           &mt('Select Author').'</a>';
                    911: }
                    912: 
1.876     raeburn   913: sub selectuser_link {
1.881     raeburn   914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   915:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   918:            ');">'.$linktext.'</a>';
1.876     raeburn   919: }
                    920: 
1.273     raeburn   921: sub check_uncheck_jscript {
                    922:     my $jscript = <<"ENDSCRT";
                    923: function checkAll(field) {
                    924:     if (field.length > 0) {
                    925:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   926:             if (!field[i].disabled) {
                    927:                 field[i].checked = true;
                    928:             }
1.273     raeburn   929:         }
                    930:     } else {
1.1075.2.14  raeburn   931:         if (!field.disabled) {
                    932:             field.checked = true;
                    933:         }
1.273     raeburn   934:     }
                    935: }
                    936:  
                    937: function uncheckAll(field) {
                    938:     if (field.length > 0) {
                    939:         for (i = 0; i < field.length; i++) {
                    940:             field[i].checked = false ;
1.543     albertel  941:         }
                    942:     } else {
1.273     raeburn   943:         field.checked = false ;
                    944:     }
                    945: }
                    946: ENDSCRT
                    947:     return $jscript;
                    948: }
                    949: 
1.656     www       950: sub select_timezone {
1.1075.2.115  raeburn   951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   953:    if ($includeempty) {
                    954:        $output .= '<option value=""';
                    955:        if (($selected eq '') || ($selected eq 'local')) {
                    956:            $output .= ' selected="selected" ';
                    957:        }
                    958:        $output .= '> </option>';
                    959:    }
1.657     raeburn   960:    my @timezones = DateTime::TimeZone->all_names;
                    961:    foreach my $tzone (@timezones) {
                    962:        $output.= '<option value="'.$tzone.'"';
                    963:        if ($tzone eq $selected) {
                    964:            $output.=' selected="selected"';
                    965:        }
                    966:        $output.=">$tzone</option>\n";
1.656     www       967:    }
                    968:    $output.="</select>";
                    969:    return $output;
                    970: }
1.273     raeburn   971: 
1.687     raeburn   972: sub select_datelocale {
1.1075.2.115  raeburn   973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   975:     if ($includeempty) {
                    976:         $output .= '<option value=""';
                    977:         if ($selected eq '') {
                    978:             $output .= ' selected="selected" ';
                    979:         }
                    980:         $output .= '> </option>';
                    981:     }
1.1075.2.102  raeburn   982:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   983:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   984:     my @locales = DateTime::Locale->ids();
                    985:     foreach my $id (@locales) {
                    986:         if ($id ne '') {
                    987:             my ($en_terr,$native_terr);
                    988:             my $loc = DateTime::Locale->load($id);
                    989:             if (ref($loc)) {
                    990:                 $en_terr = $loc->name();
                    991:                 $native_terr = $loc->native_name();
1.687     raeburn   992:                 if (grep(/^en$/,@languages) || !@languages) {
                    993:                     if ($en_terr ne '') {
                    994:                         $locale_names{$id} = '('.$en_terr.')';
                    995:                     } elsif ($native_terr ne '') {
                    996:                         $locale_names{$id} = $native_terr;
                    997:                     }
                    998:                 } else {
                    999:                     if ($native_terr ne '') {
                   1000:                         $locale_names{$id} = $native_terr.' ';
                   1001:                     } elsif ($en_terr ne '') {
                   1002:                         $locale_names{$id} = '('.$en_terr.')';
                   1003:                     }
                   1004:                 }
1.1075.2.94  raeburn  1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1006:                 push(@possibles,$id);
1.687     raeburn  1007:             }
                   1008:         }
                   1009:     }
                   1010:     foreach my $item (sort(@possibles)) {
                   1011:         $output.= '<option value="'.$item.'"';
                   1012:         if ($item eq $selected) {
                   1013:             $output.=' selected="selected"';
                   1014:         }
                   1015:         $output.=">$item";
                   1016:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1017:             $output.='  '.$locale_names{$item};
1.687     raeburn  1018:         }
                   1019:         $output.="</option>\n";
                   1020:     }
                   1021:     $output.="</select>";
                   1022:     return $output;
                   1023: }
                   1024: 
1.792     raeburn  1025: sub select_language {
1.1075.2.115  raeburn  1026:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1027:     my %langchoices;
                   1028:     if ($includeempty) {
1.1075.2.32  raeburn  1029:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1030:     }
                   1031:     foreach my $id (&languageids()) {
                   1032:         my $code = &supportedlanguagecode($id);
                   1033:         if ($code) {
                   1034:             $langchoices{$code} = &plainlanguagedescription($id);
                   1035:         }
                   1036:     }
1.1075.2.32  raeburn  1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1039: }
                   1040: 
1.42      matthew  1041: =pod
1.36      matthew  1042: 
1.648     raeburn  1043: =item * &linked_select_forms(...)
1.36      matthew  1044: 
                   1045: linked_select_forms returns a string containing a <script></script> block
                   1046: and html for two <select> menus.  The select menus will be linked in that
                   1047: changing the value of the first menu will result in new values being placed
                   1048: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1049: order unless a defined order is provided.
1.36      matthew  1050: 
                   1051: linked_select_forms takes the following ordered inputs:
                   1052: 
                   1053: =over 4
                   1054: 
1.112     bowersj2 1055: =item * $formname, the name of the <form> tag
1.36      matthew  1056: 
1.112     bowersj2 1057: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $firstdefault, the default value for the first menu
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1066: 
1.609     raeburn  1067: =item * $menuorder, the order of values in the first menu
                   1068: 
1.1075.2.31  raeburn  1069: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1070:         event for the first <select> tag
                   1071: 
                   1072: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1073:         event for the second <select> tag
                   1074: 
1.41      ng       1075: =back 
                   1076: 
1.36      matthew  1077: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1078: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1079: values for the first select menu.  The text that coincides with the 
1.41      ng       1080: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1081: and text for the second menu are given in the hash pointed to by 
                   1082: $menu{$choice1}->{'select2'}.  
                   1083: 
1.112     bowersj2 1084:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1085:                        default => "B3",
                   1086:                        select2 => { 
                   1087:                            B1 => "Choice B1",
                   1088:                            B2 => "Choice B2",
                   1089:                            B3 => "Choice B3",
                   1090:                            B4 => "Choice B4"
1.609     raeburn  1091:                            },
                   1092:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1093:                    },
                   1094:                A2 => { text =>"Choice A2" ,
                   1095:                        default => "C2",
                   1096:                        select2 => { 
                   1097:                            C1 => "Choice C1",
                   1098:                            C2 => "Choice C2",
                   1099:                            C3 => "Choice C3"
1.609     raeburn  1100:                            },
                   1101:                        order => ['C2','C1','C3'],
1.112     bowersj2 1102:                    },
                   1103:                A3 => { text =>"Choice A3" ,
                   1104:                        default => "D6",
                   1105:                        select2 => { 
                   1106:                            D1 => "Choice D1",
                   1107:                            D2 => "Choice D2",
                   1108:                            D3 => "Choice D3",
                   1109:                            D4 => "Choice D4",
                   1110:                            D5 => "Choice D5",
                   1111:                            D6 => "Choice D6",
                   1112:                            D7 => "Choice D7"
1.609     raeburn  1113:                            },
                   1114:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1115:                    }
                   1116:                );
1.36      matthew  1117: 
                   1118: =cut
                   1119: 
                   1120: sub linked_select_forms {
                   1121:     my ($formname,
                   1122:         $middletext,
                   1123:         $firstdefault,
                   1124:         $firstselectname,
                   1125:         $secondselectname, 
1.609     raeburn  1126:         $hashref,
                   1127:         $menuorder,
1.1075.2.31  raeburn  1128:         $onchangefirst,
                   1129:         $onchangesecond
1.36      matthew  1130:         ) = @_;
                   1131:     my $second = "document.$formname.$secondselectname";
                   1132:     my $first = "document.$formname.$firstselectname";
                   1133:     # output the javascript to do the changing
                   1134:     my $result = '';
1.776     bisitz   1135:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1136:     $result.="// <![CDATA[\n";
1.36      matthew  1137:     $result.="var select2data = new Object();\n";
                   1138:     $" = '","';
                   1139:     my $debug = '';
                   1140:     foreach my $s1 (sort(keys(%$hashref))) {
                   1141:         $result.="select2data.d_$s1 = new Object();\n";        
                   1142:         $result.="select2data.d_$s1.def = new String('".
                   1143:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1144:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1145:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1146:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1147:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1148:         }
1.36      matthew  1149:         $result.="\"@s2values\");\n";
                   1150:         $result.="select2data.d_$s1.texts = new Array(";        
                   1151:         my @s2texts;
                   1152:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1153:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1154:         }
                   1155:         $result.="\"@s2texts\");\n";
                   1156:     }
                   1157:     $"=' ';
                   1158:     $result.= <<"END";
                   1159: 
                   1160: function select1_changed() {
                   1161:     // Determine new choice
                   1162:     var newvalue = "d_" + $first.value;
                   1163:     // update select2
                   1164:     var values     = select2data[newvalue].values;
                   1165:     var texts      = select2data[newvalue].texts;
                   1166:     var select2def = select2data[newvalue].def;
                   1167:     var i;
                   1168:     // out with the old
                   1169:     for (i = 0; i < $second.options.length; i++) {
                   1170:         $second.options[i] = null;
                   1171:     }
                   1172:     // in with the nuclear
                   1173:     for (i=0;i<values.length; i++) {
                   1174:         $second.options[i] = new Option(values[i]);
1.143     matthew  1175:         $second.options[i].value = values[i];
1.36      matthew  1176:         $second.options[i].text = texts[i];
                   1177:         if (values[i] == select2def) {
                   1178:             $second.options[i].selected = true;
                   1179:         }
                   1180:     }
                   1181: }
1.824     bisitz   1182: // ]]>
1.36      matthew  1183: </script>
                   1184: END
                   1185:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1186:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1187:     my @order = sort(keys(%{$hashref}));
                   1188:     if (ref($menuorder) eq 'ARRAY') {
                   1189:         @order = @{$menuorder};
                   1190:     }
                   1191:     foreach my $value (@order) {
1.36      matthew  1192:         $result.="    <option value=\"$value\" ";
1.253     albertel 1193:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1194:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1195:     }
                   1196:     $result .= "</select>\n";
                   1197:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1198:     $result .= $middletext;
1.1075.2.31  raeburn  1199:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1200:     if ($onchangesecond) {
                   1201:         $result .= ' onchange="'.$onchangesecond.'"';
                   1202:     }
                   1203:     $result .= ">\n";
1.36      matthew  1204:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1205:     
                   1206:     my @secondorder = sort(keys(%select2));
                   1207:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1208:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1209:     }
                   1210:     foreach my $value (@secondorder) {
1.36      matthew  1211:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1212:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1213:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1214:     }
                   1215:     $result .= "</select>\n";
                   1216:     #    return $debug;
                   1217:     return $result;
                   1218: }   #  end of sub linked_select_forms {
                   1219: 
1.45      matthew  1220: =pod
1.44      bowersj2 1221: 
1.973     raeburn  1222: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1223: 
1.112     bowersj2 1224: Returns a string corresponding to an HTML link to the given help
                   1225: $topic, where $topic corresponds to the name of a .tex file in
                   1226: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1227: spaces. 
                   1228: 
                   1229: $text will optionally be linked to the same topic, allowing you to
                   1230: link text in addition to the graphic. If you do not want to link
                   1231: text, but wish to specify one of the later parameters, pass an
                   1232: empty string. 
                   1233: 
                   1234: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1235: the link will not open a new window. If false, the link will open
                   1236: a new window using Javascript. (Default is false.) 
                   1237: 
                   1238: $width and $height are optional numerical parameters that will
                   1239: override the width and height of the popped up window, which may
1.973     raeburn  1240: be useful for certain help topics with big pictures included.
                   1241: 
                   1242: $imgid is the id of the img tag used for the help icon. This may be
                   1243: used in a javascript call to switch the image src.  See 
                   1244: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1245: 
                   1246: =cut
                   1247: 
                   1248: sub help_open_topic {
1.973     raeburn  1249:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1250:     $text = "" if (not defined $text);
1.44      bowersj2 1251:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1252:     $width = 500 if (not defined $width);
1.44      bowersj2 1253:     $height = 400 if (not defined $height);
                   1254:     my $filename = $topic;
                   1255:     $filename =~ s/ /_/g;
                   1256: 
1.48      bowersj2 1257:     my $template = "";
                   1258:     my $link;
1.572     banghart 1259:     
1.159     www      1260:     $topic=~s/\W/\_/g;
1.44      bowersj2 1261: 
1.572     banghart 1262:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1263:         if ($env{'browser.mobile'}) {
                   1264: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1265:         } else {
                   1266:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1267:         }
1.1037    www      1268:     } elsif ($stayOnPage eq 'popup') {
                   1269:         $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 1270:     } else {
1.48      bowersj2 1271: 	$link = "/adm/help/${filename}.hlp";
                   1272:     }
                   1273: 
                   1274:     # Add the text
1.755     neumanie 1275:     if ($text ne "") {	
1.763     bisitz   1276: 	$template.='<span class="LC_help_open_topic">'
                   1277:                   .'<a target="_top" href="'.$link.'">'
                   1278:                   .$text.'</a>';
1.48      bowersj2 1279:     }
                   1280: 
1.763     bisitz   1281:     # (Always) Add the graphic
1.179     matthew  1282:     my $title = &mt('Online Help');
1.667     raeburn  1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1284:     if ($imgid ne '') {
                   1285:         $imgid = ' id="'.$imgid.'"';
                   1286:     }
1.763     bisitz   1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1288:               .'<img src="'.$helpicon.'" border="0"'
                   1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1291:               .' /></a>';
                   1292:     if ($text ne "") {	
                   1293:         $template.='</span>';
                   1294:     }
1.44      bowersj2 1295:     return $template;
                   1296: 
1.106     bowersj2 1297: }
                   1298: 
                   1299: # This is a quicky function for Latex cheatsheet editing, since it 
                   1300: # appears in at least four places
                   1301: sub helpLatexCheatsheet {
1.1037    www      1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1303:     my $out;
1.106     bowersj2 1304:     my $addOther = '';
1.732     raeburn  1305:     if ($topic) {
1.1037    www      1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1307:     }
                   1308:     $out = '<span>' # Start cheatsheet
                   1309: 	  .$addOther
                   1310:           .'<span>'
1.1037    www      1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1312: 	  .'</span> <span>'
1.1037    www      1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span>';
1.732     raeburn  1315:     unless ($not_author) {
1.763     bisitz   1316:         $out .= ' <span>'
1.1037    www      1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1318: 	       .'</span> <span>'
1.1075.2.78  raeburn  1319:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320:                .'</span>';
1.732     raeburn  1321:     }
1.763     bisitz   1322:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1323:     return $out;
1.172     www      1324: }
                   1325: 
1.430     albertel 1326: sub general_help {
                   1327:     my $helptopic='Student_Intro';
                   1328:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1329: 	$helptopic='Authoring_Intro';
1.907     raeburn  1330:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1331: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1332:     } elsif ($env{'request.role'}=~/^dc/) {
                   1333:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1334:     }
                   1335:     return $helptopic;
                   1336: }
                   1337: 
                   1338: sub update_help_link {
                   1339:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1340:     my $origurl = $ENV{'REQUEST_URI'};
                   1341:     $origurl=~s|^/~|/priv/|;
                   1342:     my $timestamp = time;
                   1343:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1344:         $$datum = &escape($$datum);
                   1345:     }
                   1346: 
                   1347:     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";
                   1348:     my $output .= <<"ENDOUTPUT";
                   1349: <script type="text/javascript">
1.824     bisitz   1350: // <![CDATA[
1.430     albertel 1351: banner_link = '$banner_link';
1.824     bisitz   1352: // ]]>
1.430     albertel 1353: </script>
                   1354: ENDOUTPUT
                   1355:     return $output;
                   1356: }
                   1357: 
                   1358: # now just updates the help link and generates a blue icon
1.193     raeburn  1359: sub help_open_menu {
1.430     albertel 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1361: 	= @_;    
1.949     droeschl 1362:     $stayOnPage = 1;
1.430     albertel 1363:     my $output;
                   1364:     if ($component_help) {
                   1365: 	if (!$text) {
                   1366: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1367: 				       $width,$height);
                   1368: 	} else {
                   1369: 	    my $help_text;
                   1370: 	    $help_text=&unescape($topic);
                   1371: 	    $output='<table><tr><td>'.
                   1372: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1373: 				 $width,$height).'</td></tr></table>';
                   1374: 	}
                   1375:     }
                   1376:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1377:     return $output.$banner_link;
                   1378: }
                   1379: 
                   1380: sub top_nav_help {
                   1381:     my ($text) = @_;
1.436     albertel 1382:     $text = &mt($text);
1.1075.2.60  raeburn  1383:     my $stay_on_page;
                   1384:     unless ($env{'environment.remote'} eq 'on') {
                   1385:         $stay_on_page = 1;
                   1386:     }
1.1075.2.61  raeburn  1387:     my ($link,$banner_link);
                   1388:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1389:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1390: 	                         : "javascript:helpMenu('open')";
                   1391:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1392:     }
1.201     raeburn  1393:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1394:     if ($link) {
                   1395:         return <<"END";
1.436     albertel 1396: $banner_link
1.1075.2.56  raeburn  1397: <a href="$link" title="$title">$text</a>
1.436     albertel 1398: END
1.1075.2.61  raeburn  1399:     } else {
                   1400:         return '&nbsp;'.$text.'&nbsp;';
                   1401:     }
1.436     albertel 1402: }
                   1403: 
                   1404: sub help_menu_js {
1.1075.2.52  raeburn  1405:     my ($httphost) = @_;
1.949     droeschl 1406:     my $stayOnPage = 1;
1.436     albertel 1407:     my $width = 620;
                   1408:     my $height = 600;
1.430     albertel 1409:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1410:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1411:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1412:     my $start_page =
                   1413:         &Apache::loncommon::start_page('Help Menu', undef,
                   1414: 				       {'frameset'    => 1,
                   1415: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1416:                                         'use_absolute' => $httphost,
1.331     albertel 1417: 					'add_entries' => {
                   1418: 					    'border' => '0',
1.579     raeburn  1419: 					    'rows'   => "110,*",},});
1.331     albertel 1420:     my $end_page =
                   1421:         &Apache::loncommon::end_page({'frameset' => 1,
                   1422: 				      'js_ready' => 1,});
                   1423: 
1.436     albertel 1424:     my $template .= <<"ENDTEMPLATE";
                   1425: <script type="text/javascript">
1.877     bisitz   1426: // <![CDATA[
1.253     albertel 1427: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1428: var banner_link = '';
1.243     raeburn  1429: function helpMenu(target) {
                   1430:     var caller = this;
                   1431:     if (target == 'open') {
                   1432:         var newWindow = null;
                   1433:         try {
1.262     albertel 1434:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1435:         }
                   1436:         catch(error) {
                   1437:             writeHelp(caller);
                   1438:             return;
                   1439:         }
                   1440:         if (newWindow) {
                   1441:             caller = newWindow;
                   1442:         }
1.193     raeburn  1443:     }
1.243     raeburn  1444:     writeHelp(caller);
                   1445:     return;
                   1446: }
                   1447: function writeHelp(caller) {
1.1075.2.61  raeburn  1448:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1449:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1450:     caller.document.close();
                   1451:     caller.focus();
1.193     raeburn  1452: }
1.877     bisitz   1453: // END LON-CAPA Internal -->
1.253     albertel 1454: // ]]>
1.436     albertel 1455: </script>
1.193     raeburn  1456: ENDTEMPLATE
                   1457:     return $template;
                   1458: }
                   1459: 
1.172     www      1460: sub help_open_bug {
                   1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1462:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1463:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1464:     $text = "" if (not defined $text);
                   1465: 	$stayOnPage=1;
1.184     albertel 1466:     $width = 600 if (not defined $width);
                   1467:     $height = 600 if (not defined $height);
1.172     www      1468: 
                   1469:     $topic=~s/\W+/\+/g;
                   1470:     my $link='';
                   1471:     my $template='';
1.379     albertel 1472:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1473: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1474:     if (!$stayOnPage)
                   1475:     {
                   1476: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1477:     }
                   1478:     else
                   1479:     {
                   1480: 	$link = $url;
                   1481:     }
                   1482:     # Add the text
                   1483:     if ($text ne "")
                   1484:     {
                   1485: 	$template .= 
                   1486:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1487:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1488:     }
                   1489: 
                   1490:     # Add the graphic
1.179     matthew  1491:     my $title = &mt('Report a Bug');
1.215     albertel 1492:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1493:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1494:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1495: ENDTEMPLATE
                   1496:     if ($text ne '') { $template.='</td></tr></table>' };
                   1497:     return $template;
                   1498: 
                   1499: }
                   1500: 
                   1501: sub help_open_faq {
                   1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1503:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1504:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1505:     $text = "" if (not defined $text);
                   1506: 	$stayOnPage=1;
                   1507:     $width = 350 if (not defined $width);
                   1508:     $height = 400 if (not defined $height);
                   1509: 
                   1510:     $topic=~s/\W+/\+/g;
                   1511:     my $link='';
                   1512:     my $template='';
                   1513:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1514:     if (!$stayOnPage)
                   1515:     {
                   1516: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1517:     }
                   1518:     else
                   1519:     {
                   1520: 	$link = $url;
                   1521:     }
                   1522: 
                   1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
1.173     www      1527:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1528:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('View the FAQ');
1.215     albertel 1533:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1535:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
1.44      bowersj2 1540: }
1.37      matthew  1541: 
1.180     matthew  1542: ###############################################################
                   1543: ###############################################################
                   1544: 
1.45      matthew  1545: =pod
                   1546: 
1.648     raeburn  1547: =item * &change_content_javascript():
1.256     matthew  1548: 
                   1549: This and the next function allow you to create small sections of an
                   1550: otherwise static HTML page that you can update on the fly with
                   1551: Javascript, even in Netscape 4.
                   1552: 
                   1553: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1554: must be written to the HTML page once. It will prove the Javascript
                   1555: function "change(name, content)". Calling the change function with the
                   1556: name of the section 
                   1557: you want to update, matching the name passed to C<changable_area>, and
                   1558: the new content you want to put in there, will put the content into
                   1559: that area.
                   1560: 
                   1561: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1562: to contain room for the original contents. You need to "make space"
                   1563: for whatever changes you wish to make, and be B<sure> to check your
                   1564: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1565: it's adequate for updating a one-line status display, but little more.
                   1566: This script will set the space to 100% width, so you only need to
                   1567: worry about height in Netscape 4.
                   1568: 
                   1569: Modern browsers are much less limiting, and if you can commit to the
                   1570: user not using Netscape 4, this feature may be used freely with
                   1571: pretty much any HTML.
                   1572: 
                   1573: =cut
                   1574: 
                   1575: sub change_content_javascript {
                   1576:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1577:     if ($env{'browser.type'} eq 'netscape' &&
                   1578: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1579: 	return (<<NETSCAPE4);
                   1580: 	function change(name, content) {
                   1581: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1582: 	    doc.open();
                   1583: 	    doc.write(content);
                   1584: 	    doc.close();
                   1585: 	}
                   1586: NETSCAPE4
                   1587:     } else {
                   1588: 	# Otherwise, we need to use semi-standards-compliant code
                   1589: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1590: 	# is really scary, and every useful browser supports it
                   1591: 	return (<<DOMBASED);
                   1592: 	function change(name, content) {
                   1593: 	    element = document.getElementById(name);
                   1594: 	    element.innerHTML = content;
                   1595: 	}
                   1596: DOMBASED
                   1597:     }
                   1598: }
                   1599: 
                   1600: =pod
                   1601: 
1.648     raeburn  1602: =item * &changable_area($name,$origContent):
1.256     matthew  1603: 
                   1604: This provides a "changable area" that can be modified on the fly via
                   1605: the Javascript code provided in C<change_content_javascript>. $name is
                   1606: the name you will use to reference the area later; do not repeat the
                   1607: same name on a given HTML page more then once. $origContent is what
                   1608: the area will originally contain, which can be left blank.
                   1609: 
                   1610: =cut
                   1611: 
                   1612: sub changable_area {
                   1613:     my ($name, $origContent) = @_;
                   1614: 
1.258     albertel 1615:     if ($env{'browser.type'} eq 'netscape' &&
                   1616: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1617: 	# If this is netscape 4, we need to use the Layer tag
                   1618: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1619:     } else {
                   1620: 	return "<span id='$name'>$origContent</span>";
                   1621:     }
                   1622: }
                   1623: 
                   1624: =pod
                   1625: 
1.648     raeburn  1626: =item * &viewport_geometry_js 
1.590     raeburn  1627: 
                   1628: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1629: 
                   1630: =cut
                   1631: 
                   1632: 
                   1633: sub viewport_geometry_js { 
                   1634:     return <<"GEOMETRY";
                   1635: var Geometry = {};
                   1636: function init_geometry() {
                   1637:     if (Geometry.init) { return };
                   1638:     Geometry.init=1;
                   1639:     if (window.innerHeight) {
                   1640:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1641:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1642:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1643:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1644:     }
                   1645:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1646:         Geometry.getViewportHeight =
                   1647:             function() { return document.documentElement.clientHeight; };
                   1648:         Geometry.getViewportWidth =
                   1649:             function() { return document.documentElement.clientWidth; };
                   1650: 
                   1651:         Geometry.getHorizontalScroll =
                   1652:             function() { return document.documentElement.scrollLeft; };
                   1653:         Geometry.getVerticalScroll =
                   1654:             function() { return document.documentElement.scrollTop; };
                   1655:     }
                   1656:     else if (document.body.clientHeight) {
                   1657:         Geometry.getViewportHeight =
                   1658:             function() { return document.body.clientHeight; };
                   1659:         Geometry.getViewportWidth =
                   1660:             function() { return document.body.clientWidth; };
                   1661:         Geometry.getHorizontalScroll =
                   1662:             function() { return document.body.scrollLeft; };
                   1663:         Geometry.getVerticalScroll =
                   1664:             function() { return document.body.scrollTop; };
                   1665:     }
                   1666: }
                   1667: 
                   1668: GEOMETRY
                   1669: }
                   1670: 
                   1671: =pod
                   1672: 
1.648     raeburn  1673: =item * &viewport_size_js()
1.590     raeburn  1674: 
                   1675: 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. 
                   1676: 
                   1677: =cut
                   1678: 
                   1679: sub viewport_size_js {
                   1680:     my $geometry = &viewport_geometry_js();
                   1681:     return <<"DIMS";
                   1682: 
                   1683: $geometry
                   1684: 
                   1685: function getViewportDims(width,height) {
                   1686:     init_geometry();
                   1687:     width.value = Geometry.getViewportWidth();
                   1688:     height.value = Geometry.getViewportHeight();
                   1689:     return;
                   1690: }
                   1691: 
                   1692: DIMS
                   1693: }
                   1694: 
                   1695: =pod
                   1696: 
1.648     raeburn  1697: =item * &resize_textarea_js()
1.565     albertel 1698: 
                   1699: emits the needed javascript to resize a textarea to be as big as possible
                   1700: 
                   1701: creates a function resize_textrea that takes two IDs first should be
                   1702: the id of the element to resize, second should be the id of a div that
                   1703: surrounds everything that comes after the textarea, this routine needs
                   1704: to be attached to the <body> for the onload and onresize events.
                   1705: 
1.648     raeburn  1706: =back
1.565     albertel 1707: 
                   1708: =cut
                   1709: 
                   1710: sub resize_textarea_js {
1.590     raeburn  1711:     my $geometry = &viewport_geometry_js();
1.565     albertel 1712:     return <<"RESIZE";
                   1713:     <script type="text/javascript">
1.824     bisitz   1714: // <![CDATA[
1.590     raeburn  1715: $geometry
1.565     albertel 1716: 
1.588     albertel 1717: function getX(element) {
                   1718:     var x = 0;
                   1719:     while (element) {
                   1720: 	x += element.offsetLeft;
                   1721: 	element = element.offsetParent;
                   1722:     }
                   1723:     return x;
                   1724: }
                   1725: function getY(element) {
                   1726:     var y = 0;
                   1727:     while (element) {
                   1728: 	y += element.offsetTop;
                   1729: 	element = element.offsetParent;
                   1730:     }
                   1731:     return y;
                   1732: }
                   1733: 
                   1734: 
1.565     albertel 1735: function resize_textarea(textarea_id,bottom_id) {
                   1736:     init_geometry();
                   1737:     var textarea        = document.getElementById(textarea_id);
                   1738:     //alert(textarea);
                   1739: 
1.588     albertel 1740:     var textarea_top    = getY(textarea);
1.565     albertel 1741:     var textarea_height = textarea.offsetHeight;
                   1742:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1743:     var bottom_top      = getY(bottom);
1.565     albertel 1744:     var bottom_height   = bottom.offsetHeight;
                   1745:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1746:     var fudge           = 23;
1.565     albertel 1747:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1748:     if (new_height < 300) {
                   1749: 	new_height = 300;
                   1750:     }
                   1751:     textarea.style.height=new_height+'px';
                   1752: }
1.824     bisitz   1753: // ]]>
1.565     albertel 1754: </script>
                   1755: RESIZE
                   1756: 
                   1757: }
                   1758: 
1.1075.2.112  raeburn  1759: sub colorfuleditor_js {
                   1760:     return <<"COLORFULEDIT"
                   1761: <script type="text/javascript">
                   1762: // <![CDATA[>
                   1763:     function fold_box(curDepth, lastresource){
                   1764: 
                   1765:     // we need a list because there can be several blocks you need to fold in one tag
                   1766:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1767:     // but there is only one folding button per tag
                   1768:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1769: 
                   1770:         if(block.item(0).style.display == 'none'){
                   1771: 
                   1772:             foldbutton.value = '@{[&mt("Hide")]}';
                   1773:             for (i = 0; i < block.length; i++){
                   1774:                 block.item(i).style.display = '';
                   1775:             }
                   1776:         }else{
                   1777: 
                   1778:             foldbutton.value = '@{[&mt("Show")]}';
                   1779:             for (i = 0; i < block.length; i++){
                   1780:                 // block.item(i).style.visibility = 'collapse';
                   1781:                 block.item(i).style.display = 'none';
                   1782:             }
                   1783:         };
                   1784:         saveState(lastresource);
                   1785:     }
                   1786: 
                   1787:     function saveState (lastresource) {
                   1788: 
                   1789:         var tag_list = getTagList();
                   1790:         if(tag_list != null){
                   1791:             var timestamp = new Date().getTime();
                   1792:             var key = lastresource;
                   1793: 
                   1794:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1795:             // starting with timestamp
                   1796:             var value = timestamp+';';
                   1797: 
                   1798:             // building the list of key-value pairs
                   1799:             for(var i = 0; i < tag_list.length; i++){
                   1800:                 value += tag_list[i]+',';
                   1801:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1802:             }
                   1803: 
                   1804:             // only iterate whole storage if nothing to override
                   1805:             if(localStorage.getItem(key) == null){
                   1806: 
                   1807:                 // prevent storage from growing large
                   1808:                 if(localStorage.length > 50){
                   1809:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1810:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1811:                     var oldest_key;
                   1812: 
                   1813:                     for(var i = 1; i < localStorage.length; i++){
                   1814:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1815:                             oldest_key = localStorage.key(i);
                   1816:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1817:                         }
                   1818:                     }
                   1819:                     localStorage.removeItem(oldest_key);
                   1820:                 }
                   1821:             }
                   1822:             localStorage.setItem(key,value);
                   1823:         }
                   1824:     }
                   1825: 
                   1826:     // restore folding status of blocks (on page load)
                   1827:     function restoreState (lastresource) {
                   1828:         if(localStorage.getItem(lastresource) != null){
                   1829:             var key = lastresource;
                   1830:             var value = localStorage.getItem(key);
                   1831:             var regex_delTimestamp = /^\d+;/;
                   1832: 
                   1833:             value.replace(regex_delTimestamp, '');
                   1834: 
                   1835:             var valueArr = value.split(';');
                   1836:             var pairs;
                   1837:             var elements;
                   1838:             for (var i = 0; i < valueArr.length; i++){
                   1839:                 pairs = valueArr[i].split(',');
                   1840:                 elements = document.getElementsByName(pairs[0]);
                   1841: 
                   1842:                 for (var j = 0; j < elements.length; j++){
                   1843:                     elements[j].style.display = pairs[1];
                   1844:                     if (pairs[1] == "none"){
                   1845:                         var regex_id = /([_\\d]+)\$/;
                   1846:                         regex_id.exec(pairs[0]);
                   1847:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1848:                     }
                   1849:                 }
                   1850:             }
                   1851:         }
                   1852:     }
                   1853: 
                   1854:     function getTagList () {
                   1855: 
                   1856:         var stringToSearch = document.lonhomework.innerHTML;
                   1857: 
                   1858:         var ret = new Array();
                   1859:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1860:         var tag_list = stringToSearch.match(regex_findBlock);
                   1861: 
                   1862:         if(tag_list != null){
                   1863:             for(var i = 0; i < tag_list.length; i++){
                   1864:                 ret.push(tag_list[i].replace(/"/, ''));
                   1865:             }
                   1866:         }
                   1867:         return ret;
                   1868:     }
                   1869: 
                   1870:     function saveScrollPosition (resource) {
                   1871:         var tag_list = getTagList();
                   1872: 
                   1873:         // we dont always want to jump to the first block
                   1874:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1875:         if(\$(window).scrollTop() > 170){
                   1876:             if(tag_list != null){
                   1877:                 var result;
                   1878:                 for(var i = 0; i < tag_list.length; i++){
                   1879:                     if(isElementInViewport(tag_list[i])){
                   1880:                         result += tag_list[i]+';';
                   1881:                     }
                   1882:                 }
                   1883:                 sessionStorage.setItem('anchor_'+resource, result);
                   1884:             }
                   1885:         } else {
                   1886:             // we dont need to save zero, just delete the item to leave everything tidy
                   1887:             sessionStorage.removeItem('anchor_'+resource);
                   1888:         }
                   1889:     }
                   1890: 
                   1891:     function restoreScrollPosition(resource){
                   1892: 
                   1893:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1894:         if(elem != null){
                   1895:             var tag_list = elem.split(';');
                   1896:             var elem_list;
                   1897: 
                   1898:             for(var i = 0; i < tag_list.length; i++){
                   1899:                 elem_list = document.getElementsByName(tag_list[i]);
                   1900: 
                   1901:                 if(elem_list.length > 0){
                   1902:                     elem = elem_list[0];
                   1903:                     break;
                   1904:                 }
                   1905:             }
                   1906:             elem.scrollIntoView();
                   1907:         }
                   1908:     }
                   1909: 
                   1910:     function isElementInViewport(el) {
                   1911: 
                   1912:         // change to last element instead of first
                   1913:         var elem = document.getElementsByName(el);
                   1914:         var rect = elem[0].getBoundingClientRect();
                   1915: 
                   1916:         return (
                   1917:             rect.top >= 0 &&
                   1918:             rect.left >= 0 &&
                   1919:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1920:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1921:         );
                   1922:     }
                   1923: 
                   1924:     function autosize(depth){
                   1925:         var cmInst = window['cm'+depth];
                   1926:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1927: 
                   1928:         // is fixed size, switching to dynamic
                   1929:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1930:             cmInst.setSize("","auto");
                   1931:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1932:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1933: 
                   1934:         // is dynamic size, switching to fixed
                   1935:         } else {
                   1936:             cmInst.setSize("","300px");
                   1937:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1938:             sessionStorage.removeItem("autosized_"+depth);
                   1939:         }
                   1940:     }
                   1941: 
                   1942: 
                   1943: 
                   1944: // ]]>
                   1945: </script>
                   1946: COLORFULEDIT
                   1947: }
                   1948: 
                   1949: sub xmleditor_js {
                   1950:     return <<XMLEDIT
                   1951: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1952: <script type="text/javascript">
                   1953: // <![CDATA[>
                   1954: 
                   1955:     function saveScrollPosition (resource) {
                   1956: 
                   1957:         var scrollPos = \$(window).scrollTop();
                   1958:         sessionStorage.setItem(resource,scrollPos);
                   1959:     }
                   1960: 
                   1961:     function restoreScrollPosition(resource){
                   1962: 
                   1963:         var scrollPos = sessionStorage.getItem(resource);
                   1964:         \$(window).scrollTop(scrollPos);
                   1965:     }
                   1966: 
                   1967:     // unless internet explorer
                   1968:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1969: 
                   1970:         \$(document).ready(function() {
                   1971:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1972:         });
                   1973:     }
                   1974: 
                   1975:     // inserts text at cursor position into codemirror (xml editor only)
                   1976:     function insertText(text){
                   1977:         cm.focus();
                   1978:         var curPos = cm.getCursor();
                   1979:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1980:     }
                   1981: // ]]>
                   1982: </script>
                   1983: XMLEDIT
                   1984: }
                   1985: 
                   1986: sub insert_folding_button {
                   1987:     my $curDepth = $Apache::lonxml::curdepth;
                   1988:     my $lastresource = $env{'request.ambiguous'};
                   1989: 
                   1990:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1991:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1992: }
                   1993: 
                   1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1075.2.56  raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.1075.2.115  raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2259: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2260: An optional arg -- $readonly -- if true will cause the select form
                   2261: to be disabled, e.g., for the case where an instructor has a section-
                   2262: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2263: 
1.88      www      2264: See lonrights.pm for an example invocation and use.
                   2265: 
                   2266: =cut
                   2267: 
                   2268: #-------------------------------------------
                   2269: sub select_form {
1.1075.2.115  raeburn  2270:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2271:     return unless (ref($hashref) eq 'HASH');
                   2272:     if ($onchange) {
                   2273:         $onchange = ' onchange="'.$onchange.'"';
                   2274:     }
1.1075.2.129  raeburn  2275:     my $disabled;
                   2276:     if ($readonly) {
                   2277:         $disabled = ' disabled="disabled"';
                   2278:     }
                   2279:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2280:     my @keys;
1.970     raeburn  2281:     if (exists($hashref->{'select_form_order'})) {
                   2282: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2283:     } else {
1.970     raeburn  2284: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2285:     }
1.356     albertel 2286:     foreach my $key (@keys) {
                   2287:         $selectform.=
                   2288: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2289:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2290:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2291:     }
                   2292:     $selectform.="</select>";
                   2293:     return $selectform;
                   2294: }
                   2295: 
1.475     www      2296: # For display filters
                   2297: 
                   2298: sub display_filter {
1.1074    raeburn  2299:     my ($context) = @_;
1.475     www      2300:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2301:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2302:     my $phraseinput = 'hidden';
                   2303:     my $includeinput = 'hidden';
                   2304:     my ($checked,$includetypestext);
                   2305:     if ($env{'form.displayfilter'} eq 'containing') {
                   2306:         $phraseinput = 'text'; 
                   2307:         if ($context eq 'parmslog') {
                   2308:             $includeinput = 'checkbox';
                   2309:             if ($env{'form.includetypes'}) {
                   2310:                 $checked = ' checked="checked"';
                   2311:             }
                   2312:             $includetypestext = &mt('Include parameter types');
                   2313:         }
                   2314:     } else {
                   2315:         $includetypestext = '&nbsp;';
                   2316:     }
                   2317:     my ($additional,$secondid,$thirdid);
                   2318:     if ($context eq 'parmslog') {
                   2319:         $additional = 
                   2320:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2321:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2322:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2323:             '</label>';
                   2324:         $secondid = 'includetypes';
                   2325:         $thirdid = 'includetypestext';
                   2326:     }
                   2327:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2328:                                                     '$secondid','$thirdid')";
                   2329:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2330: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2331: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2332: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2333:            &mt('Filter: [_1]',
1.477     www      2334: 	   &select_form($env{'form.displayfilter'},
                   2335: 			'displayfilter',
1.970     raeburn  2336: 			{'currentfolder' => 'Current folder/page',
1.477     www      2337: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2338: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2339: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2340:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2341:                          '" />'.$additional;
                   2342: }
                   2343: 
                   2344: sub display_filter_js {
                   2345:     my $includetext = &mt('Include parameter types');
                   2346:     return <<"ENDJS";
                   2347:   
                   2348: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2349:     var firstType = 'hidden';
                   2350:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2351:         firstType = 'text';
                   2352:     }
                   2353:     firstObject = document.getElementById(firstid);
                   2354:     if (typeof(firstObject) == 'object') {
                   2355:         if (firstObject.type != firstType) {
                   2356:             changeInputType(firstObject,firstType);
                   2357:         }
                   2358:     }
                   2359:     if (context == 'parmslog') {
                   2360:         var secondType = 'hidden';
                   2361:         if (firstType == 'text') {
                   2362:             secondType = 'checkbox';
                   2363:         }
                   2364:         secondObject = document.getElementById(secondid);  
                   2365:         if (typeof(secondObject) == 'object') {
                   2366:             if (secondObject.type != secondType) {
                   2367:                 changeInputType(secondObject,secondType);
                   2368:             }
                   2369:         }
                   2370:         var textItem = document.getElementById(thirdid);
                   2371:         var currtext = textItem.innerHTML;
                   2372:         var newtext;
                   2373:         if (firstType == 'text') {
                   2374:             newtext = '$includetext';
                   2375:         } else {
                   2376:             newtext = '&nbsp;';
                   2377:         }
                   2378:         if (currtext != newtext) {
                   2379:             textItem.innerHTML = newtext;
                   2380:         }
                   2381:     }
                   2382:     return;
                   2383: }
                   2384: 
                   2385: function changeInputType(oldObject,newType) {
                   2386:     var newObject = document.createElement('input');
                   2387:     newObject.type = newType;
                   2388:     if (oldObject.size) {
                   2389:         newObject.size = oldObject.size;
                   2390:     }
                   2391:     if (oldObject.value) {
                   2392:         newObject.value = oldObject.value;
                   2393:     }
                   2394:     if (oldObject.name) {
                   2395:         newObject.name = oldObject.name;
                   2396:     }
                   2397:     if (oldObject.id) {
                   2398:         newObject.id = oldObject.id;
                   2399:     }
                   2400:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2401:     return;
                   2402: }
                   2403: 
                   2404: ENDJS
1.475     www      2405: }
                   2406: 
1.167     www      2407: sub gradeleveldescription {
                   2408:     my $gradelevel=shift;
                   2409:     my %gradelevels=(0 => 'Not specified',
                   2410: 		     1 => 'Grade 1',
                   2411: 		     2 => 'Grade 2',
                   2412: 		     3 => 'Grade 3',
                   2413: 		     4 => 'Grade 4',
                   2414: 		     5 => 'Grade 5',
                   2415: 		     6 => 'Grade 6',
                   2416: 		     7 => 'Grade 7',
                   2417: 		     8 => 'Grade 8',
                   2418: 		     9 => 'Grade 9',
                   2419: 		     10 => 'Grade 10',
                   2420: 		     11 => 'Grade 11',
                   2421: 		     12 => 'Grade 12',
                   2422: 		     13 => 'Grade 13',
                   2423: 		     14 => '100 Level',
                   2424: 		     15 => '200 Level',
                   2425: 		     16 => '300 Level',
                   2426: 		     17 => '400 Level',
                   2427: 		     18 => 'Graduate Level');
                   2428:     return &mt($gradelevels{$gradelevel});
                   2429: }
                   2430: 
1.163     www      2431: sub select_level_form {
                   2432:     my ($deflevel,$name)=@_;
                   2433:     unless ($deflevel) { $deflevel=0; }
1.167     www      2434:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2435:     for (my $i=0; $i<=18; $i++) {
                   2436:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2437:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2438:                 ">".&gradeleveldescription($i)."</option>\n";
                   2439:     }
                   2440:     $selectform.="</select>";
                   2441:     return $selectform;
1.163     www      2442: }
1.167     www      2443: 
1.35      matthew  2444: #-------------------------------------------
                   2445: 
1.45      matthew  2446: =pod
                   2447: 
1.1075.2.115  raeburn  2448: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2449: 
                   2450: Returns a string containing a <select name='$name' size='1'> form to 
                   2451: allow a user to select the domain to preform an operation in.  
                   2452: See loncreateuser.pm for an example invocation and use.
                   2453: 
1.90      www      2454: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2455: selected");
                   2456: 
1.743     raeburn  2457: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2458: 
1.910     raeburn  2459: 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.
                   2460: 
1.1075.2.36  raeburn  2461: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2462: 
1.1075.2.115  raeburn  2463: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2464: 
                   2465: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2466: 
1.35      matthew  2467: =cut
                   2468: 
                   2469: #-------------------------------------------
1.34      matthew  2470: sub select_dom_form {
1.1075.2.115  raeburn  2471:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2472:     if ($onchange) {
1.874     raeburn  2473:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2474:     }
1.1075.2.115  raeburn  2475:     if ($disabled) {
                   2476:         $disabled = ' disabled="disabled"';
                   2477:     }
1.1075.2.36  raeburn  2478:     my (@domains,%exclude);
1.910     raeburn  2479:     if (ref($incdoms) eq 'ARRAY') {
                   2480:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2481:     } else {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2483:     }
1.90      www      2484:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2485:     if (ref($excdoms) eq 'ARRAY') {
                   2486:         map { $exclude{$_} = 1; } @{$excdoms};
                   2487:     }
1.1075.2.115  raeburn  2488:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2489:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2490:         next if ($exclude{$dom});
1.356     albertel 2491:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2492:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2493:         if ($showdomdesc) {
                   2494:             if ($dom ne '') {
                   2495:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2496:                 if ($domdesc ne '') {
                   2497:                     $selectdomain .= ' ('.$domdesc.')';
                   2498:                 }
                   2499:             } 
                   2500:         }
                   2501:         $selectdomain .= "</option>\n";
1.34      matthew  2502:     }
                   2503:     $selectdomain.="</select>";
                   2504:     return $selectdomain;
                   2505: }
                   2506: 
1.35      matthew  2507: #-------------------------------------------
                   2508: 
1.45      matthew  2509: =pod
                   2510: 
1.648     raeburn  2511: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2512: 
1.586     raeburn  2513: input: 4 arguments (two required, two optional) - 
                   2514:     $domain - domain of new user
                   2515:     $name - name of form element
                   2516:     $default - Value of 'default' causes a default item to be first 
                   2517:                             option, and selected by default. 
                   2518:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2519:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2520: output: returns 2 items: 
1.586     raeburn  2521: (a) form element which contains either:
                   2522:    (i) <select name="$name">
                   2523:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2524:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2525:        </select>
                   2526:        form item if there are multiple library servers in $domain, or
                   2527:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2528:        if there is only one library server in $domain.
                   2529: 
                   2530: (b) number of library servers found.
                   2531: 
                   2532: See loncreateuser.pm for example of use.
1.35      matthew  2533: 
                   2534: =cut
                   2535: 
                   2536: #-------------------------------------------
1.586     raeburn  2537: sub home_server_form_item {
                   2538:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2539:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2540:     my $result;
                   2541:     my $numlib = keys(%servers);
                   2542:     if ($numlib > 1) {
                   2543:         $result .= '<select name="'.$name.'" />'."\n";
                   2544:         if ($default) {
1.804     bisitz   2545:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2546:                        '</option>'."\n";
                   2547:         }
                   2548:         foreach my $hostid (sort(keys(%servers))) {
                   2549:             $result.= '<option value="'.$hostid.'">'.
                   2550: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2551:         }
                   2552:         $result .= '</select>'."\n";
                   2553:     } elsif ($numlib == 1) {
                   2554:         my $hostid;
                   2555:         foreach my $item (keys(%servers)) {
                   2556:             $hostid = $item;
                   2557:         }
                   2558:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2559:                    $hostid.'" />';
                   2560:                    if (!$hide) {
                   2561:                        $result .= $hostid.' '.$servers{$hostid};
                   2562:                    }
                   2563:                    $result .= "\n";
                   2564:     } elsif ($default) {
                   2565:         $result .= '<input type="hidden" name="'.$name.
                   2566:                    '" value="default" />';
                   2567:                    if (!$hide) {
                   2568:                        $result .= &mt('default');
                   2569:                    }
                   2570:                    $result .= "\n";
1.33      matthew  2571:     }
1.586     raeburn  2572:     return ($result,$numlib);
1.33      matthew  2573: }
1.112     bowersj2 2574: 
                   2575: =pod
                   2576: 
1.534     albertel 2577: =back 
                   2578: 
1.112     bowersj2 2579: =cut
1.87      matthew  2580: 
                   2581: ###############################################################
1.112     bowersj2 2582: ##                  Decoding User Agent                      ##
1.87      matthew  2583: ###############################################################
                   2584: 
                   2585: =pod
                   2586: 
1.112     bowersj2 2587: =head1 Decoding the User Agent
                   2588: 
                   2589: =over 4
                   2590: 
                   2591: =item * &decode_user_agent()
1.87      matthew  2592: 
                   2593: Inputs: $r
                   2594: 
                   2595: Outputs:
                   2596: 
                   2597: =over 4
                   2598: 
1.112     bowersj2 2599: =item * $httpbrowser
1.87      matthew  2600: 
1.112     bowersj2 2601: =item * $clientbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientversion
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientmathml
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientunicode
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientos
1.87      matthew  2610: 
1.1075.2.42  raeburn  2611: =item * $clientmobile
                   2612: 
                   2613: =item * $clientinfo
                   2614: 
1.1075.2.77  raeburn  2615: =item * $clientosversion
                   2616: 
1.87      matthew  2617: =back
                   2618: 
1.157     matthew  2619: =back 
                   2620: 
1.87      matthew  2621: =cut
                   2622: 
                   2623: ###############################################################
                   2624: ###############################################################
                   2625: sub decode_user_agent {
1.247     albertel 2626:     my ($r)=@_;
1.87      matthew  2627:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2628:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2629:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2630:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2631:     my $clientbrowser='unknown';
                   2632:     my $clientversion='0';
                   2633:     my $clientmathml='';
                   2634:     my $clientunicode='0';
1.1075.2.42  raeburn  2635:     my $clientmobile=0;
1.1075.2.77  raeburn  2636:     my $clientosversion='';
1.87      matthew  2637:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2638:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2639: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2640: 	    $clientbrowser=$bname;
                   2641:             $httpbrowser=~/$vreg/i;
                   2642: 	    $clientversion=$1;
                   2643:             $clientmathml=($clientversion>=$minv);
                   2644:             $clientunicode=($clientversion>=$univ);
                   2645: 	}
                   2646:     }
                   2647:     my $clientos='unknown';
1.1075.2.42  raeburn  2648:     my $clientinfo;
1.87      matthew  2649:     if (($httpbrowser=~/linux/i) ||
                   2650:         ($httpbrowser=~/unix/i) ||
                   2651:         ($httpbrowser=~/ux/i) ||
                   2652:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2653:     if (($httpbrowser=~/vax/i) ||
                   2654:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2655:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2656:     if (($httpbrowser=~/mac/i) ||
                   2657:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2658:     if ($httpbrowser=~/win/i) {
                   2659:         $clientos='win';
                   2660:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2661:             $clientosversion = $1;
                   2662:         }
                   2663:     }
1.87      matthew  2664:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2665:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2666:         $clientmobile=lc($1);
                   2667:     }
                   2668:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2669:         $clientinfo = 'firefox-'.$1;
                   2670:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2671:         $clientinfo = 'chromeframe-'.$1;
                   2672:     }
1.87      matthew  2673:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2674:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2675:             $clientosversion);
1.87      matthew  2676: }
                   2677: 
1.32      matthew  2678: ###############################################################
                   2679: ##    Authentication changing form generation subroutines    ##
                   2680: ###############################################################
                   2681: ##
                   2682: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2683: ## hash, and have reasonable default values.
                   2684: ##
                   2685: ##    formname = the name given in the <form> tag.
1.35      matthew  2686: #-------------------------------------------
                   2687: 
1.45      matthew  2688: =pod
                   2689: 
1.112     bowersj2 2690: =head1 Authentication Routines
                   2691: 
                   2692: =over 4
                   2693: 
1.648     raeburn  2694: =item * &authform_xxxxxx()
1.35      matthew  2695: 
                   2696: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2697: handle some of the conveniences required for authentication forms.  
                   2698: This is not an optimal method, but it works.  
                   2699: 
                   2700: =over 4
                   2701: 
1.112     bowersj2 2702: =item * authform_header
1.35      matthew  2703: 
1.112     bowersj2 2704: =item * authform_authorwarning
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_nochange
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_kerberos
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_internal
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_filesystem
1.35      matthew  2713: 
                   2714: =back
                   2715: 
1.648     raeburn  2716: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2717: 
1.35      matthew  2718: =cut
                   2719: 
                   2720: #-------------------------------------------
1.32      matthew  2721: sub authform_header{  
                   2722:     my %in = (
                   2723:         formname => 'cu',
1.80      albertel 2724:         kerb_def_dom => '',
1.32      matthew  2725:         @_,
                   2726:     );
                   2727:     $in{'formname'} = 'document.' . $in{'formname'};
                   2728:     my $result='';
1.80      albertel 2729: 
                   2730: #---------------------------------------------- Code for upper case translation
                   2731:     my $Javascript_toUpperCase;
                   2732:     unless ($in{kerb_def_dom}) {
                   2733:         $Javascript_toUpperCase =<<"END";
                   2734:         switch (choice) {
                   2735:            case 'krb': currentform.elements[choicearg].value =
                   2736:                currentform.elements[choicearg].value.toUpperCase();
                   2737:                break;
                   2738:            default:
                   2739:         }
                   2740: END
                   2741:     } else {
                   2742:         $Javascript_toUpperCase = "";
                   2743:     }
                   2744: 
1.165     raeburn  2745:     my $radioval = "'nochange'";
1.591     raeburn  2746:     if (defined($in{'curr_authtype'})) {
                   2747:         if ($in{'curr_authtype'} ne '') {
                   2748:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2749:         }
1.174     matthew  2750:     }
1.165     raeburn  2751:     my $argfield = 'null';
1.591     raeburn  2752:     if (defined($in{'mode'})) {
1.165     raeburn  2753:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2754:             if (defined($in{'curr_autharg'})) {
                   2755:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2756:                     $argfield = "'$in{'curr_autharg'}'";
                   2757:                 }
                   2758:             }
                   2759:         }
                   2760:     }
                   2761: 
1.32      matthew  2762:     $result.=<<"END";
                   2763: var current = new Object();
1.165     raeburn  2764: current.radiovalue = $radioval;
                   2765: current.argfield = $argfield;
1.32      matthew  2766: 
                   2767: function changed_radio(choice,currentform) {
                   2768:     var choicearg = choice + 'arg';
                   2769:     // If a radio button in changed, we need to change the argfield
                   2770:     if (current.radiovalue != choice) {
                   2771:         current.radiovalue = choice;
                   2772:         if (current.argfield != null) {
                   2773:             currentform.elements[current.argfield].value = '';
                   2774:         }
                   2775:         if (choice == 'nochange') {
                   2776:             current.argfield = null;
                   2777:         } else {
                   2778:             current.argfield = choicearg;
                   2779:             switch(choice) {
                   2780:                 case 'krb': 
                   2781:                     currentform.elements[current.argfield].value = 
                   2782:                         "$in{'kerb_def_dom'}";
                   2783:                 break;
                   2784:               default:
                   2785:                 break;
                   2786:             }
                   2787:         }
                   2788:     }
                   2789:     return;
                   2790: }
1.22      www      2791: 
1.32      matthew  2792: function changed_text(choice,currentform) {
                   2793:     var choicearg = choice + 'arg';
                   2794:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2795:         $Javascript_toUpperCase
1.32      matthew  2796:         // clear old field
                   2797:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2798:             currentform.elements[current.argfield].value = '';
                   2799:         }
                   2800:         current.argfield = choicearg;
                   2801:     }
                   2802:     set_auth_radio_buttons(choice,currentform);
                   2803:     return;
1.20      www      2804: }
1.32      matthew  2805: 
                   2806: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2807:     var numauthchoices = currentform.login.length;
                   2808:     if (typeof numauthchoices  == "undefined") {
                   2809:         return;
                   2810:     } 
1.32      matthew  2811:     var i=0;
1.986     raeburn  2812:     while (i < numauthchoices) {
1.32      matthew  2813:         if (currentform.login[i].value == newvalue) { break; }
                   2814:         i++;
                   2815:     }
1.986     raeburn  2816:     if (i == numauthchoices) {
1.32      matthew  2817:         return;
                   2818:     }
                   2819:     current.radiovalue = newvalue;
                   2820:     currentform.login[i].checked = true;
                   2821:     return;
                   2822: }
                   2823: END
                   2824:     return $result;
                   2825: }
                   2826: 
1.1075.2.20  raeburn  2827: sub authform_authorwarning {
1.32      matthew  2828:     my $result='';
1.144     matthew  2829:     $result='<i>'.
                   2830:         &mt('As a general rule, only authors or co-authors should be '.
                   2831:             'filesystem authenticated '.
                   2832:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2833:     return $result;
                   2834: }
                   2835: 
1.1075.2.20  raeburn  2836: sub authform_nochange {
1.32      matthew  2837:     my %in = (
                   2838:               formname => 'document.cu',
                   2839:               kerb_def_dom => 'MSU.EDU',
                   2840:               @_,
                   2841:           );
1.1075.2.20  raeburn  2842:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2843:     my $result;
1.1075.2.20  raeburn  2844:     if (!$authnum) {
                   2845:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2846:     } else {
                   2847:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2848:                   '<input type="radio" name="login" value="nochange" '.
                   2849:                   'checked="checked" onclick="'.
1.281     albertel 2850:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2851: 	    '</label>';
1.586     raeburn  2852:     }
1.32      matthew  2853:     return $result;
                   2854: }
                   2855: 
1.591     raeburn  2856: sub authform_kerberos {
1.32      matthew  2857:     my %in = (
                   2858:               formname => 'document.cu',
                   2859:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2860:               kerb_def_auth => 'krb4',
1.32      matthew  2861:               @_,
                   2862:               );
1.586     raeburn  2863:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2864:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2865:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2866:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2867:        $check5 = ' checked="checked"';
1.80      albertel 2868:     } else {
1.772     bisitz   2869:        $check4 = ' checked="checked"';
1.80      albertel 2870:     }
1.1075.2.117  raeburn  2871:     if ($in{'readonly'}) {
                   2872:         $disabled = ' disabled="disabled"';
                   2873:     }
1.165     raeburn  2874:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2875:     if (defined($in{'curr_authtype'})) {
                   2876:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2877:             $krbcheck = ' checked="checked"';
1.623     raeburn  2878:             if (defined($in{'mode'})) {
                   2879:                 if ($in{'mode'} eq 'modifyuser') {
                   2880:                     $krbcheck = '';
                   2881:                 }
                   2882:             }
1.591     raeburn  2883:             if (defined($in{'curr_kerb_ver'})) {
                   2884:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2885:                     $check5 = ' checked="checked"';
1.591     raeburn  2886:                     $check4 = '';
                   2887:                 } else {
1.772     bisitz   2888:                     $check4 = ' checked="checked"';
1.591     raeburn  2889:                     $check5 = '';
                   2890:                 }
1.586     raeburn  2891:             }
1.591     raeburn  2892:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2893:                 $krbarg = $in{'curr_autharg'};
                   2894:             }
1.586     raeburn  2895:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2896:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2897:                     $result = 
                   2898:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2899:         $in{'curr_autharg'},$krbver);
                   2900:                 } else {
                   2901:                     $result =
                   2902:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2903:                 }
                   2904:                 return $result; 
                   2905:             }
                   2906:         }
                   2907:     } else {
                   2908:         if ($authnum == 1) {
1.784     bisitz   2909:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2910:         }
                   2911:     }
1.586     raeburn  2912:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2913:         return;
1.587     raeburn  2914:     } elsif ($authtype eq '') {
1.591     raeburn  2915:         if (defined($in{'mode'})) {
1.587     raeburn  2916:             if ($in{'mode'} eq 'modifycourse') {
                   2917:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2918:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2919:                 }
                   2920:             }
                   2921:         }
1.586     raeburn  2922:     }
                   2923:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2924:     if ($authtype eq '') {
                   2925:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2926:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2927:                     $krbcheck.$disabled.' />';
1.586     raeburn  2928:     }
                   2929:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2930:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2931:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2932:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb4')) {
                   2934:         $result .= &mt
1.144     matthew  2935:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2936:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2937:          '<label>'.$authtype,
1.281     albertel 2938:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2939:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2940:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2941:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2942:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2943: 	 '</label>');
1.586     raeburn  2944:     } elsif ($can_assign{'krb4'}) {
                   2945:         $result .= &mt
                   2946:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2947:          '[_3] Version 4 [_4]',
                   2948:          '<label>'.$authtype,
                   2949:          '</label><input type="text" size="10" name="krbarg" '.
                   2950:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2951:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2952:          '<label><input type="hidden" name="krbver" value="4" />',
                   2953:          '</label>');
                   2954:     } elsif ($can_assign{'krb5'}) {
                   2955:         $result .= &mt
                   2956:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2957:          '[_3] Version 5 [_4]',
                   2958:          '<label>'.$authtype,
                   2959:          '</label><input type="text" size="10" name="krbarg" '.
                   2960:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2961:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2962:          '<label><input type="hidden" name="krbver" value="5" />',
                   2963:          '</label>');
                   2964:     }
1.32      matthew  2965:     return $result;
                   2966: }
                   2967: 
1.1075.2.20  raeburn  2968: sub authform_internal {
1.586     raeburn  2969:     my %in = (
1.32      matthew  2970:                 formname => 'document.cu',
                   2971:                 kerb_def_dom => 'MSU.EDU',
                   2972:                 @_,
                   2973:                 );
1.1075.2.117  raeburn  2974:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2975:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2976:     if ($in{'readonly'}) {
                   2977:         $disabled = ' disabled="disabled"';
                   2978:     }
1.591     raeburn  2979:     if (defined($in{'curr_authtype'})) {
                   2980:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2981:             if ($can_assign{'int'}) {
1.772     bisitz   2982:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2983:                 if (defined($in{'mode'})) {
                   2984:                     if ($in{'mode'} eq 'modifyuser') {
                   2985:                         $intcheck = '';
                   2986:                     }
                   2987:                 }
1.591     raeburn  2988:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2989:                     $intarg = $in{'curr_autharg'};
                   2990:                 }
                   2991:             } else {
                   2992:                 $result = &mt('Currently internally authenticated.');
                   2993:                 return $result;
1.165     raeburn  2994:             }
                   2995:         }
1.586     raeburn  2996:     } else {
                   2997:         if ($authnum == 1) {
1.784     bisitz   2998:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2999:         }
                   3000:     }
                   3001:     if (!$can_assign{'int'}) {
                   3002:         return;
1.587     raeburn  3003:     } elsif ($authtype eq '') {
1.591     raeburn  3004:         if (defined($in{'mode'})) {
1.587     raeburn  3005:             if ($in{'mode'} eq 'modifycourse') {
                   3006:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3007:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3008:                 }
                   3009:             }
                   3010:         }
1.165     raeburn  3011:     }
1.586     raeburn  3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3013:     if ($authtype eq '') {
                   3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3016:     }
1.605     bisitz   3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3018:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3019:     $result = &mt
1.144     matthew  3020:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3021:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3022:     $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  3023:     return $result;
                   3024: }
                   3025: 
1.1075.2.20  raeburn  3026: sub authform_local {
1.32      matthew  3027:     my %in = (
                   3028:               formname => 'document.cu',
                   3029:               kerb_def_dom => 'MSU.EDU',
                   3030:               @_,
                   3031:               );
1.1075.2.117  raeburn  3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3034:     if ($in{'readonly'}) {
                   3035:         $disabled = ' disabled="disabled"';
                   3036:     }
1.591     raeburn  3037:     if (defined($in{'curr_authtype'})) {
                   3038:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3039:             if ($can_assign{'loc'}) {
1.772     bisitz   3040:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3041:                 if (defined($in{'mode'})) {
                   3042:                     if ($in{'mode'} eq 'modifyuser') {
                   3043:                         $loccheck = '';
                   3044:                     }
                   3045:                 }
1.591     raeburn  3046:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3047:                     $locarg = $in{'curr_autharg'};
                   3048:                 }
                   3049:             } else {
                   3050:                 $result = &mt('Currently using local (institutional) authentication.');
                   3051:                 return $result;
1.165     raeburn  3052:             }
                   3053:         }
1.586     raeburn  3054:     } else {
                   3055:         if ($authnum == 1) {
1.784     bisitz   3056:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3057:         }
                   3058:     }
                   3059:     if (!$can_assign{'loc'}) {
                   3060:         return;
1.587     raeburn  3061:     } elsif ($authtype eq '') {
1.591     raeburn  3062:         if (defined($in{'mode'})) {
1.587     raeburn  3063:             if ($in{'mode'} eq 'modifycourse') {
                   3064:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3065:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3066:                 }
                   3067:             }
                   3068:         }
1.165     raeburn  3069:     }
1.586     raeburn  3070:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3071:     if ($authtype eq '') {
                   3072:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3073:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3074:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3075:     }
                   3076:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3077:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3078:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3079:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3080:     return $result;
                   3081: }
                   3082: 
1.1075.2.20  raeburn  3083: sub authform_filesystem {
1.32      matthew  3084:     my %in = (
                   3085:               formname => 'document.cu',
                   3086:               kerb_def_dom => 'MSU.EDU',
                   3087:               @_,
                   3088:               );
1.1075.2.117  raeburn  3089:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3090:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3091:     if ($in{'readonly'}) {
                   3092:         $disabled = ' disabled="disabled"';
                   3093:     }
1.591     raeburn  3094:     if (defined($in{'curr_authtype'})) {
                   3095:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3096:             if ($can_assign{'fsys'}) {
1.772     bisitz   3097:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3098:                 if (defined($in{'mode'})) {
                   3099:                     if ($in{'mode'} eq 'modifyuser') {
                   3100:                         $fsyscheck = '';
                   3101:                     }
                   3102:                 }
1.586     raeburn  3103:             } else {
                   3104:                 $result = &mt('Currently Filesystem Authenticated.');
                   3105:                 return $result;
                   3106:             }           
                   3107:         }
                   3108:     } else {
                   3109:         if ($authnum == 1) {
1.784     bisitz   3110:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3111:         }
                   3112:     }
                   3113:     if (!$can_assign{'fsys'}) {
                   3114:         return;
1.587     raeburn  3115:     } elsif ($authtype eq '') {
1.591     raeburn  3116:         if (defined($in{'mode'})) {
1.587     raeburn  3117:             if ($in{'mode'} eq 'modifycourse') {
                   3118:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3119:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3120:                 }
                   3121:             }
                   3122:         }
1.586     raeburn  3123:     }
                   3124:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3125:     if ($authtype eq '') {
                   3126:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3127:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3128:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3129:     }
                   3130:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3131:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3132:     $result = &mt
1.144     matthew  3133:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3134:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3135:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3136:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3137:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3138:     return $result;
                   3139: }
                   3140: 
1.586     raeburn  3141: sub get_assignable_auth {
                   3142:     my ($dom) = @_;
                   3143:     if ($dom eq '') {
                   3144:         $dom = $env{'request.role.domain'};
                   3145:     }
                   3146:     my %can_assign = (
                   3147:                           krb4 => 1,
                   3148:                           krb5 => 1,
                   3149:                           int  => 1,
                   3150:                           loc  => 1,
                   3151:                      );
                   3152:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3153:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3154:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3155:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3156:             my $context;
                   3157:             if ($env{'request.role'} =~ /^au/) {
                   3158:                 $context = 'author';
1.1075.2.117  raeburn  3159:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3160:                 $context = 'domain';
                   3161:             } elsif ($env{'request.course.id'}) {
                   3162:                 $context = 'course';
                   3163:             }
                   3164:             if ($context) {
                   3165:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3166:                    %can_assign = %{$authhash->{$context}}; 
                   3167:                 }
                   3168:             }
                   3169:         }
                   3170:     }
                   3171:     my $authnum = 0;
                   3172:     foreach my $key (keys(%can_assign)) {
                   3173:         if ($can_assign{$key}) {
                   3174:             $authnum ++;
                   3175:         }
                   3176:     }
                   3177:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3178:         $authnum --;
                   3179:     }
                   3180:     return ($authnum,%can_assign);
                   3181: }
                   3182: 
1.1075.2.137  raeburn  3183: sub check_passwd_rules {
                   3184:     my ($domain,$plainpass) = @_;
                   3185:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3186:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3187:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3188:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3189:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3190:             if ($passwdconf{'min'} > $min) {
                   3191:                 $min = $passwdconf{'min'};
                   3192:             }
1.1075.2.137  raeburn  3193:         }
                   3194:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3195:             $max = $passwdconf{'max'};
                   3196:         }
                   3197:         @chars = @{$passwdconf{'chars'}};
                   3198:     }
                   3199:     if (($min) && (length($plainpass) < $min)) {
                   3200:         push(@brokerule,'min');
                   3201:     }
                   3202:     if (($max) && (length($plainpass) > $max)) {
                   3203:         push(@brokerule,'max');
                   3204:     }
                   3205:     if (@chars) {
                   3206:         my %rules;
                   3207:         map { $rules{$_} = 1; } @chars;
                   3208:         if ($rules{'uc'}) {
                   3209:             unless ($plainpass =~ /[A-Z]/) {
                   3210:                 push(@brokerule,'uc');
                   3211:             }
                   3212:         }
                   3213:         if ($rules{'lc'}) {
                   3214:             unless ($plainpass =~ /[a-z]/) {
                   3215:                 push(@brokerule,'lc');
                   3216:             }
                   3217:         }
                   3218:         if ($rules{'num'}) {
                   3219:             unless ($plainpass =~ /\d/) {
                   3220:                 push(@brokerule,'num');
                   3221:             }
                   3222:         }
                   3223:         if ($rules{'spec'}) {
                   3224:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3225:                 push(@brokerule,'spec');
                   3226:             }
                   3227:         }
                   3228:     }
                   3229:     if (@brokerule) {
                   3230:         my %rulenames = &Apache::lonlocal::texthash(
                   3231:             uc   => 'At least one upper case letter',
                   3232:             lc   => 'At least one lower case letter',
                   3233:             num  => 'At least one number',
                   3234:             spec => 'At least one non-alphanumeric',
                   3235:         );
                   3236:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3237:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3238:         $rulenames{'num'} .= ': 0123456789';
                   3239:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3240:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3241:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3242:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3243:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3244:             if (grep(/^$rule$/,@brokerule)) {
                   3245:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3246:             }
                   3247:         }
                   3248:         $warning .= '</ul>';
                   3249:     }
                   3250:     if (wantarray) {
                   3251:         return @brokerule;
                   3252:     }
                   3253:     return $warning;
                   3254: }
                   3255: 
1.80      albertel 3256: ###############################################################
                   3257: ##    Get Kerberos Defaults for Domain                 ##
                   3258: ###############################################################
                   3259: ##
                   3260: ## Returns default kerberos version and an associated argument
                   3261: ## as listed in file domain.tab. If not listed, provides
                   3262: ## appropriate default domain and kerberos version.
                   3263: ##
                   3264: #-------------------------------------------
                   3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &get_kerberos_defaults()
1.80      albertel 3269: 
                   3270: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3271: version and domain. If not found, it defaults to version 4 and the 
                   3272: domain of the server.
1.80      albertel 3273: 
1.648     raeburn  3274: =over 4
                   3275: 
1.80      albertel 3276: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3277: 
1.648     raeburn  3278: =back
                   3279: 
                   3280: =back
                   3281: 
1.80      albertel 3282: =cut
                   3283: 
                   3284: #-------------------------------------------
                   3285: sub get_kerberos_defaults {
                   3286:     my $domain=shift;
1.641     raeburn  3287:     my ($krbdef,$krbdefdom);
                   3288:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3289:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3290:         $krbdef = $domdefaults{'auth_def'};
                   3291:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3292:     } else {
1.80      albertel 3293:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3294:         my $krbdefdom=$1;
                   3295:         $krbdefdom=~tr/a-z/A-Z/;
                   3296:         $krbdef = "krb4";
                   3297:     }
                   3298:     return ($krbdef,$krbdefdom);
                   3299: }
1.112     bowersj2 3300: 
1.32      matthew  3301: 
1.46      matthew  3302: ###############################################################
                   3303: ##                Thesaurus Functions                        ##
                   3304: ###############################################################
1.20      www      3305: 
1.46      matthew  3306: =pod
1.20      www      3307: 
1.112     bowersj2 3308: =head1 Thesaurus Functions
                   3309: 
                   3310: =over 4
                   3311: 
1.648     raeburn  3312: =item * &initialize_keywords()
1.46      matthew  3313: 
                   3314: Initializes the package variable %Keywords if it is empty.  Uses the
                   3315: package variable $thesaurus_db_file.
                   3316: 
                   3317: =cut
                   3318: 
                   3319: ###################################################
                   3320: 
                   3321: sub initialize_keywords {
                   3322:     return 1 if (scalar keys(%Keywords));
                   3323:     # If we are here, %Keywords is empty, so fill it up
                   3324:     #   Make sure the file we need exists...
                   3325:     if (! -e $thesaurus_db_file) {
                   3326:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3327:                                  " failed because it does not exist");
                   3328:         return 0;
                   3329:     }
                   3330:     #   Set up the hash as a database
                   3331:     my %thesaurus_db;
                   3332:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3333:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3334:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3335:                                  $thesaurus_db_file);
                   3336:         return 0;
                   3337:     } 
                   3338:     #  Get the average number of appearances of a word.
                   3339:     my $avecount = $thesaurus_db{'average.count'};
                   3340:     #  Put keywords (those that appear > average) into %Keywords
                   3341:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3342:         my ($count,undef) = split /:/,$data;
                   3343:         $Keywords{$word}++ if ($count > $avecount);
                   3344:     }
                   3345:     untie %thesaurus_db;
                   3346:     # Remove special values from %Keywords.
1.356     albertel 3347:     foreach my $value ('total.count','average.count') {
                   3348:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3349:   }
1.46      matthew  3350:     return 1;
                   3351: }
                   3352: 
                   3353: ###################################################
                   3354: 
                   3355: =pod
                   3356: 
1.648     raeburn  3357: =item * &keyword($word)
1.46      matthew  3358: 
                   3359: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3360: than the average number of times in the thesaurus database.  Calls 
                   3361: &initialize_keywords
                   3362: 
                   3363: =cut
                   3364: 
                   3365: ###################################################
1.20      www      3366: 
                   3367: sub keyword {
1.46      matthew  3368:     return if (!&initialize_keywords());
                   3369:     my $word=lc(shift());
                   3370:     $word=~s/\W//g;
                   3371:     return exists($Keywords{$word});
1.20      www      3372: }
1.46      matthew  3373: 
                   3374: ###############################################################
                   3375: 
                   3376: =pod 
1.20      www      3377: 
1.648     raeburn  3378: =item * &get_related_words()
1.46      matthew  3379: 
1.160     matthew  3380: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3381: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3382: will be returned.  The order of the words returned is determined by the
                   3383: database which holds them.
                   3384: 
                   3385: Uses global $thesaurus_db_file.
                   3386: 
1.1057    foxr     3387: 
1.46      matthew  3388: =cut
                   3389: 
                   3390: ###############################################################
                   3391: sub get_related_words {
                   3392:     my $keyword = shift;
                   3393:     my %thesaurus_db;
                   3394:     if (! -e $thesaurus_db_file) {
                   3395:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3396:                                  "failed because the file does not exist");
                   3397:         return ();
                   3398:     }
                   3399:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3400:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3401:         return ();
                   3402:     } 
                   3403:     my @Words=();
1.429     www      3404:     my $count=0;
1.46      matthew  3405:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3406: 	# The first element is the number of times
                   3407: 	# the word appears.  We do not need it now.
1.429     www      3408: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3409: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3410: 	my $threshold=$mostfrequentcount/10;
                   3411:         foreach my $possibleword (@RelatedWords) {
                   3412:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3413:             if ($wordcount>$threshold) {
                   3414: 		push(@Words,$word);
                   3415:                 $count++;
                   3416:                 if ($count>10) { last; }
                   3417: 	    }
1.20      www      3418:         }
                   3419:     }
1.46      matthew  3420:     untie %thesaurus_db;
                   3421:     return @Words;
1.14      harris41 3422: }
1.46      matthew  3423: 
1.112     bowersj2 3424: =pod
                   3425: 
                   3426: =back
                   3427: 
                   3428: =cut
1.61      www      3429: 
                   3430: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3431: =pod
                   3432: 
1.112     bowersj2 3433: =head1 User Name Functions
                   3434: 
                   3435: =over 4
                   3436: 
1.648     raeburn  3437: =item * &plainname($uname,$udom,$first)
1.81      albertel 3438: 
1.112     bowersj2 3439: Takes a users logon name and returns it as a string in
1.226     albertel 3440: "first middle last generation" form 
                   3441: if $first is set to 'lastname' then it returns it as
                   3442: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3443: 
                   3444: =cut
1.61      www      3445: 
1.295     www      3446: 
1.81      albertel 3447: ###############################################################
1.61      www      3448: sub plainname {
1.226     albertel 3449:     my ($uname,$udom,$first)=@_;
1.537     albertel 3450:     return if (!defined($uname) || !defined($udom));
1.295     www      3451:     my %names=&getnames($uname,$udom);
1.226     albertel 3452:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3453: 					  $names{'middlename'},
                   3454: 					  $names{'lastname'},
                   3455: 					  $names{'generation'},$first);
                   3456:     $name=~s/^\s+//;
1.62      www      3457:     $name=~s/\s+$//;
                   3458:     $name=~s/\s+/ /g;
1.353     albertel 3459:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3460:     return $name;
1.61      www      3461: }
1.66      www      3462: 
                   3463: # -------------------------------------------------------------------- Nickname
1.81      albertel 3464: =pod
                   3465: 
1.648     raeburn  3466: =item * &nickname($uname,$udom)
1.81      albertel 3467: 
                   3468: Gets a users name and returns it as a string as
                   3469: 
                   3470: "&quot;nickname&quot;"
1.66      www      3471: 
1.81      albertel 3472: if the user has a nickname or
                   3473: 
                   3474: "first middle last generation"
                   3475: 
                   3476: if the user does not
                   3477: 
                   3478: =cut
1.66      www      3479: 
                   3480: sub nickname {
                   3481:     my ($uname,$udom)=@_;
1.537     albertel 3482:     return if (!defined($uname) || !defined($udom));
1.295     www      3483:     my %names=&getnames($uname,$udom);
1.68      albertel 3484:     my $name=$names{'nickname'};
1.66      www      3485:     if ($name) {
                   3486:        $name='&quot;'.$name.'&quot;'; 
                   3487:     } else {
                   3488:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3489: 	     $names{'lastname'}.' '.$names{'generation'};
                   3490:        $name=~s/\s+$//;
                   3491:        $name=~s/\s+/ /g;
                   3492:     }
                   3493:     return $name;
                   3494: }
                   3495: 
1.295     www      3496: sub getnames {
                   3497:     my ($uname,$udom)=@_;
1.537     albertel 3498:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3499:     if ($udom eq 'public' && $uname eq 'public') {
                   3500: 	return ('lastname' => &mt('Public'));
                   3501:     }
1.295     www      3502:     my $id=$uname.':'.$udom;
                   3503:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3504:     if ($cached) {
                   3505: 	return %{$names};
                   3506:     } else {
                   3507: 	my %loadnames=&Apache::lonnet::get('environment',
                   3508:                     ['firstname','middlename','lastname','generation','nickname'],
                   3509: 					 $udom,$uname);
                   3510: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3511: 	return %loadnames;
                   3512:     }
                   3513: }
1.61      www      3514: 
1.542     raeburn  3515: # -------------------------------------------------------------------- getemails
1.648     raeburn  3516: 
1.542     raeburn  3517: =pod
                   3518: 
1.648     raeburn  3519: =item * &getemails($uname,$udom)
1.542     raeburn  3520: 
                   3521: Gets a user's email information and returns it as a hash with keys:
                   3522: notification, critnotification, permanentemail
                   3523: 
                   3524: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3525: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3526:  
1.648     raeburn  3527: 
1.542     raeburn  3528: =cut
                   3529: 
1.648     raeburn  3530: 
1.466     albertel 3531: sub getemails {
                   3532:     my ($uname,$udom)=@_;
                   3533:     if ($udom eq 'public' && $uname eq 'public') {
                   3534: 	return;
                   3535:     }
1.467     www      3536:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3537:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3538:     my $id=$uname.':'.$udom;
                   3539:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3540:     if ($cached) {
                   3541: 	return %{$names};
                   3542:     } else {
                   3543: 	my %loadnames=&Apache::lonnet::get('environment',
                   3544:                     			   ['notification','critnotification',
                   3545: 					    'permanentemail'],
                   3546: 					   $udom,$uname);
                   3547: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3548: 	return %loadnames;
                   3549:     }
                   3550: }
                   3551: 
1.551     albertel 3552: sub flush_email_cache {
                   3553:     my ($uname,$udom)=@_;
                   3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3555:     if (!$uname) { $uname=$env{'user.name'};   }
                   3556:     return if ($udom eq 'public' && $uname eq 'public');
                   3557:     my $id=$uname.':'.$udom;
                   3558:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3559: }
                   3560: 
1.728     raeburn  3561: # -------------------------------------------------------------------- getlangs
                   3562: 
                   3563: =pod
                   3564: 
                   3565: =item * &getlangs($uname,$udom)
                   3566: 
                   3567: Gets a user's language preference and returns it as a hash with key:
                   3568: language.
                   3569: 
                   3570: =cut
                   3571: 
                   3572: 
                   3573: sub getlangs {
                   3574:     my ($uname,$udom) = @_;
                   3575:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3576:     if (!$uname) { $uname=$env{'user.name'};   }
                   3577:     my $id=$uname.':'.$udom;
                   3578:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3579:     if ($cached) {
                   3580:         return %{$langs};
                   3581:     } else {
                   3582:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3583:                                            $udom,$uname);
                   3584:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3585:         return %loadlangs;
                   3586:     }
                   3587: }
                   3588: 
                   3589: sub flush_langs_cache {
                   3590:     my ($uname,$udom)=@_;
                   3591:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3592:     if (!$uname) { $uname=$env{'user.name'};   }
                   3593:     return if ($udom eq 'public' && $uname eq 'public');
                   3594:     my $id=$uname.':'.$udom;
                   3595:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3596: }
                   3597: 
1.61      www      3598: # ------------------------------------------------------------------ Screenname
1.81      albertel 3599: 
                   3600: =pod
                   3601: 
1.648     raeburn  3602: =item * &screenname($uname,$udom)
1.81      albertel 3603: 
                   3604: Gets a users screenname and returns it as a string
                   3605: 
                   3606: =cut
1.61      www      3607: 
                   3608: sub screenname {
                   3609:     my ($uname,$udom)=@_;
1.258     albertel 3610:     if ($uname eq $env{'user.name'} &&
                   3611: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3612:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3613:     return $names{'screenname'};
1.62      www      3614: }
                   3615: 
1.212     albertel 3616: 
1.802     bisitz   3617: # ------------------------------------------------------------- Confirm Wrapper
                   3618: =pod
                   3619: 
1.1075.2.42  raeburn  3620: =item * &confirmwrapper($message)
1.802     bisitz   3621: 
                   3622: Wrap messages about completion of operation in box
                   3623: 
                   3624: =cut
                   3625: 
                   3626: sub confirmwrapper {
                   3627:     my ($message)=@_;
                   3628:     if ($message) {
                   3629:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3630:                .$message."\n"
                   3631:                .'</div>'."\n";
                   3632:     } else {
                   3633:         return $message;
                   3634:     }
                   3635: }
                   3636: 
1.62      www      3637: # ------------------------------------------------------------- Message Wrapper
                   3638: 
                   3639: sub messagewrapper {
1.369     www      3640:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3641:     return 
1.441     albertel 3642:         '<a href="/adm/email?compose=individual&amp;'.
                   3643:         'recname='.$username.'&amp;recdom='.$domain.
                   3644: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3645:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3646: }
1.802     bisitz   3647: 
1.74      www      3648: # --------------------------------------------------------------- Notes Wrapper
                   3649: 
                   3650: sub noteswrapper {
                   3651:     my ($link,$un,$do)=@_;
                   3652:     return 
1.896     amueller 3653: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3654: }
1.802     bisitz   3655: 
1.62      www      3656: # ------------------------------------------------------------- Aboutme Wrapper
                   3657: 
                   3658: sub aboutmewrapper {
1.1070    raeburn  3659:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3660:     if (!defined($username)  && !defined($domain)) {
                   3661:         return;
                   3662:     }
1.1075.2.15  raeburn  3663:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3664: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3665: }
                   3666: 
                   3667: # ------------------------------------------------------------ Syllabus Wrapper
                   3668: 
                   3669: sub syllabuswrapper {
1.707     bisitz   3670:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3671:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3672: }
1.14      harris41 3673: 
1.802     bisitz   3674: # -----------------------------------------------------------------------------
                   3675: 
1.208     matthew  3676: sub track_student_link {
1.887     raeburn  3677:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3678:     my $link ="/adm/trackstudent?";
1.208     matthew  3679:     my $title = 'View recent activity';
                   3680:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3681:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3682:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3683:         $title .= ' of this student';
1.268     albertel 3684:     } 
1.208     matthew  3685:     if (defined($target) && $target !~ /^\s*$/) {
                   3686:         $target = qq{target="$target"};
                   3687:     } else {
                   3688:         $target = '';
                   3689:     }
1.268     albertel 3690:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3691:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3692:     $title = &mt($title);
                   3693:     $linktext = &mt($linktext);
1.448     albertel 3694:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3695: 	&help_open_topic('View_recent_activity');
1.208     matthew  3696: }
                   3697: 
1.781     raeburn  3698: sub slot_reservations_link {
                   3699:     my ($linktext,$sname,$sdom,$target) = @_;
                   3700:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3701:     my $title = 'View slot reservation history';
                   3702:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3703:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3704:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3705:         $title .= ' of this student';
                   3706:     }
                   3707:     if (defined($target) && $target !~ /^\s*$/) {
                   3708:         $target = qq{target="$target"};
                   3709:     } else {
                   3710:         $target = '';
                   3711:     }
                   3712:     $title = &mt($title);
                   3713:     $linktext = &mt($linktext);
                   3714:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3715: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3716: 
                   3717: }
                   3718: 
1.508     www      3719: # ===================================================== Display a student photo
                   3720: 
                   3721: 
1.509     albertel 3722: sub student_image_tag {
1.508     www      3723:     my ($domain,$user)=@_;
                   3724:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3725:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3726: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3727:     } else {
                   3728: 	return '';
                   3729:     }
                   3730: }
                   3731: 
1.112     bowersj2 3732: =pod
                   3733: 
                   3734: =back
                   3735: 
                   3736: =head1 Access .tab File Data
                   3737: 
                   3738: =over 4
                   3739: 
1.648     raeburn  3740: =item * &languageids() 
1.112     bowersj2 3741: 
                   3742: returns list of all language ids
                   3743: 
                   3744: =cut
                   3745: 
1.14      harris41 3746: sub languageids {
1.16      harris41 3747:     return sort(keys(%language));
1.14      harris41 3748: }
                   3749: 
1.112     bowersj2 3750: =pod
                   3751: 
1.648     raeburn  3752: =item * &languagedescription() 
1.112     bowersj2 3753: 
                   3754: returns description of a specified language id
                   3755: 
                   3756: =cut
                   3757: 
1.14      harris41 3758: sub languagedescription {
1.125     www      3759:     my $code=shift;
                   3760:     return  ($supported_language{$code}?'* ':'').
                   3761:             $language{$code}.
1.126     www      3762: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3763: }
                   3764: 
1.1048    foxr     3765: =pod
                   3766: 
                   3767: =item * &plainlanguagedescription
                   3768: 
                   3769: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3770: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3771: 
                   3772: =cut
                   3773: 
1.145     www      3774: sub plainlanguagedescription {
                   3775:     my $code=shift;
                   3776:     return $language{$code};
                   3777: }
                   3778: 
1.1048    foxr     3779: =pod
                   3780: 
                   3781: =item * &supportedlanguagecode
                   3782: 
                   3783: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3784: code.
                   3785: 
                   3786: =cut
                   3787: 
1.145     www      3788: sub supportedlanguagecode {
                   3789:     my $code=shift;
                   3790:     return $supported_language{$code};
1.97      www      3791: }
                   3792: 
1.112     bowersj2 3793: =pod
                   3794: 
1.1048    foxr     3795: =item * &latexlanguage()
                   3796: 
                   3797: Given a language key code returns the correspondnig language to use
                   3798: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3799: is no supported hyphenation for the language code.
                   3800: 
                   3801: =cut
                   3802: 
                   3803: sub latexlanguage {
                   3804:     my $code = shift;
                   3805:     return $latex_language{$code};
                   3806: }
                   3807: 
                   3808: =pod
                   3809: 
                   3810: =item * &latexhyphenation()
                   3811: 
                   3812: Same as above but what's supplied is the language as it might be stored
                   3813: in the metadata.
                   3814: 
                   3815: =cut
                   3816: 
                   3817: sub latexhyphenation {
                   3818:     my $key = shift;
                   3819:     return $latex_language_bykey{$key};
                   3820: }
                   3821: 
                   3822: =pod
                   3823: 
1.648     raeburn  3824: =item * &copyrightids() 
1.112     bowersj2 3825: 
                   3826: returns list of all copyrights
                   3827: 
                   3828: =cut
                   3829: 
                   3830: sub copyrightids {
                   3831:     return sort(keys(%cprtag));
                   3832: }
                   3833: 
                   3834: =pod
                   3835: 
1.648     raeburn  3836: =item * &copyrightdescription() 
1.112     bowersj2 3837: 
                   3838: returns description of a specified copyright id
                   3839: 
                   3840: =cut
                   3841: 
                   3842: sub copyrightdescription {
1.166     www      3843:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3844: }
1.197     matthew  3845: 
                   3846: =pod
                   3847: 
1.648     raeburn  3848: =item * &source_copyrightids() 
1.192     taceyjo1 3849: 
                   3850: returns list of all source copyrights
                   3851: 
                   3852: =cut
                   3853: 
                   3854: sub source_copyrightids {
                   3855:     return sort(keys(%scprtag));
                   3856: }
                   3857: 
                   3858: =pod
                   3859: 
1.648     raeburn  3860: =item * &source_copyrightdescription() 
1.192     taceyjo1 3861: 
                   3862: returns description of a specified source copyright id
                   3863: 
                   3864: =cut
                   3865: 
                   3866: sub source_copyrightdescription {
                   3867:     return &mt($scprtag{shift(@_)});
                   3868: }
1.112     bowersj2 3869: 
                   3870: =pod
                   3871: 
1.648     raeburn  3872: =item * &filecategories() 
1.112     bowersj2 3873: 
                   3874: returns list of all file categories
                   3875: 
                   3876: =cut
                   3877: 
                   3878: sub filecategories {
                   3879:     return sort(keys(%category_extensions));
                   3880: }
                   3881: 
                   3882: =pod
                   3883: 
1.648     raeburn  3884: =item * &filecategorytypes() 
1.112     bowersj2 3885: 
                   3886: returns list of file types belonging to a given file
                   3887: category
                   3888: 
                   3889: =cut
                   3890: 
                   3891: sub filecategorytypes {
1.356     albertel 3892:     my ($cat) = @_;
                   3893:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3894: }
                   3895: 
                   3896: =pod
                   3897: 
1.648     raeburn  3898: =item * &fileembstyle() 
1.112     bowersj2 3899: 
                   3900: returns embedding style for a specified file type
                   3901: 
                   3902: =cut
                   3903: 
                   3904: sub fileembstyle {
                   3905:     return $fe{lc(shift(@_))};
1.169     www      3906: }
                   3907: 
1.351     www      3908: sub filemimetype {
                   3909:     return $fm{lc(shift(@_))};
                   3910: }
                   3911: 
1.169     www      3912: 
                   3913: sub filecategoryselect {
                   3914:     my ($name,$value)=@_;
1.189     matthew  3915:     return &select_form($value,$name,
1.970     raeburn  3916:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3917: }
                   3918: 
                   3919: =pod
                   3920: 
1.648     raeburn  3921: =item * &filedescription() 
1.112     bowersj2 3922: 
                   3923: returns description for a specified file type
                   3924: 
                   3925: =cut
                   3926: 
                   3927: sub filedescription {
1.188     matthew  3928:     my $file_description = $fd{lc(shift())};
                   3929:     $file_description =~ s:([\[\]]):~$1:g;
                   3930:     return &mt($file_description);
1.112     bowersj2 3931: }
                   3932: 
                   3933: =pod
                   3934: 
1.648     raeburn  3935: =item * &filedescriptionex() 
1.112     bowersj2 3936: 
                   3937: returns description for a specified file type with
                   3938: extra formatting
                   3939: 
                   3940: =cut
                   3941: 
                   3942: sub filedescriptionex {
                   3943:     my $ex=shift;
1.188     matthew  3944:     my $file_description = $fd{lc($ex)};
                   3945:     $file_description =~ s:([\[\]]):~$1:g;
                   3946:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3947: }
                   3948: 
                   3949: # End of .tab access
                   3950: =pod
                   3951: 
                   3952: =back
                   3953: 
                   3954: =cut
                   3955: 
                   3956: # ------------------------------------------------------------------ File Types
                   3957: sub fileextensions {
                   3958:     return sort(keys(%fe));
                   3959: }
                   3960: 
1.97      www      3961: # ----------------------------------------------------------- Display Languages
                   3962: # returns a hash with all desired display languages
                   3963: #
                   3964: 
                   3965: sub display_languages {
                   3966:     my %languages=();
1.695     raeburn  3967:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3968: 	$languages{$lang}=1;
1.97      www      3969:     }
                   3970:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3971:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3972: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3973: 	    $languages{$lang}=1;
1.97      www      3974:         }
                   3975:     }
                   3976:     return %languages;
1.14      harris41 3977: }
                   3978: 
1.582     albertel 3979: sub languages {
                   3980:     my ($possible_langs) = @_;
1.695     raeburn  3981:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3982:     if (!ref($possible_langs)) {
                   3983: 	if( wantarray ) {
                   3984: 	    return @preferred_langs;
                   3985: 	} else {
                   3986: 	    return $preferred_langs[0];
                   3987: 	}
                   3988:     }
                   3989:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3990:     my @preferred_possibilities;
                   3991:     foreach my $preferred_lang (@preferred_langs) {
                   3992: 	if (exists($possibilities{$preferred_lang})) {
                   3993: 	    push(@preferred_possibilities, $preferred_lang);
                   3994: 	}
                   3995:     }
                   3996:     if( wantarray ) {
                   3997: 	return @preferred_possibilities;
                   3998:     }
                   3999:     return $preferred_possibilities[0];
                   4000: }
                   4001: 
1.742     raeburn  4002: sub user_lang {
                   4003:     my ($touname,$toudom,$fromcid) = @_;
                   4004:     my @userlangs;
                   4005:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4006:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4007:                     $env{'course.'.$fromcid.'.languages'}));
                   4008:     } else {
                   4009:         my %langhash = &getlangs($touname,$toudom);
                   4010:         if ($langhash{'languages'} ne '') {
                   4011:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4012:         } else {
                   4013:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4014:             if ($domdefs{'lang_def'} ne '') {
                   4015:                 @userlangs = ($domdefs{'lang_def'});
                   4016:             }
                   4017:         }
                   4018:     }
                   4019:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4020:     my $user_lh = Apache::localize->get_handle(@languages);
                   4021:     return $user_lh;
                   4022: }
                   4023: 
                   4024: 
1.112     bowersj2 4025: ###############################################################
                   4026: ##               Student Answer Attempts                     ##
                   4027: ###############################################################
                   4028: 
                   4029: =pod
                   4030: 
                   4031: =head1 Alternate Problem Views
                   4032: 
                   4033: =over 4
                   4034: 
1.648     raeburn  4035: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4036:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4037: 
                   4038: Return string with previous attempt on problem. Arguments:
                   4039: 
                   4040: =over 4
                   4041: 
                   4042: =item * $symb: Problem, including path
                   4043: 
                   4044: =item * $username: username of the desired student
                   4045: 
                   4046: =item * $domain: domain of the desired student
1.14      harris41 4047: 
1.112     bowersj2 4048: =item * $course: Course ID
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4051:     something
1.14      harris41 4052: 
1.112     bowersj2 4053: =item * $regexp: if string matches this regexp, the string will be
                   4054:     sent to $gradesub
1.14      harris41 4055: 
1.112     bowersj2 4056: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4057: 
1.1075.2.86  raeburn  4058: =item * $usec: section of the desired student
                   4059: 
                   4060: =item * $identifier: counter for student (multiple students one problem) or
                   4061:     problem (one student; whole sequence).
                   4062: 
1.112     bowersj2 4063: =back
1.14      harris41 4064: 
1.112     bowersj2 4065: The output string is a table containing all desired attempts, if any.
1.16      harris41 4066: 
1.112     bowersj2 4067: =cut
1.1       albertel 4068: 
                   4069: sub get_previous_attempt {
1.1075.2.86  raeburn  4070:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4071:   my $prevattempts='';
1.43      ng       4072:   no strict 'refs';
1.1       albertel 4073:   if ($symb) {
1.3       albertel 4074:     my (%returnhash)=
                   4075:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4076:     if ($returnhash{'version'}) {
                   4077:       my %lasthash=();
                   4078:       my $version;
                   4079:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4080:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4081:             if ($key =~ /\.rawrndseed$/) {
                   4082:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4083:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4084:             } else {
                   4085:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4086:             }
1.19      harris41 4087:         }
1.1       albertel 4088:       }
1.596     albertel 4089:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4090:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4091:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4092:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4093:       foreach my $key (sort(keys(%lasthash))) {
                   4094: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4095: 	if ($#parts > 0) {
1.31      albertel 4096: 	  my $data=$parts[-1];
1.989     raeburn  4097:           next if ($data eq 'foilorder');
1.31      albertel 4098: 	  pop(@parts);
1.1010    www      4099:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4100:           if ($data eq 'type') {
                   4101:               unless ($showsurv) {
                   4102:                   my $id = join(',',@parts);
                   4103:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4104:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4105:                       $lasthidden{$ign.'.'.$id} = 1;
                   4106:                   }
1.945     raeburn  4107:               }
1.1075.2.86  raeburn  4108:               if ($identifier ne '') {
                   4109:                   my $id = join(',',@parts);
                   4110:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4111:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4112:                       $hidestatus{$ign.'.'.$id} = 1;
                   4113:                   }
                   4114:               }
                   4115:           } elsif ($data eq 'regrader') {
                   4116:               if (($identifier ne '') && (@parts)) {
                   4117:                   my $id = join(',',@parts);
                   4118:                   $regraded{$ign.'.'.$id} = 1;
                   4119:               }
1.1010    www      4120:           } 
1.31      albertel 4121: 	} else {
1.41      ng       4122: 	  if ($#parts == 0) {
                   4123: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4124: 	  } else {
                   4125: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4126: 	  }
1.31      albertel 4127: 	}
1.16      harris41 4128:       }
1.596     albertel 4129:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4130:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4131:         my (%solved,%resets,%probstatus);
                   4132:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4133:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4134:                 foreach my $id (keys(%regraded)) {
                   4135:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4136:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4137:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4138:                         push(@{$resets{$id}},$version);
                   4139:                     }
                   4140:                 }
                   4141:             }
                   4142:         }
1.40      ng       4143: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4144:             my (@hidden,@unsolved);
1.945     raeburn  4145:             if (%typeparts) {
                   4146:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4147:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4148:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4149:                         push(@hidden,$id);
1.1075.2.86  raeburn  4150:                     } elsif ($identifier ne '') {
                   4151:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4152:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4153:                                 ($hidestatus{$id})) {
                   4154:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4155:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4156:                                 push(@{$solved{$id}},$version);
                   4157:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4158:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4159:                                 my $skip;
                   4160:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4161:                                     foreach my $reset (@{$resets{$id}}) {
                   4162:                                         if ($reset > $solved{$id}[-1]) {
                   4163:                                             $skip=1;
                   4164:                                             last;
                   4165:                                         }
                   4166:                                     }
                   4167:                                 }
                   4168:                                 unless ($skip) {
                   4169:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4170:                                     push(@unsolved,$partslist);
                   4171:                                 }
                   4172:                             }
                   4173:                         }
1.945     raeburn  4174:                     }
                   4175:                 }
                   4176:             }
                   4177:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4178:                            '<td>'.&mt('Transaction [_1]',$version);
                   4179:             if (@unsolved) {
                   4180:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4181:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4182:                                  &mt('Hide').'</label></span>';
                   4183:             }
                   4184:             $prevattempts .= '</td>';
1.945     raeburn  4185:             if (@hidden) {
                   4186:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4187:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4188:                     my $hide;
                   4189:                     foreach my $id (@hidden) {
                   4190:                         if ($key =~ /^\Q$id\E/) {
                   4191:                             $hide = 1;
                   4192:                             last;
                   4193:                         }
                   4194:                     }
                   4195:                     if ($hide) {
                   4196:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4197:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4198:                             my $value = &format_previous_attempt_value($key,
                   4199:                                              $returnhash{$version.':'.$key});
                   4200:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4201:                         } else {
                   4202:                             $prevattempts.='<td>&nbsp;</td>';
                   4203:                         }
                   4204:                     } else {
                   4205:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4206:                             my $value = $returnhash{$version.':'.$key};
                   4207:                             if ($key =~ /\.rndseed$/) {
                   4208:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4209:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4210:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4211:                                 }
                   4212:                             }
                   4213:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4214:                                            '&nbsp;</td>';
1.945     raeburn  4215:                         } else {
                   4216:                             $prevattempts.='<td>&nbsp;</td>';
                   4217:                         }
                   4218:                     }
                   4219:                 }
                   4220:             } else {
                   4221: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4222:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4223:                     my $value = $returnhash{$version.':'.$key};
                   4224:                     if ($key =~ /\.rndseed$/) {
                   4225:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4226:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4227:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4228:                         }
                   4229:                     }
                   4230:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4231:                                    '&nbsp;</td>';
1.945     raeburn  4232: 	        }
                   4233:             }
                   4234: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4235: 	 }
1.1       albertel 4236:       }
1.945     raeburn  4237:       my @currhidden = keys(%lasthidden);
1.596     albertel 4238:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4239:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4240:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4241:           if (%typeparts) {
                   4242:               my $hidden;
                   4243:               foreach my $id (@currhidden) {
                   4244:                   if ($key =~ /^\Q$id\E/) {
                   4245:                       $hidden = 1;
                   4246:                       last;
                   4247:                   }
                   4248:               }
                   4249:               if ($hidden) {
                   4250:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4251:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4252:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4253:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4254:                           $value = &$gradesub($value);
                   4255:                       }
                   4256:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4257:                   } else {
                   4258:                       $prevattempts.='<td>&nbsp;</td>';
                   4259:                   }
                   4260:               } else {
                   4261:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4262:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4263:                       $value = &$gradesub($value);
                   4264:                   }
                   4265:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4266:               }
                   4267:           } else {
                   4268: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4269: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4270:                   $value = &$gradesub($value);
                   4271:               }
                   4272: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4273:           }
1.16      harris41 4274:       }
1.596     albertel 4275:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4276:     } else {
1.596     albertel 4277:       $prevattempts=
                   4278: 	  &start_data_table().&start_data_table_row().
                   4279: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4280: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4281:     }
                   4282:   } else {
1.596     albertel 4283:     $prevattempts=
                   4284: 	  &start_data_table().&start_data_table_row().
                   4285: 	  '<td>'.&mt('No data.').'</td>'.
                   4286: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4287:   }
1.10      albertel 4288: }
                   4289: 
1.581     albertel 4290: sub format_previous_attempt_value {
                   4291:     my ($key,$value) = @_;
1.1011    www      4292:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4293: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4294:     } elsif (ref($value) eq 'ARRAY') {
                   4295: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4296:     } elsif ($key =~ /answerstring$/) {
                   4297:         my %answers = &Apache::lonnet::str2hash($value);
                   4298:         my @anskeys = sort(keys(%answers));
                   4299:         if (@anskeys == 1) {
                   4300:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4301:             if ($answer =~ m{\0}) {
                   4302:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4303:             }
                   4304:             my $tag_internal_answer_name = 'INTERNAL';
                   4305:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4306:                 $value = $answer; 
                   4307:             } else {
                   4308:                 $value = $anskeys[0].'='.$answer;
                   4309:             }
                   4310:         } else {
                   4311:             foreach my $ans (@anskeys) {
                   4312:                 my $answer = $answers{$ans};
1.1001    raeburn  4313:                 if ($answer =~ m{\0}) {
                   4314:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4315:                 }
                   4316:                 $value .=  $ans.'='.$answer.'<br />';;
                   4317:             } 
                   4318:         }
1.581     albertel 4319:     } else {
                   4320: 	$value = &unescape($value);
                   4321:     }
                   4322:     return $value;
                   4323: }
                   4324: 
                   4325: 
1.107     albertel 4326: sub relative_to_absolute {
                   4327:     my ($url,$output)=@_;
                   4328:     my $parser=HTML::TokeParser->new(\$output);
                   4329:     my $token;
                   4330:     my $thisdir=$url;
                   4331:     my @rlinks=();
                   4332:     while ($token=$parser->get_token) {
                   4333: 	if ($token->[0] eq 'S') {
                   4334: 	    if ($token->[1] eq 'a') {
                   4335: 		if ($token->[2]->{'href'}) {
                   4336: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4337: 		}
                   4338: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4339: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4340: 	    } elsif ($token->[1] eq 'base') {
                   4341: 		$thisdir=$token->[2]->{'href'};
                   4342: 	    }
                   4343: 	}
                   4344:     }
                   4345:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4346:     foreach my $link (@rlinks) {
1.726     raeburn  4347: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4348: 		($link=~/^\//) ||
                   4349: 		($link=~/^javascript:/i) ||
                   4350: 		($link=~/^mailto:/i) ||
                   4351: 		($link=~/^\#/)) {
                   4352: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4353: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4354: 	}
                   4355:     }
                   4356: # -------------------------------------------------- Deal with Applet codebases
                   4357:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4358:     return $output;
                   4359: }
                   4360: 
1.112     bowersj2 4361: =pod
                   4362: 
1.648     raeburn  4363: =item * &get_student_view()
1.112     bowersj2 4364: 
                   4365: show a snapshot of what student was looking at
                   4366: 
                   4367: =cut
                   4368: 
1.10      albertel 4369: sub get_student_view {
1.186     albertel 4370:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4371:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4372:   my (%form);
1.10      albertel 4373:   my @elements=('symb','courseid','domain','username');
                   4374:   foreach my $element (@elements) {
1.186     albertel 4375:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4376:   }
1.186     albertel 4377:   if (defined($moreenv)) {
                   4378:       %form=(%form,%{$moreenv});
                   4379:   }
1.236     albertel 4380:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4381:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4382:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4383:   $userview=~s/\<body[^\>]*\>//gi;
                   4384:   $userview=~s/\<\/body\>//gi;
                   4385:   $userview=~s/\<html\>//gi;
                   4386:   $userview=~s/\<\/html\>//gi;
                   4387:   $userview=~s/\<head\>//gi;
                   4388:   $userview=~s/\<\/head\>//gi;
                   4389:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4390:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4391:   if (wantarray) {
                   4392:      return ($userview,$response);
                   4393:   } else {
                   4394:      return $userview;
                   4395:   }
                   4396: }
                   4397: 
                   4398: sub get_student_view_with_retries {
                   4399:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4400: 
                   4401:     my $ok = 0;                 # True if we got a good response.
                   4402:     my $content;
                   4403:     my $response;
                   4404: 
                   4405:     # Try to get the student_view done. within the retries count:
                   4406:     
                   4407:     do {
                   4408:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4409:          $ok      = $response->is_success;
                   4410:          if (!$ok) {
                   4411:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4412:          }
                   4413:          $retries--;
                   4414:     } while (!$ok && ($retries > 0));
                   4415:     
                   4416:     if (!$ok) {
                   4417:        $content = '';          # On error return an empty content.
                   4418:     }
1.651     www      4419:     if (wantarray) {
                   4420:        return ($content, $response);
                   4421:     } else {
                   4422:        return $content;
                   4423:     }
1.11      albertel 4424: }
                   4425: 
1.1075.2.149  raeburn  4426: sub css_links {
                   4427:     my ($currsymb,$level) = @_;
                   4428:     my ($links,@symbs,%cssrefs,%httpref);
                   4429:     if ($level eq 'map') {
                   4430:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4431:         if (ref($navmap)) {
                   4432:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4433:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4434:             foreach my $res (@resources) {
                   4435:                 if (ref($res) && $res->symb()) {
                   4436:                     push(@symbs,$res->symb());
                   4437:                 }
                   4438:             }
                   4439:         }
                   4440:     } else {
                   4441:         @symbs = ($currsymb);
                   4442:     }
                   4443:     foreach my $symb (@symbs) {
                   4444:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4445:         if ($css_href =~ /\S/) {
                   4446:             unless ($css_href =~ m{https?://}) {
                   4447:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4448:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4449:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4450:                 unless ($css_href =~ m{^/}) {
                   4451:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4452:                 }
                   4453:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4454:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4455:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4456:                         my $thisurl = $proburl;
                   4457:                         if ($env{'httpref.'.$proburl}) {
                   4458:                             $thisurl = $env{'httpref.'.$proburl};
                   4459:                         }
                   4460:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4461:                     }
                   4462:                 }
                   4463:             }
                   4464:             $cssrefs{$css_href} = 1;
                   4465:         }
                   4466:     }
                   4467:     if (keys(%httpref)) {
                   4468:         &Apache::lonnet::appenv(\%httpref);
                   4469:     }
                   4470:     if (keys(%cssrefs)) {
                   4471:         foreach my $css_href (keys(%cssrefs)) {
                   4472:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4473:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4474:         }
                   4475:     }
                   4476:     return $links;
                   4477: }
                   4478: 
1.112     bowersj2 4479: =pod
                   4480: 
1.648     raeburn  4481: =item * &get_student_answers() 
1.112     bowersj2 4482: 
                   4483: show a snapshot of how student was answering problem
                   4484: 
                   4485: =cut
                   4486: 
1.11      albertel 4487: sub get_student_answers {
1.100     sakharuk 4488:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4489:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4490:   my (%moreenv);
1.11      albertel 4491:   my @elements=('symb','courseid','domain','username');
                   4492:   foreach my $element (@elements) {
1.186     albertel 4493:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4494:   }
1.186     albertel 4495:   $moreenv{'grade_target'}='answer';
                   4496:   %moreenv=(%form,%moreenv);
1.497     raeburn  4497:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4498:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4499:   return $userview;
1.1       albertel 4500: }
1.116     albertel 4501: 
                   4502: =pod
                   4503: 
                   4504: =item * &submlink()
                   4505: 
1.242     albertel 4506: Inputs: $text $uname $udom $symb $target
1.116     albertel 4507: 
                   4508: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4509: 
                   4510: =cut
                   4511: 
                   4512: ###############################################
                   4513: sub submlink {
1.242     albertel 4514:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4515:     if (!($uname && $udom)) {
                   4516: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4517: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4518: 	if (!$symb) { $symb=$cursymb; }
                   4519:     }
1.254     matthew  4520:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4521:     $symb=&escape($symb);
1.960     bisitz   4522:     if ($target) { $target=" target=\"$target\""; }
                   4523:     return
                   4524:         '<a href="/adm/grades?command=submission'.
                   4525:         '&amp;symb='.$symb.
                   4526:         '&amp;student='.$uname.
                   4527:         '&amp;userdom='.$udom.'"'.
                   4528:         $target.'>'.$text.'</a>';
1.242     albertel 4529: }
                   4530: ##############################################
                   4531: 
                   4532: =pod
                   4533: 
                   4534: =item * &pgrdlink()
                   4535: 
                   4536: Inputs: $text $uname $udom $symb $target
                   4537: 
                   4538: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4539: 
                   4540: =cut
                   4541: 
                   4542: ###############################################
                   4543: sub pgrdlink {
                   4544:     my $link=&submlink(@_);
                   4545:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4546:     return $link;
                   4547: }
                   4548: ##############################################
                   4549: 
                   4550: =pod
                   4551: 
                   4552: =item * &pprmlink()
                   4553: 
                   4554: Inputs: $text $uname $udom $symb $target
                   4555: 
                   4556: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4557: student and a specific resource
1.242     albertel 4558: 
                   4559: =cut
                   4560: 
                   4561: ###############################################
                   4562: sub pprmlink {
                   4563:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4564:     if (!($uname && $udom)) {
                   4565: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4566: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4567: 	if (!$symb) { $symb=$cursymb; }
                   4568:     }
1.254     matthew  4569:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4570:     $symb=&escape($symb);
1.242     albertel 4571:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4572:     return '<a href="/adm/parmset?command=set&amp;'.
                   4573: 	'symb='.$symb.'&amp;uname='.$uname.
                   4574: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4575: }
                   4576: ##############################################
1.37      matthew  4577: 
1.112     bowersj2 4578: =pod
                   4579: 
                   4580: =back
                   4581: 
                   4582: =cut
                   4583: 
1.37      matthew  4584: ###############################################
1.51      www      4585: 
                   4586: 
                   4587: sub timehash {
1.687     raeburn  4588:     my ($thistime) = @_;
                   4589:     my $timezone = &Apache::lonlocal::gettimezone();
                   4590:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4591:                      ->set_time_zone($timezone);
                   4592:     my $wday = $dt->day_of_week();
                   4593:     if ($wday == 7) { $wday = 0; }
                   4594:     return ( 'second' => $dt->second(),
                   4595:              'minute' => $dt->minute(),
                   4596:              'hour'   => $dt->hour(),
                   4597:              'day'     => $dt->day_of_month(),
                   4598:              'month'   => $dt->month(),
                   4599:              'year'    => $dt->year(),
                   4600:              'weekday' => $wday,
                   4601:              'dayyear' => $dt->day_of_year(),
                   4602:              'dlsav'   => $dt->is_dst() );
1.51      www      4603: }
                   4604: 
1.370     www      4605: sub utc_string {
                   4606:     my ($date)=@_;
1.371     www      4607:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4608: }
                   4609: 
1.51      www      4610: sub maketime {
                   4611:     my %th=@_;
1.687     raeburn  4612:     my ($epoch_time,$timezone,$dt);
                   4613:     $timezone = &Apache::lonlocal::gettimezone();
                   4614:     eval {
                   4615:         $dt = DateTime->new( year   => $th{'year'},
                   4616:                              month  => $th{'month'},
                   4617:                              day    => $th{'day'},
                   4618:                              hour   => $th{'hour'},
                   4619:                              minute => $th{'minute'},
                   4620:                              second => $th{'second'},
                   4621:                              time_zone => $timezone,
                   4622:                          );
                   4623:     };
                   4624:     if (!$@) {
                   4625:         $epoch_time = $dt->epoch;
                   4626:         if ($epoch_time) {
                   4627:             return $epoch_time;
                   4628:         }
                   4629:     }
1.51      www      4630:     return POSIX::mktime(
                   4631:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4632:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4633: }
                   4634: 
                   4635: #########################################
1.51      www      4636: 
                   4637: sub findallcourses {
1.482     raeburn  4638:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4639:     my %roles;
                   4640:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4641:     my %courses;
1.51      www      4642:     my $now=time;
1.482     raeburn  4643:     if (!defined($uname)) {
                   4644:         $uname = $env{'user.name'};
                   4645:     }
                   4646:     if (!defined($udom)) {
                   4647:         $udom = $env{'user.domain'};
                   4648:     }
                   4649:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4650:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4651:         if (!%roles) {
                   4652:             %roles = (
                   4653:                        cc => 1,
1.907     raeburn  4654:                        co => 1,
1.482     raeburn  4655:                        in => 1,
                   4656:                        ep => 1,
                   4657:                        ta => 1,
                   4658:                        cr => 1,
                   4659:                        st => 1,
                   4660:              );
                   4661:         }
                   4662:         foreach my $entry (keys(%roleshash)) {
                   4663:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4664:             if ($trole =~ /^cr/) { 
                   4665:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4666:             } else {
                   4667:                 next if (!exists($roles{$trole}));
                   4668:             }
                   4669:             if ($tend) {
                   4670:                 next if ($tend < $now);
                   4671:             }
                   4672:             if ($tstart) {
                   4673:                 next if ($tstart > $now);
                   4674:             }
1.1058    raeburn  4675:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4676:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4677:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4678:             if ($secpart eq '') {
                   4679:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4680:                 $sec = 'none';
1.1058    raeburn  4681:                 $value .= $cnum.'/';
1.482     raeburn  4682:             } else {
                   4683:                 $cnum = $cnumpart;
                   4684:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4685:                 $value .= $cnum.'/'.$sec;
                   4686:             }
                   4687:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4688:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4689:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4690:                 }
                   4691:             } else {
                   4692:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4693:             }
1.482     raeburn  4694:         }
                   4695:     } else {
                   4696:         foreach my $key (keys(%env)) {
1.483     albertel 4697: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4698:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4699: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4700: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4701: 	        next if (%roles && !exists($roles{$role}));
                   4702: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4703:                 my $active=1;
                   4704:                 if ($starttime) {
                   4705: 		    if ($now<$starttime) { $active=0; }
                   4706:                 }
                   4707:                 if ($endtime) {
                   4708:                     if ($now>$endtime) { $active=0; }
                   4709:                 }
                   4710:                 if ($active) {
1.1058    raeburn  4711:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4712:                     if ($sec eq '') {
                   4713:                         $sec = 'none';
1.1058    raeburn  4714:                     } else {
                   4715:                         $value .= $sec;
                   4716:                     }
                   4717:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4718:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4719:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4720:                         }
                   4721:                     } else {
                   4722:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4723:                     }
1.474     raeburn  4724:                 }
                   4725:             }
1.51      www      4726:         }
                   4727:     }
1.474     raeburn  4728:     return %courses;
1.51      www      4729: }
1.37      matthew  4730: 
1.54      www      4731: ###############################################
1.474     raeburn  4732: 
                   4733: sub blockcheck {
1.1075.2.147  raeburn  4734:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4735: 
1.1075.2.73  raeburn  4736:     if (defined($udom) && defined($uname)) {
                   4737:         # If uname and udom are for a course, check for blocks in the course.
                   4738:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4739:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  4740:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  4741:             return ($startblock,$endblock,$triggerblock);
                   4742:         }
                   4743:     } else {
1.490     raeburn  4744:         $udom = $env{'user.domain'};
                   4745:         $uname = $env{'user.name'};
                   4746:     }
                   4747: 
1.502     raeburn  4748:     my $startblock = 0;
                   4749:     my $endblock = 0;
1.1062    raeburn  4750:     my $triggerblock = '';
1.482     raeburn  4751:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4752: 
1.490     raeburn  4753:     # If uname is for a user, and activity is course-specific, i.e.,
                   4754:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4755: 
1.490     raeburn  4756:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4757:          $activity eq 'groups' || $activity eq 'printout') &&
                   4758:         ($env{'request.course.id'})) {
1.490     raeburn  4759:         foreach my $key (keys(%live_courses)) {
                   4760:             if ($key ne $env{'request.course.id'}) {
                   4761:                 delete($live_courses{$key});
                   4762:             }
                   4763:         }
                   4764:     }
                   4765: 
                   4766:     my $otheruser = 0;
                   4767:     my %own_courses;
                   4768:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4769:         # Resource belongs to user other than current user.
                   4770:         $otheruser = 1;
                   4771:         # Gather courses for current user
                   4772:         %own_courses = 
                   4773:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4774:     }
                   4775: 
                   4776:     # Gather active course roles - course coordinator, instructor, 
                   4777:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4778: 
                   4779:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4780:         my ($cdom,$cnum);
                   4781:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4782:             $cdom = $env{'course.'.$course.'.domain'};
                   4783:             $cnum = $env{'course.'.$course.'.num'};
                   4784:         } else {
1.490     raeburn  4785:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4786:         }
                   4787:         my $no_ownblock = 0;
                   4788:         my $no_userblock = 0;
1.533     raeburn  4789:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4790:             # Check if current user has 'evb' priv for this
                   4791:             if (defined($own_courses{$course})) {
                   4792:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4793:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4794:                     if ($sec ne 'none') {
                   4795:                         $checkrole .= '/'.$sec;
                   4796:                     }
                   4797:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4798:                         $no_ownblock = 1;
                   4799:                         last;
                   4800:                     }
                   4801:                 }
                   4802:             }
                   4803:             # if they have 'evb' priv and are currently not playing student
                   4804:             next if (($no_ownblock) &&
                   4805:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4806:         }
1.474     raeburn  4807:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4808:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4809:             if ($sec ne 'none') {
1.482     raeburn  4810:                 $checkrole .= '/'.$sec;
1.474     raeburn  4811:             }
1.490     raeburn  4812:             if ($otheruser) {
                   4813:                 # Resource belongs to user other than current user.
                   4814:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4815:                 my (%allroles,%userroles);
                   4816:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4817:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4818:                         my ($trole,$tdom,$tnum,$tsec);
                   4819:                         if ($entry =~ /^cr/) {
                   4820:                             ($trole,$tdom,$tnum,$tsec) = 
                   4821:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4822:                         } else {
                   4823:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4824:                         }
                   4825:                         my ($spec,$area,$trest);
                   4826:                         $area = '/'.$tdom.'/'.$tnum;
                   4827:                         $trest = $tnum;
                   4828:                         if ($tsec ne '') {
                   4829:                             $area .= '/'.$tsec;
                   4830:                             $trest .= '/'.$tsec;
                   4831:                         }
                   4832:                         $spec = $trole.'.'.$area;
                   4833:                         if ($trole =~ /^cr/) {
                   4834:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4835:                                                               $tdom,$spec,$trest,$area);
                   4836:                         } else {
                   4837:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4838:                                                                 $tdom,$spec,$trest,$area);
                   4839:                         }
                   4840:                     }
1.1075.2.124  raeburn  4841:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4842:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4843:                         if ($1) {
                   4844:                             $no_userblock = 1;
                   4845:                             last;
                   4846:                         }
1.486     raeburn  4847:                     }
                   4848:                 }
1.490     raeburn  4849:             } else {
                   4850:                 # Resource belongs to current user
                   4851:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4852:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4853:                     $no_ownblock = 1;
                   4854:                     last;
                   4855:                 }
1.474     raeburn  4856:             }
                   4857:         }
                   4858:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4859:         next if (($no_ownblock) &&
1.491     albertel 4860:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4861:         next if ($no_userblock);
1.474     raeburn  4862: 
1.1075.2.128  raeburn  4863:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4864:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4865:         
1.1062    raeburn  4866:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  4867:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  4868:         if (($start != 0) && 
                   4869:             (($startblock == 0) || ($startblock > $start))) {
                   4870:             $startblock = $start;
1.1062    raeburn  4871:             if ($trigger ne '') {
                   4872:                 $triggerblock = $trigger;
                   4873:             }
1.502     raeburn  4874:         }
                   4875:         if (($end != 0)  &&
                   4876:             (($endblock == 0) || ($endblock < $end))) {
                   4877:             $endblock = $end;
1.1062    raeburn  4878:             if ($trigger ne '') {
                   4879:                 $triggerblock = $trigger;
                   4880:             }
1.502     raeburn  4881:         }
1.490     raeburn  4882:     }
1.1062    raeburn  4883:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4884: }
                   4885: 
                   4886: sub get_blocks {
1.1075.2.147  raeburn  4887:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  4888:     my $startblock = 0;
                   4889:     my $endblock = 0;
1.1062    raeburn  4890:     my $triggerblock = '';
1.490     raeburn  4891:     my $course = $cdom.'_'.$cnum;
                   4892:     $setters->{$course} = {};
                   4893:     $setters->{$course}{'staff'} = [];
                   4894:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4895:     $setters->{$course}{'triggers'} = [];
                   4896:     my (@blockers,%triggered);
                   4897:     my $now = time;
                   4898:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4899:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  4900:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  4901:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   4902:             $blocked = 1;
                   4903:             $nosymbcache = 1;
1.1075.2.148  raeburn  4904:             $noenccheck = 1;
1.1075.2.147  raeburn  4905:         }
1.1075.2.148  raeburn  4906:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  4907:         foreach my $block (@blockers) {
                   4908:             if ($block =~ /^firstaccess____(.+)$/) {
                   4909:                 my $item = $1;
                   4910:                 my $type = 'map';
                   4911:                 my $timersymb = $item;
                   4912:                 if ($item eq 'course') {
                   4913:                     $type = 'course';
                   4914:                 } elsif ($item =~ /___\d+___/) {
                   4915:                     $type = 'resource';
                   4916:                 } else {
                   4917:                     $timersymb = &Apache::lonnet::symbread($item);
                   4918:                 }
                   4919:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4920:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4921:                 $triggered{$block} = {
                   4922:                                        start => $start,
                   4923:                                        end   => $end,
                   4924:                                        type  => $type,
                   4925:                                      };
                   4926:             }
                   4927:         }
                   4928:     } else {
                   4929:         foreach my $block (keys(%commblocks)) {
                   4930:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4931:                 my ($start,$end) = ($1,$2);
                   4932:                 if ($start <= time && $end >= time) {
                   4933:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4934:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4935:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4936:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4937:                                     push(@blockers,$block);
                   4938:                                 }
                   4939:                             }
                   4940:                         }
                   4941:                     }
                   4942:                 }
                   4943:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4944:                 my $item = $1;
                   4945:                 my $timersymb = $item; 
                   4946:                 my $type = 'map';
                   4947:                 if ($item eq 'course') {
                   4948:                     $type = 'course';
                   4949:                 } elsif ($item =~ /___\d+___/) {
                   4950:                     $type = 'resource';
                   4951:                 } else {
                   4952:                     $timersymb = &Apache::lonnet::symbread($item);
                   4953:                 }
                   4954:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4955:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4956:                 if ($start && $end) {
                   4957:                     if (($start <= time) && ($end >= time)) {
                   4958:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4959:                             push(@blockers,$block);
                   4960:                             $triggered{$block} = {
                   4961:                                                    start => $start,
                   4962:                                                    end   => $end,
                   4963:                                                    type  => $type,
                   4964:                                                  };
                   4965:                         }
                   4966:                     }
1.490     raeburn  4967:                 }
1.1062    raeburn  4968:             }
                   4969:         }
                   4970:     }
                   4971:     foreach my $blocker (@blockers) {
                   4972:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4973:             &parse_block_record($commblocks{$blocker});
                   4974:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4975:         my ($start,$end,$triggertype);
                   4976:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4977:             ($start,$end) = ($1,$2);
                   4978:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4979:             $start = $triggered{$blocker}{'start'};
                   4980:             $end = $triggered{$blocker}{'end'};
                   4981:             $triggertype = $triggered{$blocker}{'type'};
                   4982:         }
                   4983:         if ($start) {
                   4984:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4985:             if ($triggertype) {
                   4986:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4987:             } else {
                   4988:                 push(@{$$setters{$course}{'triggers'}},0);
                   4989:             }
                   4990:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4991:                 $startblock = $start;
                   4992:                 if ($triggertype) {
                   4993:                     $triggerblock = $blocker;
1.474     raeburn  4994:                 }
                   4995:             }
1.1062    raeburn  4996:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4997:                $endblock = $end;
                   4998:                if ($triggertype) {
                   4999:                    $triggerblock = $blocker;
                   5000:                }
                   5001:             }
1.474     raeburn  5002:         }
                   5003:     }
1.1062    raeburn  5004:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5005: }
                   5006: 
                   5007: sub parse_block_record {
                   5008:     my ($record) = @_;
                   5009:     my ($setuname,$setudom,$title,$blocks);
                   5010:     if (ref($record) eq 'HASH') {
                   5011:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5012:         $title = &unescape($record->{'event'});
                   5013:         $blocks = $record->{'blocks'};
                   5014:     } else {
                   5015:         my @data = split(/:/,$record,3);
                   5016:         if (scalar(@data) eq 2) {
                   5017:             $title = $data[1];
                   5018:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5019:         } else {
                   5020:             ($setuname,$setudom,$title) = @data;
                   5021:         }
                   5022:         $blocks = { 'com' => 'on' };
                   5023:     }
                   5024:     return ($setuname,$setudom,$title,$blocks);
                   5025: }
                   5026: 
1.854     kalberla 5027: sub blocking_status {
1.1075.2.147  raeburn  5028:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5029:     my %setters;
1.890     droeschl 5030: 
1.1061    raeburn  5031: # check for active blocking
1.1062    raeburn  5032:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.147  raeburn  5033:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5034:     my $blocked = 0;
                   5035:     if ($startblock && $endblock) {
                   5036:         $blocked = 1;
                   5037:     }
1.890     droeschl 5038: 
1.1061    raeburn  5039: # caller just wants to know whether a block is active
                   5040:     if (!wantarray) { return $blocked; }
                   5041: 
                   5042: # build a link to a popup window containing the details
                   5043:     my $querystring  = "?activity=$activity";
                   5044: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  5045:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5046:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5047:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5048:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5049:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5050:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5051:         if ($symb) {
                   5052:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5053:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5054:         }
1.1062    raeburn  5055:     }
1.1061    raeburn  5056: 
                   5057:     my $output .= <<'END_MYBLOCK';
                   5058: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5059:     var options = "width=" + w + ",height=" + h + ",";
                   5060:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5061:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5062:     var newWin = window.open(url, wdwName, options);
                   5063:     newWin.focus();
                   5064: }
1.890     droeschl 5065: END_MYBLOCK
1.854     kalberla 5066: 
1.1061    raeburn  5067:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5068:   
1.1061    raeburn  5069:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5070:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5071:     my $class = 'LC_comblock';
1.1062    raeburn  5072:     if ($activity eq 'docs') {
                   5073:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5074:         $class = '';
1.1063    raeburn  5075:     } elsif ($activity eq 'printout') {
                   5076:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5077:     } elsif ($activity eq 'passwd') {
                   5078:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5079:     }
1.1061    raeburn  5080:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5081: <div class='$class'>
1.869     kalberla 5082:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5083:   title='$text'>
                   5084:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5085:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5086:   title='$text'>$text</a>
1.867     kalberla 5087: </div>
                   5088: 
                   5089: END_BLOCK
1.474     raeburn  5090: 
1.1061    raeburn  5091:     return ($blocked, $output);
1.854     kalberla 5092: }
1.490     raeburn  5093: 
1.60      matthew  5094: ###############################################
                   5095: 
1.682     raeburn  5096: sub check_ip_acc {
1.1075.2.105  raeburn  5097:     my ($acc,$clientip)=@_;
1.682     raeburn  5098:     &Apache::lonxml::debug("acc is $acc");
                   5099:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5100:         return 1;
                   5101:     }
                   5102:     my $allowed=0;
1.1075.2.144  raeburn  5103:     my $ip;
                   5104:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5105:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5106:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5107:     } else {
1.1075.2.150  raeburn  5108:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5109:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5110:     }
1.682     raeburn  5111: 
                   5112:     my $name;
                   5113:     foreach my $pattern (split(',',$acc)) {
                   5114:         $pattern =~ s/^\s*//;
                   5115:         $pattern =~ s/\s*$//;
                   5116:         if ($pattern =~ /\*$/) {
                   5117:             #35.8.*
                   5118:             $pattern=~s/\*//;
                   5119:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5120:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5121:             #35.8.3.[34-56]
                   5122:             my $low=$2;
                   5123:             my $high=$3;
                   5124:             $pattern=$1;
                   5125:             if ($ip =~ /^\Q$pattern\E/) {
                   5126:                 my $last=(split(/\./,$ip))[3];
                   5127:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5128:             }
                   5129:         } elsif ($pattern =~ /^\*/) {
                   5130:             #*.msu.edu
                   5131:             $pattern=~s/\*//;
                   5132:             if (!defined($name)) {
                   5133:                 use Socket;
                   5134:                 my $netaddr=inet_aton($ip);
                   5135:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5136:             }
                   5137:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5138:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5139:             #127.0.0.1
                   5140:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5141:         } else {
                   5142:             #some.name.com
                   5143:             if (!defined($name)) {
                   5144:                 use Socket;
                   5145:                 my $netaddr=inet_aton($ip);
                   5146:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5147:             }
                   5148:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5149:         }
                   5150:         if ($allowed) { last; }
                   5151:     }
                   5152:     return $allowed;
                   5153: }
                   5154: 
                   5155: ###############################################
                   5156: 
1.60      matthew  5157: =pod
                   5158: 
1.112     bowersj2 5159: =head1 Domain Template Functions
                   5160: 
                   5161: =over 4
                   5162: 
                   5163: =item * &determinedomain()
1.60      matthew  5164: 
                   5165: Inputs: $domain (usually will be undef)
                   5166: 
1.63      www      5167: Returns: Determines which domain should be used for designs
1.60      matthew  5168: 
                   5169: =cut
1.54      www      5170: 
1.60      matthew  5171: ###############################################
1.63      www      5172: sub determinedomain {
                   5173:     my $domain=shift;
1.531     albertel 5174:     if (! $domain) {
1.60      matthew  5175:         # Determine domain if we have not been given one
1.893     raeburn  5176:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5177:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5178:         if ($env{'request.role.domain'}) { 
                   5179:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5180:         }
                   5181:     }
1.63      www      5182:     return $domain;
                   5183: }
                   5184: ###############################################
1.517     raeburn  5185: 
1.518     albertel 5186: sub devalidate_domconfig_cache {
                   5187:     my ($udom)=@_;
                   5188:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5189: }
                   5190: 
                   5191: # ---------------------- Get domain configuration for a domain
                   5192: sub get_domainconf {
                   5193:     my ($udom) = @_;
                   5194:     my $cachetime=1800;
                   5195:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5196:     if (defined($cached)) { return %{$result}; }
                   5197: 
                   5198:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5199: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5200:     my (%designhash,%legacy);
1.518     albertel 5201:     if (keys(%domconfig) > 0) {
                   5202:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5203:             if (keys(%{$domconfig{'login'}})) {
                   5204:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5205:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5206:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5207:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5208:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5209:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5210:                                         if ($key eq 'loginvia') {
                   5211:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5212:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5213:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5214:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5215:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5216:                                                 } else {
                   5217:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5218:                                                 }
1.948     raeburn  5219:                                             }
1.1075.2.87  raeburn  5220:                                         } elsif ($key eq 'headtag') {
                   5221:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5222:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5223:                                             }
1.946     raeburn  5224:                                         }
1.1075.2.87  raeburn  5225:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5226:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5227:                                         }
1.946     raeburn  5228:                                     }
                   5229:                                 }
                   5230:                             }
                   5231:                         } else {
                   5232:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5233:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5234:                                     $domconfig{'login'}{$key}{$img};
                   5235:                             }
1.699     raeburn  5236:                         }
                   5237:                     } else {
                   5238:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5239:                     }
1.632     raeburn  5240:                 }
                   5241:             } else {
                   5242:                 $legacy{'login'} = 1;
1.518     albertel 5243:             }
1.632     raeburn  5244:         } else {
                   5245:             $legacy{'login'} = 1;
1.518     albertel 5246:         }
                   5247:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5248:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5249:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5250:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5251:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5252:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5253:                         }
1.518     albertel 5254:                     }
                   5255:                 }
1.632     raeburn  5256:             } else {
                   5257:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5258:             }
1.632     raeburn  5259:         } else {
                   5260:             $legacy{'rolecolors'} = 1;
1.518     albertel 5261:         }
1.948     raeburn  5262:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5263:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5264:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5265:             }
                   5266:         }
1.632     raeburn  5267:         if (keys(%legacy) > 0) {
                   5268:             my %legacyhash = &get_legacy_domconf($udom);
                   5269:             foreach my $item (keys(%legacyhash)) {
                   5270:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5271:                     if ($legacy{'login'}) { 
                   5272:                         $designhash{$item} = $legacyhash{$item};
                   5273:                     }
                   5274:                 } else {
                   5275:                     if ($legacy{'rolecolors'}) {
                   5276:                         $designhash{$item} = $legacyhash{$item};
                   5277:                     }
1.518     albertel 5278:                 }
                   5279:             }
                   5280:         }
1.632     raeburn  5281:     } else {
                   5282:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5283:     }
                   5284:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5285: 				  $cachetime);
                   5286:     return %designhash;
                   5287: }
                   5288: 
1.632     raeburn  5289: sub get_legacy_domconf {
                   5290:     my ($udom) = @_;
                   5291:     my %legacyhash;
                   5292:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5293:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5294:     if (-e $designfile) {
1.1075.2.128  raeburn  5295:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5296:             while (my $line = <$fh>) {
                   5297:                 next if ($line =~ /^\#/);
                   5298:                 chomp($line);
                   5299:                 my ($key,$val)=(split(/\=/,$line));
                   5300:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5301:             }
                   5302:             close($fh);
                   5303:         }
                   5304:     }
1.1026    raeburn  5305:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5306:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5307:     }
                   5308:     return %legacyhash;
                   5309: }
                   5310: 
1.63      www      5311: =pod
                   5312: 
1.112     bowersj2 5313: =item * &domainlogo()
1.63      www      5314: 
                   5315: Inputs: $domain (usually will be undef)
                   5316: 
                   5317: Returns: A link to a domain logo, if the domain logo exists.
                   5318: If the domain logo does not exist, a description of the domain.
                   5319: 
                   5320: =cut
1.112     bowersj2 5321: 
1.63      www      5322: ###############################################
                   5323: sub domainlogo {
1.517     raeburn  5324:     my $domain = &determinedomain(shift);
1.518     albertel 5325:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5326:     # See if there is a logo
                   5327:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5328:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5329:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5330: 	    if ($imgsrc =~ m{^/res/}) {
                   5331: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5332: 		&Apache::lonnet::repcopy($local_name);
                   5333: 	    }
                   5334: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5335:         } 
                   5336:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5337:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5338:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5339:     } else {
1.60      matthew  5340:         return '';
1.59      www      5341:     }
                   5342: }
1.63      www      5343: ##############################################
                   5344: 
                   5345: =pod
                   5346: 
1.112     bowersj2 5347: =item * &designparm()
1.63      www      5348: 
                   5349: Inputs: $which parameter; $domain (usually will be undef)
                   5350: 
                   5351: Returns: value of designparamter $which
                   5352: 
                   5353: =cut
1.112     bowersj2 5354: 
1.397     albertel 5355: 
1.400     albertel 5356: ##############################################
1.397     albertel 5357: sub designparm {
                   5358:     my ($which,$domain)=@_;
                   5359:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5360:         return $env{'environment.color.'.$which};
1.96      www      5361:     }
1.63      www      5362:     $domain=&determinedomain($domain);
1.1016    raeburn  5363:     my %domdesign;
                   5364:     unless ($domain eq 'public') {
                   5365:         %domdesign = &get_domainconf($domain);
                   5366:     }
1.520     raeburn  5367:     my $output;
1.517     raeburn  5368:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5369:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5370:     } else {
1.520     raeburn  5371:         $output = $defaultdesign{$which};
                   5372:     }
                   5373:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5374:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5375:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5376:             if ($output =~ m{^/res/}) {
                   5377:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5378:                 &Apache::lonnet::repcopy($local_name);
                   5379:             }
1.520     raeburn  5380:             $output = &lonhttpdurl($output);
                   5381:         }
1.63      www      5382:     }
1.520     raeburn  5383:     return $output;
1.63      www      5384: }
1.59      www      5385: 
1.822     bisitz   5386: ##############################################
                   5387: =pod
                   5388: 
1.832     bisitz   5389: =item * &authorspace()
                   5390: 
1.1028    raeburn  5391: Inputs: $url (usually will be undef).
1.832     bisitz   5392: 
1.1075.2.40  raeburn  5393: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5394:          directory being viewed (or for which action is being taken). 
                   5395:          If $url is provided, and begins /priv/<domain>/<uname>
                   5396:          the path will be that portion of the $context argument.
                   5397:          Otherwise the path will be for the author space of the current
                   5398:          user when the current role is author, or for that of the 
                   5399:          co-author/assistant co-author space when the current role 
                   5400:          is co-author or assistant co-author.
1.832     bisitz   5401: 
                   5402: =cut
                   5403: 
                   5404: sub authorspace {
1.1028    raeburn  5405:     my ($url) = @_;
                   5406:     if ($url ne '') {
                   5407:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5408:            return $1;
                   5409:         }
                   5410:     }
1.832     bisitz   5411:     my $caname = '';
1.1024    www      5412:     my $cadom = '';
1.1028    raeburn  5413:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5414:         ($cadom,$caname) =
1.832     bisitz   5415:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5416:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5417:         $caname = $env{'user.name'};
1.1024    www      5418:         $cadom = $env{'user.domain'};
1.832     bisitz   5419:     }
1.1028    raeburn  5420:     if (($caname ne '') && ($cadom ne '')) {
                   5421:         return "/priv/$cadom/$caname/";
                   5422:     }
                   5423:     return;
1.832     bisitz   5424: }
                   5425: 
                   5426: ##############################################
                   5427: =pod
                   5428: 
1.822     bisitz   5429: =item * &head_subbox()
                   5430: 
                   5431: Inputs: $content (contains HTML code with page functions, etc.)
                   5432: 
                   5433: Returns: HTML div with $content
                   5434:          To be included in page header
                   5435: 
                   5436: =cut
                   5437: 
                   5438: sub head_subbox {
                   5439:     my ($content)=@_;
                   5440:     my $output =
1.993     raeburn  5441:         '<div class="LC_head_subbox">'
1.822     bisitz   5442:        .$content
                   5443:        .'</div>'
                   5444: }
                   5445: 
                   5446: ##############################################
                   5447: =pod
                   5448: 
                   5449: =item * &CSTR_pageheader()
                   5450: 
1.1026    raeburn  5451: Input: (optional) filename from which breadcrumb trail is built.
                   5452:        In most cases no input as needed, as $env{'request.filename'}
                   5453:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5454: 
                   5455: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5456:          To be included on Authoring Space pages
1.822     bisitz   5457: 
                   5458: =cut
                   5459: 
                   5460: sub CSTR_pageheader {
1.1026    raeburn  5461:     my ($trailfile) = @_;
                   5462:     if ($trailfile eq '') {
                   5463:         $trailfile = $env{'request.filename'};
                   5464:     }
                   5465: 
                   5466: # this is for resources; directories have customtitle, and crumbs
                   5467: # and select recent are created in lonpubdir.pm
                   5468: 
                   5469:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5470:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5471:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5472:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5473:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5474: 
                   5475:     my $parentpath = '';
                   5476:     my $lastitem = '';
                   5477:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5478:         $parentpath = $1;
                   5479:         $lastitem = $2;
                   5480:     } else {
                   5481:         $lastitem = $thisdisfn;
                   5482:     }
1.921     bisitz   5483: 
                   5484:     my $output =
1.822     bisitz   5485:          '<div>'
                   5486:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5487:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5488:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5489:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5490:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5491: 
                   5492:     if ($lastitem) {
                   5493:         $output .=
                   5494:              '<span class="LC_filename">'
                   5495:             .$lastitem
                   5496:             .'</span>';
                   5497:     }
                   5498:     $output .=
                   5499:          '<br />'
1.822     bisitz   5500:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5501:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5502:         .'</form>'
                   5503:         .&Apache::lonmenu::constspaceform()
                   5504:         .'</div>';
1.921     bisitz   5505: 
                   5506:     return $output;
1.822     bisitz   5507: }
                   5508: 
1.60      matthew  5509: ###############################################
                   5510: ###############################################
                   5511: 
                   5512: =pod
                   5513: 
1.112     bowersj2 5514: =back
                   5515: 
1.549     albertel 5516: =head1 HTML Helpers
1.112     bowersj2 5517: 
                   5518: =over 4
                   5519: 
                   5520: =item * &bodytag()
1.60      matthew  5521: 
                   5522: Returns a uniform header for LON-CAPA web pages.
                   5523: 
                   5524: Inputs: 
                   5525: 
1.112     bowersj2 5526: =over 4
                   5527: 
                   5528: =item * $title, A title to be displayed on the page.
                   5529: 
                   5530: =item * $function, the current role (can be undef).
                   5531: 
                   5532: =item * $addentries, extra parameters for the <body> tag.
                   5533: 
                   5534: =item * $bodyonly, if defined, only return the <body> tag.
                   5535: 
                   5536: =item * $domain, if defined, force a given domain.
                   5537: 
                   5538: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5539:             text interface only)
1.60      matthew  5540: 
1.814     bisitz   5541: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5542:                      navigational links
1.317     albertel 5543: 
1.338     albertel 5544: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5545: 
1.1075.2.12  raeburn  5546: =item * $no_inline_link, if true and in remote mode, don't show the
                   5547:          'Switch To Inline Menu' link
                   5548: 
1.460     albertel 5549: =item * $args, optional argument valid values are
                   5550:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5551:             use_absolute     -> for external resource or syllabus, this will
                   5552:                                 contain https://<hostname> if server uses
                   5553:                                 https (as per hosts.tab), but request is for http
                   5554:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5555: 
1.1075.2.15  raeburn  5556: =item * $advtoolsref, optional argument, ref to an array containing
                   5557:             inlineremote items to be added in "Functions" menu below
                   5558:             breadcrumbs.
                   5559: 
1.112     bowersj2 5560: =back
                   5561: 
1.60      matthew  5562: Returns: A uniform header for LON-CAPA web pages.  
                   5563: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5564: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5565: other decorations will be returned.
                   5566: 
                   5567: =cut
                   5568: 
1.54      www      5569: sub bodytag {
1.831     bisitz   5570:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5571:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5572: 
1.954     raeburn  5573:     my $public;
                   5574:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5575:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5576:         $public = 1;
                   5577:     }
1.460     albertel 5578:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5579:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5580:     my $hostname = $args->{'hostname'};
1.339     albertel 5581: 
1.183     matthew  5582:     $function = &get_users_function() if (!$function);
1.339     albertel 5583:     my $img =    &designparm($function.'.img',$domain);
                   5584:     my $font =   &designparm($function.'.font',$domain);
                   5585:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5586: 
1.803     bisitz   5587:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5588: 		   'bgcolor' => $pgbg,
1.339     albertel 5589: 		   'text'    => $font,
                   5590:                    'alink'   => &designparm($function.'.alink',$domain),
                   5591: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5592: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5593:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5594: 
1.63      www      5595:  # role and realm
1.1075.2.68  raeburn  5596:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5597:     if ($realm) {
                   5598:         $realm = '/'.$realm;
                   5599:     }
1.378     raeburn  5600:     if ($role  eq 'ca') {
1.479     albertel 5601:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5602:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5603:     } 
1.55      www      5604: # realm
1.258     albertel 5605:     if ($env{'request.course.id'}) {
1.378     raeburn  5606:         if ($env{'request.role'} !~ /^cr/) {
                   5607:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5608:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5609:             if ($env{'request.role.desc'}) {
                   5610:                 $role = $env{'request.role.desc'};
                   5611:             } else {
                   5612:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5613:             }
1.1075.2.115  raeburn  5614:         } else {
                   5615:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5616:         }
1.898     raeburn  5617:         if ($env{'request.course.sec'}) {
                   5618:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5619:         }   
1.359     albertel 5620: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5621:     } else {
                   5622:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5623:     }
1.433     albertel 5624: 
1.359     albertel 5625:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5626: 
1.438     albertel 5627:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5628: 
1.101     www      5629: # construct main body tag
1.359     albertel 5630:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5631: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5632: 
1.1075.2.38  raeburn  5633:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5634: 
                   5635:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5636:         return $bodytag;
1.1075.2.38  raeburn  5637:     }
1.359     albertel 5638: 
1.954     raeburn  5639:     if ($public) {
1.433     albertel 5640: 	undef($role);
                   5641:     }
1.359     albertel 5642:     
1.762     bisitz   5643:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5644:     #
                   5645:     # Extra info if you are the DC
                   5646:     my $dc_info = '';
                   5647:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5648:                         $env{'course.'.$env{'request.course.id'}.
                   5649:                                  '.domain'}.'/'})) {
                   5650:         my $cid = $env{'request.course.id'};
1.917     raeburn  5651:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5652:         $dc_info =~ s/\s+$//;
1.359     albertel 5653:     }
                   5654: 
1.1075.2.108  raeburn  5655:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5656: 
1.1075.2.13  raeburn  5657:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5658: 
1.1075.2.38  raeburn  5659: 
                   5660: 
1.1075.2.21  raeburn  5661:     my $funclist;
                   5662:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5663:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5664:                     Apache::lonmenu::serverform();
                   5665:         my $forbodytag;
                   5666:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5667:                                             $forcereg,$args->{'group'},
                   5668:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5669:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5670:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5671:             $funclist = $forbodytag;
                   5672:         }
                   5673:     } else {
1.903     droeschl 5674: 
                   5675:         #    if ($env{'request.state'} eq 'construct') {
                   5676:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5677:         #    }
                   5678: 
1.1075.2.38  raeburn  5679:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5680:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5681: 
1.1075.2.38  raeburn  5682:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5683: 
1.916     droeschl 5684:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5685:             if ($dc_info) {
                   5686:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5687:             }
1.1075.2.38  raeburn  5688:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5689:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5690:             return $bodytag;
                   5691:         }
1.894     droeschl 5692: 
1.927     raeburn  5693:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5694:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5695:         }
1.916     droeschl 5696: 
1.1075.2.38  raeburn  5697:         $bodytag .= $right;
1.852     droeschl 5698: 
1.917     raeburn  5699:         if ($dc_info) {
                   5700:             $dc_info = &dc_courseid_toggle($dc_info);
                   5701:         }
                   5702:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5703: 
1.1075.2.61  raeburn  5704:         #if directed to not display the secondary menu, don't.
                   5705:         if ($args->{'no_secondary_menu'}) {
                   5706:             return $bodytag;
                   5707:         }
1.903     droeschl 5708:         #don't show menus for public users
1.954     raeburn  5709:         if (!$public){
1.1075.2.52  raeburn  5710:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5711:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5712:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5713:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5714:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5715:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5716:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5717:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5718:                                                             $args->{'group'},
1.1075.2.133  raeburn  5719:                                                             $args->{'hide_buttons',
                   5720:                                                             $hostname});
1.1075.2.15  raeburn  5721:             } else {
1.1075.2.21  raeburn  5722:                 my $forbodytag;
                   5723:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5724:                                                     $forcereg,$args->{'group'},
                   5725:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5726:                                                     $advtoolsref,'',$hostname,
                   5727:                                                     \$forbodytag);
1.1075.2.21  raeburn  5728:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5729:                     $bodytag .= $forbodytag;
                   5730:                 }
1.920     raeburn  5731:             }
1.903     droeschl 5732:         }else{
                   5733:             # this is to seperate menu from content when there's no secondary
                   5734:             # menu. Especially needed for public accessible ressources.
                   5735:             $bodytag .= '<hr style="clear:both" />';
                   5736:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5737:         }
1.903     droeschl 5738: 
1.235     raeburn  5739:         return $bodytag;
1.1075.2.12  raeburn  5740:     }
                   5741: 
                   5742: #
                   5743: # Top frame rendering, Remote is up
                   5744: #
                   5745: 
                   5746:     my $imgsrc = $img;
                   5747:     if ($img =~ /^\/adm/) {
                   5748:         $imgsrc = &lonhttpdurl($img);
                   5749:     }
                   5750:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5751: 
1.1075.2.60  raeburn  5752:     my $help=($no_inline_link?''
                   5753:               :&Apache::loncommon::top_nav_help('Help'));
                   5754: 
1.1075.2.12  raeburn  5755:     # Explicit link to get inline menu
                   5756:     my $menu= ($no_inline_link?''
                   5757:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5758: 
                   5759:     if ($dc_info) {
                   5760:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5761:     }
                   5762: 
1.1075.2.38  raeburn  5763:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5764:     unless ($public) {
                   5765:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5766:                                 undef,'LC_menubuttons_link');
                   5767:     }
                   5768: 
1.1075.2.12  raeburn  5769:     unless ($env{'form.inhibitmenu'}) {
                   5770:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5771:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5772:                        <li>$help</li>
1.1075.2.12  raeburn  5773:                        <li>$menu</li>
                   5774:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5775:     }
1.1075.2.13  raeburn  5776:     if ($env{'request.state'} eq 'construct') {
                   5777:         if (!$public){
                   5778:             if ($env{'request.state'} eq 'construct') {
                   5779:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5780:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5781:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5782:                             &Apache::lonmenu::innerregister($forcereg,
                   5783:                                                             $args->{'bread_crumbs'});
                   5784:             }
                   5785:         }
                   5786:     }
1.1075.2.21  raeburn  5787:     return $bodytag."\n".$funclist;
1.182     matthew  5788: }
                   5789: 
1.917     raeburn  5790: sub dc_courseid_toggle {
                   5791:     my ($dc_info) = @_;
1.980     raeburn  5792:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5793:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5794:            &mt('(More ...)').'</a></span>'.
                   5795:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5796: }
                   5797: 
1.330     albertel 5798: sub make_attr_string {
                   5799:     my ($register,$attr_ref) = @_;
                   5800: 
                   5801:     if ($attr_ref && !ref($attr_ref)) {
                   5802: 	die("addentries Must be a hash ref ".
                   5803: 	    join(':',caller(1))." ".
                   5804: 	    join(':',caller(0))." ");
                   5805:     }
                   5806: 
                   5807:     if ($register) {
1.339     albertel 5808: 	my ($on_load,$on_unload);
                   5809: 	foreach my $key (keys(%{$attr_ref})) {
                   5810: 	    if      (lc($key) eq 'onload') {
                   5811: 		$on_load.=$attr_ref->{$key}.';';
                   5812: 		delete($attr_ref->{$key});
                   5813: 
                   5814: 	    } elsif (lc($key) eq 'onunload') {
                   5815: 		$on_unload.=$attr_ref->{$key}.';';
                   5816: 		delete($attr_ref->{$key});
                   5817: 	    }
                   5818: 	}
1.1075.2.12  raeburn  5819:         if ($env{'environment.remote'} eq 'on') {
                   5820:             $attr_ref->{'onload'}  =
                   5821:                 &Apache::lonmenu::loadevents().  $on_load;
                   5822:             $attr_ref->{'onunload'}=
                   5823:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5824:         } else {  
                   5825: 	    $attr_ref->{'onload'}  = $on_load;
                   5826: 	    $attr_ref->{'onunload'}= $on_unload;
                   5827:         }
1.330     albertel 5828:     }
1.339     albertel 5829: 
1.330     albertel 5830:     my $attr_string;
1.1075.2.56  raeburn  5831:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5832: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5833:     }
                   5834:     return $attr_string;
                   5835: }
                   5836: 
                   5837: 
1.182     matthew  5838: ###############################################
1.251     albertel 5839: ###############################################
                   5840: 
                   5841: =pod
                   5842: 
                   5843: =item * &endbodytag()
                   5844: 
                   5845: Returns a uniform footer for LON-CAPA web pages.
                   5846: 
1.635     raeburn  5847: Inputs: 1 - optional reference to an args hash
                   5848: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5849: a 'Continue' link is not displayed if the page contains an
                   5850: internal redirect in the <head></head> section,
                   5851: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5852: 
                   5853: =cut
                   5854: 
                   5855: sub endbodytag {
1.635     raeburn  5856:     my ($args) = @_;
1.1075.2.6  raeburn  5857:     my $endbodytag;
                   5858:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5859:         $endbodytag='</body>';
                   5860:     }
1.315     albertel 5861:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5862:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5863: 	    $endbodytag=
                   5864: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5865: 	        &mt('Continue').'</a>'.
                   5866: 	        $endbodytag;
                   5867:         }
1.315     albertel 5868:     }
1.251     albertel 5869:     return $endbodytag;
                   5870: }
                   5871: 
1.352     albertel 5872: =pod
                   5873: 
                   5874: =item * &standard_css()
                   5875: 
                   5876: Returns a style sheet
                   5877: 
                   5878: Inputs: (all optional)
                   5879:             domain         -> force to color decorate a page for a specific
                   5880:                                domain
                   5881:             function       -> force usage of a specific rolish color scheme
                   5882:             bgcolor        -> override the default page bgcolor
                   5883: 
                   5884: =cut
                   5885: 
1.343     albertel 5886: sub standard_css {
1.345     albertel 5887:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5888:     $function  = &get_users_function() if (!$function);
                   5889:     my $img    = &designparm($function.'.img',   $domain);
                   5890:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5891:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5892:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5893: #second colour for later usage
1.345     albertel 5894:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5895:     my $pgbg_or_bgcolor =
                   5896: 	         $bgcolor ||
1.352     albertel 5897: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5898:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5899:     my $alink  = &designparm($function.'.alink', $domain);
                   5900:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5901:     my $link   = &designparm($function.'.link',  $domain);
                   5902: 
1.602     albertel 5903:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5904:     my $mono                 = 'monospace';
1.850     bisitz   5905:     my $data_table_head      = $sidebg;
                   5906:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5907:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5908:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5909:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5910:     my $mail_new             = '#FFBB77';
                   5911:     my $mail_new_hover       = '#DD9955';
                   5912:     my $mail_read            = '#BBBB77';
                   5913:     my $mail_read_hover      = '#999944';
                   5914:     my $mail_replied         = '#AAAA88';
                   5915:     my $mail_replied_hover   = '#888855';
                   5916:     my $mail_other           = '#99BBBB';
                   5917:     my $mail_other_hover     = '#669999';
1.391     albertel 5918:     my $table_header         = '#DDDDDD';
1.489     raeburn  5919:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5920:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5921:     my $button_hover         = '#BF2317';
1.392     albertel 5922: 
1.608     albertel 5923:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5924:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5925:                                              : '0 3px 0 4px';
1.448     albertel 5926: 
1.523     albertel 5927: 
1.343     albertel 5928:     return <<END;
1.947     droeschl 5929: 
                   5930: /* needed for iframe to allow 100% height in FF */
                   5931: body, html { 
                   5932:     margin: 0;
                   5933:     padding: 0 0.5%;
                   5934:     height: 99%; /* to avoid scrollbars */
                   5935: }
                   5936: 
1.795     www      5937: body {
1.911     bisitz   5938:   font-family: $sans;
                   5939:   line-height:130%;
                   5940:   font-size:0.83em;
                   5941:   color:$font;
1.795     www      5942: }
                   5943: 
1.959     onken    5944: a:focus,
                   5945: a:focus img {
1.795     www      5946:   color: red;
                   5947: }
1.698     harmsja  5948: 
1.911     bisitz   5949: form, .inline {
                   5950:   display: inline;
1.795     www      5951: }
1.721     harmsja  5952: 
1.795     www      5953: .LC_right {
1.911     bisitz   5954:   text-align:right;
1.795     www      5955: }
                   5956: 
                   5957: .LC_middle {
1.911     bisitz   5958:   vertical-align:middle;
1.795     www      5959: }
1.721     harmsja  5960: 
1.1075.2.38  raeburn  5961: .LC_floatleft {
                   5962:   float: left;
                   5963: }
                   5964: 
                   5965: .LC_floatright {
                   5966:   float: right;
                   5967: }
                   5968: 
1.911     bisitz   5969: .LC_400Box {
                   5970:   width:400px;
                   5971: }
1.721     harmsja  5972: 
1.947     droeschl 5973: .LC_iframecontainer {
                   5974:     width: 98%;
                   5975:     margin: 0;
                   5976:     position: fixed;
                   5977:     top: 8.5em;
                   5978:     bottom: 0;
                   5979: }
                   5980: 
                   5981: .LC_iframecontainer iframe{
                   5982:     border: none;
                   5983:     width: 100%;
                   5984:     height: 100%;
                   5985: }
                   5986: 
1.778     bisitz   5987: .LC_filename {
                   5988:   font-family: $mono;
                   5989:   white-space:pre;
1.921     bisitz   5990:   font-size: 120%;
1.778     bisitz   5991: }
                   5992: 
                   5993: .LC_fileicon {
                   5994:   border: none;
                   5995:   height: 1.3em;
                   5996:   vertical-align: text-bottom;
                   5997:   margin-right: 0.3em;
                   5998:   text-decoration:none;
                   5999: }
                   6000: 
1.1008    www      6001: .LC_setting {
                   6002:   text-decoration:underline;
                   6003: }
                   6004: 
1.350     albertel 6005: .LC_error {
                   6006:   color: red;
                   6007: }
1.795     www      6008: 
1.1075.2.15  raeburn  6009: .LC_warning {
                   6010:   color: darkorange;
                   6011: }
                   6012: 
1.457     albertel 6013: .LC_diff_removed {
1.733     bisitz   6014:   color: red;
1.394     albertel 6015: }
1.532     albertel 6016: 
                   6017: .LC_info,
1.457     albertel 6018: .LC_success,
                   6019: .LC_diff_added {
1.350     albertel 6020:   color: green;
                   6021: }
1.795     www      6022: 
1.802     bisitz   6023: div.LC_confirm_box {
                   6024:   background-color: #FAFAFA;
                   6025:   border: 1px solid $lg_border_color;
                   6026:   margin-right: 0;
                   6027:   padding: 5px;
                   6028: }
                   6029: 
                   6030: div.LC_confirm_box .LC_error img,
                   6031: div.LC_confirm_box .LC_success img {
                   6032:   vertical-align: middle;
                   6033: }
                   6034: 
1.1075.2.108  raeburn  6035: .LC_maxwidth {
                   6036:   max-width: 100%;
                   6037:   height: auto;
                   6038: }
                   6039: 
                   6040: .LC_textsize_mobile {
                   6041:   \@media only screen and (max-device-width: 480px) {
                   6042:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6043:   }
                   6044: }
                   6045: 
1.440     albertel 6046: .LC_icon {
1.771     droeschl 6047:   border: none;
1.790     droeschl 6048:   vertical-align: middle;
1.771     droeschl 6049: }
                   6050: 
1.543     albertel 6051: .LC_docs_spacer {
                   6052:   width: 25px;
                   6053:   height: 1px;
1.771     droeschl 6054:   border: none;
1.543     albertel 6055: }
1.346     albertel 6056: 
1.532     albertel 6057: .LC_internal_info {
1.735     bisitz   6058:   color: #999999;
1.532     albertel 6059: }
                   6060: 
1.794     www      6061: .LC_discussion {
1.1050    www      6062:   background: $data_table_dark;
1.911     bisitz   6063:   border: 1px solid black;
                   6064:   margin: 2px;
1.794     www      6065: }
                   6066: 
                   6067: .LC_disc_action_left {
1.1050    www      6068:   background: $sidebg;
1.911     bisitz   6069:   text-align: left;
1.1050    www      6070:   padding: 4px;
                   6071:   margin: 2px;
1.794     www      6072: }
                   6073: 
                   6074: .LC_disc_action_right {
1.1050    www      6075:   background: $sidebg;
1.911     bisitz   6076:   text-align: right;
1.1050    www      6077:   padding: 4px;
                   6078:   margin: 2px;
1.794     www      6079: }
                   6080: 
                   6081: .LC_disc_new_item {
1.911     bisitz   6082:   background: white;
                   6083:   border: 2px solid red;
1.1050    www      6084:   margin: 4px;
                   6085:   padding: 4px;
1.794     www      6086: }
                   6087: 
                   6088: .LC_disc_old_item {
1.911     bisitz   6089:   background: white;
1.1050    www      6090:   margin: 4px;
                   6091:   padding: 4px;
1.794     www      6092: }
                   6093: 
1.458     albertel 6094: table.LC_pastsubmission {
                   6095:   border: 1px solid black;
                   6096:   margin: 2px;
                   6097: }
                   6098: 
1.924     bisitz   6099: table#LC_menubuttons {
1.345     albertel 6100:   width: 100%;
                   6101:   background: $pgbg;
1.392     albertel 6102:   border: 2px;
1.402     albertel 6103:   border-collapse: separate;
1.803     bisitz   6104:   padding: 0;
1.345     albertel 6105: }
1.392     albertel 6106: 
1.801     tempelho 6107: table#LC_title_bar a {
                   6108:   color: $fontmenu;
                   6109: }
1.836     bisitz   6110: 
1.807     droeschl 6111: table#LC_title_bar {
1.819     tempelho 6112:   clear: both;
1.836     bisitz   6113:   display: none;
1.807     droeschl 6114: }
                   6115: 
1.795     www      6116: table#LC_title_bar,
1.933     droeschl 6117: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6118: table#LC_title_bar.LC_with_remote {
1.359     albertel 6119:   width: 100%;
1.392     albertel 6120:   border-color: $pgbg;
                   6121:   border-style: solid;
                   6122:   border-width: $border;
1.379     albertel 6123:   background: $pgbg;
1.801     tempelho 6124:   color: $fontmenu;
1.392     albertel 6125:   border-collapse: collapse;
1.803     bisitz   6126:   padding: 0;
1.819     tempelho 6127:   margin: 0;
1.359     albertel 6128: }
1.795     www      6129: 
1.933     droeschl 6130: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6131:     margin: 0;
                   6132:     padding: 0;
1.933     droeschl 6133:     position: relative;
                   6134:     list-style: none;
1.913     droeschl 6135: }
1.933     droeschl 6136: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6137:     display: inline;
                   6138: }
1.933     droeschl 6139: 
                   6140: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6141:     padding: 0;
1.933     droeschl 6142:     margin: 0;
                   6143:     float: left;
1.913     droeschl 6144: }
1.933     droeschl 6145: .LC_breadcrumb_tools_tools {
                   6146:     padding: 0;
                   6147:     margin: 0;
1.913     droeschl 6148:     float: right;
                   6149: }
                   6150: 
1.359     albertel 6151: table#LC_title_bar td {
                   6152:   background: $tabbg;
                   6153: }
1.795     www      6154: 
1.911     bisitz   6155: table#LC_menubuttons img {
1.803     bisitz   6156:   border: none;
1.346     albertel 6157: }
1.795     www      6158: 
1.842     droeschl 6159: .LC_breadcrumbs_component {
1.911     bisitz   6160:   float: right;
                   6161:   margin: 0 1em;
1.357     albertel 6162: }
1.842     droeschl 6163: .LC_breadcrumbs_component img {
1.911     bisitz   6164:   vertical-align: middle;
1.777     tempelho 6165: }
1.795     www      6166: 
1.1075.2.108  raeburn  6167: .LC_breadcrumbs_hoverable {
                   6168:   background: $sidebg;
                   6169: }
                   6170: 
1.383     albertel 6171: td.LC_table_cell_checkbox {
                   6172:   text-align: center;
                   6173: }
1.795     www      6174: 
                   6175: .LC_fontsize_small {
1.911     bisitz   6176:   font-size: 70%;
1.705     tempelho 6177: }
                   6178: 
1.844     bisitz   6179: #LC_breadcrumbs {
1.911     bisitz   6180:   clear:both;
                   6181:   background: $sidebg;
                   6182:   border-bottom: 1px solid $lg_border_color;
                   6183:   line-height: 2.5em;
1.933     droeschl 6184:   overflow: hidden;
1.911     bisitz   6185:   margin: 0;
                   6186:   padding: 0;
1.995     raeburn  6187:   text-align: left;
1.819     tempelho 6188: }
1.862     bisitz   6189: 
1.1075.2.16  raeburn  6190: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6191:   clear:both;
                   6192:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6193:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6194:   margin: 0 0 10px 0;
1.966     bisitz   6195:   padding: 3px;
1.995     raeburn  6196:   text-align: left;
1.822     bisitz   6197: }
                   6198: 
1.795     www      6199: .LC_fontsize_medium {
1.911     bisitz   6200:   font-size: 85%;
1.705     tempelho 6201: }
                   6202: 
1.795     www      6203: .LC_fontsize_large {
1.911     bisitz   6204:   font-size: 120%;
1.705     tempelho 6205: }
                   6206: 
1.346     albertel 6207: .LC_menubuttons_inline_text {
                   6208:   color: $font;
1.698     harmsja  6209:   font-size: 90%;
1.701     harmsja  6210:   padding-left:3px;
1.346     albertel 6211: }
                   6212: 
1.934     droeschl 6213: .LC_menubuttons_inline_text img{
                   6214:   vertical-align: middle;
                   6215: }
                   6216: 
1.1051    www      6217: li.LC_menubuttons_inline_text img {
1.951     onken    6218:   cursor:pointer;
1.1002    droeschl 6219:   text-decoration: none;
1.951     onken    6220: }
                   6221: 
1.526     www      6222: .LC_menubuttons_link {
                   6223:   text-decoration: none;
                   6224: }
1.795     www      6225: 
1.522     albertel 6226: .LC_menubuttons_category {
1.521     www      6227:   color: $font;
1.526     www      6228:   background: $pgbg;
1.521     www      6229:   font-size: larger;
                   6230:   font-weight: bold;
                   6231: }
                   6232: 
1.346     albertel 6233: td.LC_menubuttons_text {
1.911     bisitz   6234:   color: $font;
1.346     albertel 6235: }
1.706     harmsja  6236: 
1.346     albertel 6237: .LC_current_location {
                   6238:   background: $tabbg;
                   6239: }
1.795     www      6240: 
1.1075.2.134  raeburn  6241: td.LC_zero_height {
                   6242:   line-height: 0;
                   6243:   cellpadding: 0;
                   6244: }
                   6245: 
1.938     bisitz   6246: table.LC_data_table {
1.347     albertel 6247:   border: 1px solid #000000;
1.402     albertel 6248:   border-collapse: separate;
1.426     albertel 6249:   border-spacing: 1px;
1.610     albertel 6250:   background: $pgbg;
1.347     albertel 6251: }
1.795     www      6252: 
1.422     albertel 6253: .LC_data_table_dense {
                   6254:   font-size: small;
                   6255: }
1.795     www      6256: 
1.507     raeburn  6257: table.LC_nested_outer {
                   6258:   border: 1px solid #000000;
1.589     raeburn  6259:   border-collapse: collapse;
1.803     bisitz   6260:   border-spacing: 0;
1.507     raeburn  6261:   width: 100%;
                   6262: }
1.795     www      6263: 
1.879     raeburn  6264: table.LC_innerpickbox,
1.507     raeburn  6265: table.LC_nested {
1.803     bisitz   6266:   border: none;
1.589     raeburn  6267:   border-collapse: collapse;
1.803     bisitz   6268:   border-spacing: 0;
1.507     raeburn  6269:   width: 100%;
                   6270: }
1.795     www      6271: 
1.911     bisitz   6272: table.LC_data_table tr th,
                   6273: table.LC_calendar tr th,
1.879     raeburn  6274: table.LC_prior_tries tr th,
                   6275: table.LC_innerpickbox tr th {
1.349     albertel 6276:   font-weight: bold;
                   6277:   background-color: $data_table_head;
1.801     tempelho 6278:   color:$fontmenu;
1.701     harmsja  6279:   font-size:90%;
1.347     albertel 6280: }
1.795     www      6281: 
1.879     raeburn  6282: table.LC_innerpickbox tr th,
                   6283: table.LC_innerpickbox tr td {
                   6284:   vertical-align: top;
                   6285: }
                   6286: 
1.711     raeburn  6287: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6288:   background-color: #CCCCCC;
1.711     raeburn  6289:   font-weight: bold;
                   6290:   text-align: left;
                   6291: }
1.795     www      6292: 
1.912     bisitz   6293: table.LC_data_table tr.LC_odd_row > td {
                   6294:   background-color: $data_table_light;
                   6295:   padding: 2px;
                   6296:   vertical-align: top;
                   6297: }
                   6298: 
1.809     bisitz   6299: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6300:   background-color: $data_table_light;
1.912     bisitz   6301:   vertical-align: top;
                   6302: }
                   6303: 
                   6304: table.LC_data_table tr.LC_even_row > td {
                   6305:   background-color: $data_table_dark;
1.425     albertel 6306:   padding: 2px;
1.900     bisitz   6307:   vertical-align: top;
1.347     albertel 6308: }
1.795     www      6309: 
1.809     bisitz   6310: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6311:   background-color: $data_table_dark;
1.900     bisitz   6312:   vertical-align: top;
1.347     albertel 6313: }
1.795     www      6314: 
1.425     albertel 6315: table.LC_data_table tr.LC_data_table_highlight td {
                   6316:   background-color: $data_table_darker;
                   6317: }
1.795     www      6318: 
1.639     raeburn  6319: table.LC_data_table tr td.LC_leftcol_header {
                   6320:   background-color: $data_table_head;
                   6321:   font-weight: bold;
                   6322: }
1.795     www      6323: 
1.451     albertel 6324: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6325: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6326:   font-weight: bold;
                   6327:   font-style: italic;
                   6328:   text-align: center;
                   6329:   padding: 8px;
1.347     albertel 6330: }
1.795     www      6331: 
1.1075.2.30  raeburn  6332: table.LC_data_table tr.LC_empty_row td,
                   6333: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6334:   background-color: $sidebg;
                   6335: }
                   6336: 
                   6337: table.LC_nested tr.LC_empty_row td {
                   6338:   background-color: #FFFFFF;
                   6339: }
                   6340: 
1.890     droeschl 6341: table.LC_caption {
                   6342: }
                   6343: 
1.507     raeburn  6344: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6345:   padding: 4ex
                   6346: }
1.795     www      6347: 
1.507     raeburn  6348: table.LC_nested_outer tr th {
                   6349:   font-weight: bold;
1.801     tempelho 6350:   color:$fontmenu;
1.507     raeburn  6351:   background-color: $data_table_head;
1.701     harmsja  6352:   font-size: small;
1.507     raeburn  6353:   border-bottom: 1px solid #000000;
                   6354: }
1.795     www      6355: 
1.507     raeburn  6356: table.LC_nested_outer tr td.LC_subheader {
                   6357:   background-color: $data_table_head;
                   6358:   font-weight: bold;
                   6359:   font-size: small;
                   6360:   border-bottom: 1px solid #000000;
                   6361:   text-align: right;
1.451     albertel 6362: }
1.795     www      6363: 
1.507     raeburn  6364: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6365:   background-color: #CCCCCC;
1.451     albertel 6366:   font-weight: bold;
                   6367:   font-size: small;
1.507     raeburn  6368:   text-align: center;
                   6369: }
1.795     www      6370: 
1.589     raeburn  6371: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6372: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6373:   text-align: left;
1.451     albertel 6374: }
1.795     www      6375: 
1.507     raeburn  6376: table.LC_nested td {
1.735     bisitz   6377:   background-color: #FFFFFF;
1.451     albertel 6378:   font-size: small;
1.507     raeburn  6379: }
1.795     www      6380: 
1.507     raeburn  6381: table.LC_nested_outer tr th.LC_right_item,
                   6382: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6383: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6384: table.LC_nested tr td.LC_right_item {
1.451     albertel 6385:   text-align: right;
                   6386: }
                   6387: 
1.507     raeburn  6388: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6389:   background-color: #EEEEEE;
1.451     albertel 6390: }
                   6391: 
1.473     raeburn  6392: table.LC_createuser {
                   6393: }
                   6394: 
                   6395: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6396:   font-size: small;
1.473     raeburn  6397: }
                   6398: 
                   6399: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6400:   background-color: #CCCCCC;
1.473     raeburn  6401:   font-weight: bold;
                   6402:   text-align: center;
                   6403: }
                   6404: 
1.349     albertel 6405: table.LC_calendar {
                   6406:   border: 1px solid #000000;
                   6407:   border-collapse: collapse;
1.917     raeburn  6408:   width: 98%;
1.349     albertel 6409: }
1.795     www      6410: 
1.349     albertel 6411: table.LC_calendar_pickdate {
                   6412:   font-size: xx-small;
                   6413: }
1.795     www      6414: 
1.349     albertel 6415: table.LC_calendar tr td {
                   6416:   border: 1px solid #000000;
                   6417:   vertical-align: top;
1.917     raeburn  6418:   width: 14%;
1.349     albertel 6419: }
1.795     www      6420: 
1.349     albertel 6421: table.LC_calendar tr td.LC_calendar_day_empty {
                   6422:   background-color: $data_table_dark;
                   6423: }
1.795     www      6424: 
1.779     bisitz   6425: table.LC_calendar tr td.LC_calendar_day_current {
                   6426:   background-color: $data_table_highlight;
1.777     tempelho 6427: }
1.795     www      6428: 
1.938     bisitz   6429: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6430:   background-color: $mail_new;
                   6431: }
1.795     www      6432: 
1.938     bisitz   6433: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6434:   background-color: $mail_new_hover;
                   6435: }
1.795     www      6436: 
1.938     bisitz   6437: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6438:   background-color: $mail_read;
                   6439: }
1.795     www      6440: 
1.938     bisitz   6441: /*
                   6442: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6443:   background-color: $mail_read_hover;
                   6444: }
1.938     bisitz   6445: */
1.795     www      6446: 
1.938     bisitz   6447: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6448:   background-color: $mail_replied;
                   6449: }
1.795     www      6450: 
1.938     bisitz   6451: /*
                   6452: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6453:   background-color: $mail_replied_hover;
                   6454: }
1.938     bisitz   6455: */
1.795     www      6456: 
1.938     bisitz   6457: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6458:   background-color: $mail_other;
                   6459: }
1.795     www      6460: 
1.938     bisitz   6461: /*
                   6462: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6463:   background-color: $mail_other_hover;
                   6464: }
1.938     bisitz   6465: */
1.494     raeburn  6466: 
1.777     tempelho 6467: table.LC_data_table tr > td.LC_browser_file,
                   6468: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6469:   background: #AAEE77;
1.389     albertel 6470: }
1.795     www      6471: 
1.777     tempelho 6472: table.LC_data_table tr > td.LC_browser_file_locked,
                   6473: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6474:   background: #FFAA99;
1.387     albertel 6475: }
1.795     www      6476: 
1.777     tempelho 6477: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6478:   background: #888888;
1.779     bisitz   6479: }
1.795     www      6480: 
1.777     tempelho 6481: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6482: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6483:   background: #F8F866;
1.777     tempelho 6484: }
1.795     www      6485: 
1.696     bisitz   6486: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6487:   background: #E0E8FF;
1.387     albertel 6488: }
1.696     bisitz   6489: 
1.707     bisitz   6490: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6491:   /* background: #77FF77; */
1.707     bisitz   6492: }
1.795     www      6493: 
1.707     bisitz   6494: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6495:   border-right: 8px solid #FFFF77;
1.707     bisitz   6496: }
1.795     www      6497: 
1.707     bisitz   6498: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6499:   border-right: 8px solid #FFAA77;
1.707     bisitz   6500: }
1.795     www      6501: 
1.707     bisitz   6502: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6503:   border-right: 8px solid #FF7777;
1.707     bisitz   6504: }
1.795     www      6505: 
1.707     bisitz   6506: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6507:   border-right: 8px solid #AAFF77;
1.707     bisitz   6508: }
1.795     www      6509: 
1.707     bisitz   6510: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6511:   border-right: 8px solid #11CC55;
1.707     bisitz   6512: }
                   6513: 
1.388     albertel 6514: span.LC_current_location {
1.701     harmsja  6515:   font-size:larger;
1.388     albertel 6516:   background: $pgbg;
                   6517: }
1.387     albertel 6518: 
1.1029    www      6519: span.LC_current_nav_location {
                   6520:   font-weight:bold;
                   6521:   background: $sidebg;
                   6522: }
                   6523: 
1.395     albertel 6524: span.LC_parm_menu_item {
                   6525:   font-size: larger;
                   6526: }
1.795     www      6527: 
1.395     albertel 6528: span.LC_parm_scope_all {
                   6529:   color: red;
                   6530: }
1.795     www      6531: 
1.395     albertel 6532: span.LC_parm_scope_folder {
                   6533:   color: green;
                   6534: }
1.795     www      6535: 
1.395     albertel 6536: span.LC_parm_scope_resource {
                   6537:   color: orange;
                   6538: }
1.795     www      6539: 
1.395     albertel 6540: span.LC_parm_part {
                   6541:   color: blue;
                   6542: }
1.795     www      6543: 
1.911     bisitz   6544: span.LC_parm_folder,
                   6545: span.LC_parm_symb {
1.395     albertel 6546:   font-size: x-small;
                   6547:   font-family: $mono;
                   6548:   color: #AAAAAA;
                   6549: }
                   6550: 
1.977     bisitz   6551: ul.LC_parm_parmlist li {
                   6552:   display: inline-block;
                   6553:   padding: 0.3em 0.8em;
                   6554:   vertical-align: top;
                   6555:   width: 150px;
                   6556:   border-top:1px solid $lg_border_color;
                   6557: }
                   6558: 
1.795     www      6559: td.LC_parm_overview_level_menu,
                   6560: td.LC_parm_overview_map_menu,
                   6561: td.LC_parm_overview_parm_selectors,
                   6562: td.LC_parm_overview_restrictions  {
1.396     albertel 6563:   border: 1px solid black;
                   6564:   border-collapse: collapse;
                   6565: }
1.795     www      6566: 
1.396     albertel 6567: table.LC_parm_overview_restrictions td {
                   6568:   border-width: 1px 4px 1px 4px;
                   6569:   border-style: solid;
                   6570:   border-color: $pgbg;
                   6571:   text-align: center;
                   6572: }
1.795     www      6573: 
1.396     albertel 6574: table.LC_parm_overview_restrictions th {
                   6575:   background: $tabbg;
                   6576:   border-width: 1px 4px 1px 4px;
                   6577:   border-style: solid;
                   6578:   border-color: $pgbg;
                   6579: }
1.795     www      6580: 
1.398     albertel 6581: table#LC_helpmenu {
1.803     bisitz   6582:   border: none;
1.398     albertel 6583:   height: 55px;
1.803     bisitz   6584:   border-spacing: 0;
1.398     albertel 6585: }
                   6586: 
                   6587: table#LC_helpmenu fieldset legend {
                   6588:   font-size: larger;
                   6589: }
1.795     www      6590: 
1.397     albertel 6591: table#LC_helpmenu_links {
                   6592:   width: 100%;
                   6593:   border: 1px solid black;
                   6594:   background: $pgbg;
1.803     bisitz   6595:   padding: 0;
1.397     albertel 6596:   border-spacing: 1px;
                   6597: }
1.795     www      6598: 
1.397     albertel 6599: table#LC_helpmenu_links tr td {
                   6600:   padding: 1px;
                   6601:   background: $tabbg;
1.399     albertel 6602:   text-align: center;
                   6603:   font-weight: bold;
1.397     albertel 6604: }
1.396     albertel 6605: 
1.795     www      6606: table#LC_helpmenu_links a:link,
                   6607: table#LC_helpmenu_links a:visited,
1.397     albertel 6608: table#LC_helpmenu_links a:active {
                   6609:   text-decoration: none;
                   6610:   color: $font;
                   6611: }
1.795     www      6612: 
1.397     albertel 6613: table#LC_helpmenu_links a:hover {
                   6614:   text-decoration: underline;
                   6615:   color: $vlink;
                   6616: }
1.396     albertel 6617: 
1.417     albertel 6618: .LC_chrt_popup_exists {
                   6619:   border: 1px solid #339933;
                   6620:   margin: -1px;
                   6621: }
1.795     www      6622: 
1.417     albertel 6623: .LC_chrt_popup_up {
                   6624:   border: 1px solid yellow;
                   6625:   margin: -1px;
                   6626: }
1.795     www      6627: 
1.417     albertel 6628: .LC_chrt_popup {
                   6629:   border: 1px solid #8888FF;
                   6630:   background: #CCCCFF;
                   6631: }
1.795     www      6632: 
1.421     albertel 6633: table.LC_pick_box {
                   6634:   border-collapse: separate;
                   6635:   background: white;
                   6636:   border: 1px solid black;
                   6637:   border-spacing: 1px;
                   6638: }
1.795     www      6639: 
1.421     albertel 6640: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6641:   background: $sidebg;
1.421     albertel 6642:   font-weight: bold;
1.900     bisitz   6643:   text-align: left;
1.740     bisitz   6644:   vertical-align: top;
1.421     albertel 6645:   width: 184px;
                   6646:   padding: 8px;
                   6647: }
1.795     www      6648: 
1.579     raeburn  6649: table.LC_pick_box td.LC_pick_box_value {
                   6650:   text-align: left;
                   6651:   padding: 8px;
                   6652: }
1.795     www      6653: 
1.579     raeburn  6654: table.LC_pick_box td.LC_pick_box_select {
                   6655:   text-align: left;
                   6656:   padding: 8px;
                   6657: }
1.795     www      6658: 
1.424     albertel 6659: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6660:   padding: 0;
1.421     albertel 6661:   height: 1px;
                   6662:   background: black;
                   6663: }
1.795     www      6664: 
1.421     albertel 6665: table.LC_pick_box td.LC_pick_box_submit {
                   6666:   text-align: right;
                   6667: }
1.795     www      6668: 
1.579     raeburn  6669: table.LC_pick_box td.LC_evenrow_value {
                   6670:   text-align: left;
                   6671:   padding: 8px;
                   6672:   background-color: $data_table_light;
                   6673: }
1.795     www      6674: 
1.579     raeburn  6675: table.LC_pick_box td.LC_oddrow_value {
                   6676:   text-align: left;
                   6677:   padding: 8px;
                   6678:   background-color: $data_table_light;
                   6679: }
1.795     www      6680: 
1.579     raeburn  6681: span.LC_helpform_receipt_cat {
                   6682:   font-weight: bold;
                   6683: }
1.795     www      6684: 
1.424     albertel 6685: table.LC_group_priv_box {
                   6686:   background: white;
                   6687:   border: 1px solid black;
                   6688:   border-spacing: 1px;
                   6689: }
1.795     www      6690: 
1.424     albertel 6691: table.LC_group_priv_box td.LC_pick_box_title {
                   6692:   background: $tabbg;
                   6693:   font-weight: bold;
                   6694:   text-align: right;
                   6695:   width: 184px;
                   6696: }
1.795     www      6697: 
1.424     albertel 6698: table.LC_group_priv_box td.LC_groups_fixed {
                   6699:   background: $data_table_light;
                   6700:   text-align: center;
                   6701: }
1.795     www      6702: 
1.424     albertel 6703: table.LC_group_priv_box td.LC_groups_optional {
                   6704:   background: $data_table_dark;
                   6705:   text-align: center;
                   6706: }
1.795     www      6707: 
1.424     albertel 6708: table.LC_group_priv_box td.LC_groups_functionality {
                   6709:   background: $data_table_darker;
                   6710:   text-align: center;
                   6711:   font-weight: bold;
                   6712: }
1.795     www      6713: 
1.424     albertel 6714: table.LC_group_priv td {
                   6715:   text-align: left;
1.803     bisitz   6716:   padding: 0;
1.424     albertel 6717: }
                   6718: 
                   6719: .LC_navbuttons {
                   6720:   margin: 2ex 0ex 2ex 0ex;
                   6721: }
1.795     www      6722: 
1.423     albertel 6723: .LC_topic_bar {
                   6724:   font-weight: bold;
                   6725:   background: $tabbg;
1.918     wenzelju 6726:   margin: 1em 0em 1em 2em;
1.805     bisitz   6727:   padding: 3px;
1.918     wenzelju 6728:   font-size: 1.2em;
1.423     albertel 6729: }
1.795     www      6730: 
1.423     albertel 6731: .LC_topic_bar span {
1.918     wenzelju 6732:   left: 0.5em;
                   6733:   position: absolute;
1.423     albertel 6734:   vertical-align: middle;
1.918     wenzelju 6735:   font-size: 1.2em;
1.423     albertel 6736: }
1.795     www      6737: 
1.423     albertel 6738: table.LC_course_group_status {
                   6739:   margin: 20px;
                   6740: }
1.795     www      6741: 
1.423     albertel 6742: table.LC_status_selector td {
                   6743:   vertical-align: top;
                   6744:   text-align: center;
1.424     albertel 6745:   padding: 4px;
                   6746: }
1.795     www      6747: 
1.599     albertel 6748: div.LC_feedback_link {
1.616     albertel 6749:   clear: both;
1.829     kalberla 6750:   background: $sidebg;
1.779     bisitz   6751:   width: 100%;
1.829     kalberla 6752:   padding-bottom: 10px;
                   6753:   border: 1px $tabbg solid;
1.833     kalberla 6754:   height: 22px;
                   6755:   line-height: 22px;
                   6756:   padding-top: 5px;
                   6757: }
                   6758: 
                   6759: div.LC_feedback_link img {
                   6760:   height: 22px;
1.867     kalberla 6761:   vertical-align:middle;
1.829     kalberla 6762: }
                   6763: 
1.911     bisitz   6764: div.LC_feedback_link a {
1.829     kalberla 6765:   text-decoration: none;
1.489     raeburn  6766: }
1.795     www      6767: 
1.867     kalberla 6768: div.LC_comblock {
1.911     bisitz   6769:   display:inline;
1.867     kalberla 6770:   color:$font;
                   6771:   font-size:90%;
                   6772: }
                   6773: 
                   6774: div.LC_feedback_link div.LC_comblock {
                   6775:   padding-left:5px;
                   6776: }
                   6777: 
                   6778: div.LC_feedback_link div.LC_comblock a {
                   6779:   color:$font;
                   6780: }
                   6781: 
1.489     raeburn  6782: span.LC_feedback_link {
1.858     bisitz   6783:   /* background: $feedback_link_bg; */
1.599     albertel 6784:   font-size: larger;
                   6785: }
1.795     www      6786: 
1.599     albertel 6787: span.LC_message_link {
1.858     bisitz   6788:   /* background: $feedback_link_bg; */
1.599     albertel 6789:   font-size: larger;
                   6790:   position: absolute;
                   6791:   right: 1em;
1.489     raeburn  6792: }
1.421     albertel 6793: 
1.515     albertel 6794: table.LC_prior_tries {
1.524     albertel 6795:   border: 1px solid #000000;
                   6796:   border-collapse: separate;
                   6797:   border-spacing: 1px;
1.515     albertel 6798: }
1.523     albertel 6799: 
1.515     albertel 6800: table.LC_prior_tries td {
1.524     albertel 6801:   padding: 2px;
1.515     albertel 6802: }
1.523     albertel 6803: 
                   6804: .LC_answer_correct {
1.795     www      6805:   background: lightgreen;
                   6806:   color: darkgreen;
                   6807:   padding: 6px;
1.523     albertel 6808: }
1.795     www      6809: 
1.523     albertel 6810: .LC_answer_charged_try {
1.797     www      6811:   background: #FFAAAA;
1.795     www      6812:   color: darkred;
                   6813:   padding: 6px;
1.523     albertel 6814: }
1.795     www      6815: 
1.779     bisitz   6816: .LC_answer_not_charged_try,
1.523     albertel 6817: .LC_answer_no_grade,
                   6818: .LC_answer_late {
1.795     www      6819:   background: lightyellow;
1.523     albertel 6820:   color: black;
1.795     www      6821:   padding: 6px;
1.523     albertel 6822: }
1.795     www      6823: 
1.523     albertel 6824: .LC_answer_previous {
1.795     www      6825:   background: lightblue;
                   6826:   color: darkblue;
                   6827:   padding: 6px;
1.523     albertel 6828: }
1.795     www      6829: 
1.779     bisitz   6830: .LC_answer_no_message {
1.777     tempelho 6831:   background: #FFFFFF;
                   6832:   color: black;
1.795     www      6833:   padding: 6px;
1.779     bisitz   6834: }
1.795     www      6835: 
1.1075.2.140  raeburn  6836: .LC_answer_unknown,
                   6837: .LC_answer_warning {
1.779     bisitz   6838:   background: orange;
                   6839:   color: black;
1.795     www      6840:   padding: 6px;
1.777     tempelho 6841: }
1.795     www      6842: 
1.529     albertel 6843: span.LC_prior_numerical,
                   6844: span.LC_prior_string,
                   6845: span.LC_prior_custom,
                   6846: span.LC_prior_reaction,
                   6847: span.LC_prior_math {
1.925     bisitz   6848:   font-family: $mono;
1.523     albertel 6849:   white-space: pre;
                   6850: }
                   6851: 
1.525     albertel 6852: span.LC_prior_string {
1.925     bisitz   6853:   font-family: $mono;
1.525     albertel 6854:   white-space: pre;
                   6855: }
                   6856: 
1.523     albertel 6857: table.LC_prior_option {
                   6858:   width: 100%;
                   6859:   border-collapse: collapse;
                   6860: }
1.795     www      6861: 
1.911     bisitz   6862: table.LC_prior_rank,
1.795     www      6863: table.LC_prior_match {
1.528     albertel 6864:   border-collapse: collapse;
                   6865: }
1.795     www      6866: 
1.528     albertel 6867: table.LC_prior_option tr td,
                   6868: table.LC_prior_rank tr td,
                   6869: table.LC_prior_match tr td {
1.524     albertel 6870:   border: 1px solid #000000;
1.515     albertel 6871: }
                   6872: 
1.855     bisitz   6873: .LC_nobreak {
1.544     albertel 6874:   white-space: nowrap;
1.519     raeburn  6875: }
                   6876: 
1.576     raeburn  6877: span.LC_cusr_emph {
                   6878:   font-style: italic;
                   6879: }
                   6880: 
1.633     raeburn  6881: span.LC_cusr_subheading {
                   6882:   font-weight: normal;
                   6883:   font-size: 85%;
                   6884: }
                   6885: 
1.861     bisitz   6886: div.LC_docs_entry_move {
1.859     bisitz   6887:   border: 1px solid #BBBBBB;
1.545     albertel 6888:   background: #DDDDDD;
1.861     bisitz   6889:   width: 22px;
1.859     bisitz   6890:   padding: 1px;
                   6891:   margin: 0;
1.545     albertel 6892: }
                   6893: 
1.861     bisitz   6894: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6895: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6896:   font-size: x-small;
                   6897: }
1.795     www      6898: 
1.861     bisitz   6899: .LC_docs_entry_parameter {
                   6900:   white-space: nowrap;
                   6901: }
                   6902: 
1.544     albertel 6903: .LC_docs_copy {
1.545     albertel 6904:   color: #000099;
1.544     albertel 6905: }
1.795     www      6906: 
1.544     albertel 6907: .LC_docs_cut {
1.545     albertel 6908:   color: #550044;
1.544     albertel 6909: }
1.795     www      6910: 
1.544     albertel 6911: .LC_docs_rename {
1.545     albertel 6912:   color: #009900;
1.544     albertel 6913: }
1.795     www      6914: 
1.544     albertel 6915: .LC_docs_remove {
1.545     albertel 6916:   color: #990000;
                   6917: }
                   6918: 
1.1075.2.134  raeburn  6919: .LC_domprefs_email,
1.547     albertel 6920: .LC_docs_reinit_warn,
                   6921: .LC_docs_ext_edit {
                   6922:   font-size: x-small;
                   6923: }
                   6924: 
1.545     albertel 6925: table.LC_docs_adddocs td,
                   6926: table.LC_docs_adddocs th {
                   6927:   border: 1px solid #BBBBBB;
                   6928:   padding: 4px;
                   6929:   background: #DDDDDD;
1.543     albertel 6930: }
                   6931: 
1.584     albertel 6932: table.LC_sty_begin {
                   6933:   background: #BBFFBB;
                   6934: }
1.795     www      6935: 
1.584     albertel 6936: table.LC_sty_end {
                   6937:   background: #FFBBBB;
                   6938: }
                   6939: 
1.589     raeburn  6940: table.LC_double_column {
1.803     bisitz   6941:   border-width: 0;
1.589     raeburn  6942:   border-collapse: collapse;
                   6943:   width: 100%;
                   6944:   padding: 2px;
                   6945: }
                   6946: 
                   6947: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6948:   top: 2px;
1.589     raeburn  6949:   left: 2px;
                   6950:   width: 47%;
                   6951:   vertical-align: top;
                   6952: }
                   6953: 
                   6954: table.LC_double_column tr td.LC_right_col {
                   6955:   top: 2px;
1.779     bisitz   6956:   right: 2px;
1.589     raeburn  6957:   width: 47%;
                   6958:   vertical-align: top;
                   6959: }
                   6960: 
1.591     raeburn  6961: div.LC_left_float {
                   6962:   float: left;
                   6963:   padding-right: 5%;
1.597     albertel 6964:   padding-bottom: 4px;
1.591     raeburn  6965: }
                   6966: 
                   6967: div.LC_clear_float_header {
1.597     albertel 6968:   padding-bottom: 2px;
1.591     raeburn  6969: }
                   6970: 
                   6971: div.LC_clear_float_footer {
1.597     albertel 6972:   padding-top: 10px;
1.591     raeburn  6973:   clear: both;
                   6974: }
                   6975: 
1.597     albertel 6976: div.LC_grade_show_user {
1.941     bisitz   6977: /*  border-left: 5px solid $sidebg; */
                   6978:   border-top: 5px solid #000000;
                   6979:   margin: 50px 0 0 0;
1.936     bisitz   6980:   padding: 15px 0 5px 10px;
1.597     albertel 6981: }
1.795     www      6982: 
1.936     bisitz   6983: div.LC_grade_show_user_odd_row {
1.941     bisitz   6984: /*  border-left: 5px solid #000000; */
                   6985: }
                   6986: 
                   6987: div.LC_grade_show_user div.LC_Box {
                   6988:   margin-right: 50px;
1.597     albertel 6989: }
                   6990: 
                   6991: div.LC_grade_submissions,
                   6992: div.LC_grade_message_center,
1.936     bisitz   6993: div.LC_grade_info_links {
1.597     albertel 6994:   margin: 5px;
                   6995:   width: 99%;
                   6996:   background: #FFFFFF;
                   6997: }
1.795     www      6998: 
1.597     albertel 6999: div.LC_grade_submissions_header,
1.936     bisitz   7000: div.LC_grade_message_center_header {
1.705     tempelho 7001:   font-weight: bold;
                   7002:   font-size: large;
1.597     albertel 7003: }
1.795     www      7004: 
1.597     albertel 7005: div.LC_grade_submissions_body,
1.936     bisitz   7006: div.LC_grade_message_center_body {
1.597     albertel 7007:   border: 1px solid black;
                   7008:   width: 99%;
                   7009:   background: #FFFFFF;
                   7010: }
1.795     www      7011: 
1.613     albertel 7012: table.LC_scantron_action {
                   7013:   width: 100%;
                   7014: }
1.795     www      7015: 
1.613     albertel 7016: table.LC_scantron_action tr th {
1.698     harmsja  7017:   font-weight:bold;
                   7018:   font-style:normal;
1.613     albertel 7019: }
1.795     www      7020: 
1.779     bisitz   7021: .LC_edit_problem_header,
1.614     albertel 7022: div.LC_edit_problem_footer {
1.705     tempelho 7023:   font-weight: normal;
                   7024:   font-size:  medium;
1.602     albertel 7025:   margin: 2px;
1.1060    bisitz   7026:   background-color: $sidebg;
1.600     albertel 7027: }
1.795     www      7028: 
1.600     albertel 7029: div.LC_edit_problem_header,
1.602     albertel 7030: div.LC_edit_problem_header div,
1.614     albertel 7031: div.LC_edit_problem_footer,
                   7032: div.LC_edit_problem_footer div,
1.602     albertel 7033: div.LC_edit_problem_editxml_header,
                   7034: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7035:   z-index: 100;
1.600     albertel 7036: }
1.795     www      7037: 
1.600     albertel 7038: div.LC_edit_problem_header_title {
1.705     tempelho 7039:   font-weight: bold;
                   7040:   font-size: larger;
1.602     albertel 7041:   background: $tabbg;
                   7042:   padding: 3px;
1.1060    bisitz   7043:   margin: 0 0 5px 0;
1.602     albertel 7044: }
1.795     www      7045: 
1.602     albertel 7046: table.LC_edit_problem_header_title {
                   7047:   width: 100%;
1.600     albertel 7048:   background: $tabbg;
1.602     albertel 7049: }
                   7050: 
1.1075.2.112  raeburn  7051: div.LC_edit_actionbar {
                   7052:     background-color: $sidebg;
                   7053:     margin: 0;
                   7054:     padding: 0;
                   7055:     line-height: 200%;
1.602     albertel 7056: }
1.795     www      7057: 
1.1075.2.112  raeburn  7058: div.LC_edit_actionbar div{
                   7059:     padding: 0;
                   7060:     margin: 0;
                   7061:     display: inline-block;
1.600     albertel 7062: }
1.795     www      7063: 
1.1075.2.34  raeburn  7064: .LC_edit_opt {
                   7065:   padding-left: 1em;
                   7066:   white-space: nowrap;
                   7067: }
                   7068: 
1.1075.2.57  raeburn  7069: .LC_edit_problem_latexhelper{
                   7070:     text-align: right;
                   7071: }
                   7072: 
                   7073: #LC_edit_problem_colorful div{
                   7074:     margin-left: 40px;
                   7075: }
                   7076: 
1.1075.2.112  raeburn  7077: #LC_edit_problem_codemirror div{
                   7078:     margin-left: 0px;
                   7079: }
                   7080: 
1.911     bisitz   7081: img.stift {
1.803     bisitz   7082:   border-width: 0;
                   7083:   vertical-align: middle;
1.677     riegler  7084: }
1.680     riegler  7085: 
1.923     bisitz   7086: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7087:   vertical-align: top;
1.777     tempelho 7088: }
1.795     www      7089: 
1.716     raeburn  7090: div.LC_createcourse {
1.911     bisitz   7091:   margin: 10px 10px 10px 10px;
1.716     raeburn  7092: }
                   7093: 
1.917     raeburn  7094: .LC_dccid {
1.1075.2.38  raeburn  7095:   float: right;
1.917     raeburn  7096:   margin: 0.2em 0 0 0;
                   7097:   padding: 0;
                   7098:   font-size: 90%;
                   7099:   display:none;
                   7100: }
                   7101: 
1.897     wenzelju 7102: ol.LC_primary_menu a:hover,
1.721     harmsja  7103: ol#LC_MenuBreadcrumbs a:hover,
                   7104: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7105: ul#LC_secondary_menu a:hover,
1.721     harmsja  7106: .LC_FormSectionClearButton input:hover
1.795     www      7107: ul.LC_TabContent   li:hover a {
1.952     onken    7108:   color:$button_hover;
1.911     bisitz   7109:   text-decoration:none;
1.693     droeschl 7110: }
                   7111: 
1.779     bisitz   7112: h1 {
1.911     bisitz   7113:   padding: 0;
                   7114:   line-height:130%;
1.693     droeschl 7115: }
1.698     harmsja  7116: 
1.911     bisitz   7117: h2,
                   7118: h3,
                   7119: h4,
                   7120: h5,
                   7121: h6 {
                   7122:   margin: 5px 0 5px 0;
                   7123:   padding: 0;
                   7124:   line-height:130%;
1.693     droeschl 7125: }
1.795     www      7126: 
                   7127: .LC_hcell {
1.911     bisitz   7128:   padding:3px 15px 3px 15px;
                   7129:   margin: 0;
                   7130:   background-color:$tabbg;
                   7131:   color:$fontmenu;
                   7132:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7133: }
1.795     www      7134: 
1.840     bisitz   7135: .LC_Box > .LC_hcell {
1.911     bisitz   7136:   margin: 0 -10px 10px -10px;
1.835     bisitz   7137: }
                   7138: 
1.721     harmsja  7139: .LC_noBorder {
1.911     bisitz   7140:   border: 0;
1.698     harmsja  7141: }
1.693     droeschl 7142: 
1.721     harmsja  7143: .LC_FormSectionClearButton input {
1.911     bisitz   7144:   background-color:transparent;
                   7145:   border: none;
                   7146:   cursor:pointer;
                   7147:   text-decoration:underline;
1.693     droeschl 7148: }
1.763     bisitz   7149: 
                   7150: .LC_help_open_topic {
1.911     bisitz   7151:   color: #FFFFFF;
                   7152:   background-color: #EEEEFF;
                   7153:   margin: 1px;
                   7154:   padding: 4px;
                   7155:   border: 1px solid #000033;
                   7156:   white-space: nowrap;
                   7157:   /* vertical-align: middle; */
1.759     neumanie 7158: }
1.693     droeschl 7159: 
1.911     bisitz   7160: dl,
                   7161: ul,
                   7162: div,
                   7163: fieldset {
                   7164:   margin: 10px 10px 10px 0;
                   7165:   /* overflow: hidden; */
1.693     droeschl 7166: }
1.795     www      7167: 
1.1075.2.90  raeburn  7168: article.geogebraweb div {
                   7169:     margin: 0;
                   7170: }
                   7171: 
1.838     bisitz   7172: fieldset > legend {
1.911     bisitz   7173:   font-weight: bold;
                   7174:   padding: 0 5px 0 5px;
1.838     bisitz   7175: }
                   7176: 
1.813     bisitz   7177: #LC_nav_bar {
1.911     bisitz   7178:   float: left;
1.995     raeburn  7179:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7180:   margin: 0 0 2px 0;
1.807     droeschl 7181: }
                   7182: 
1.916     droeschl 7183: #LC_realm {
                   7184:   margin: 0.2em 0 0 0;
                   7185:   padding: 0;
                   7186:   font-weight: bold;
                   7187:   text-align: center;
1.995     raeburn  7188:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7189: }
                   7190: 
1.911     bisitz   7191: #LC_nav_bar em {
                   7192:   font-weight: bold;
                   7193:   font-style: normal;
1.807     droeschl 7194: }
                   7195: 
1.897     wenzelju 7196: ol.LC_primary_menu {
1.934     droeschl 7197:   margin: 0;
1.1075.2.2  raeburn  7198:   padding: 0;
1.807     droeschl 7199: }
                   7200: 
1.852     droeschl 7201: ol#LC_PathBreadcrumbs {
1.911     bisitz   7202:   margin: 0;
1.693     droeschl 7203: }
                   7204: 
1.897     wenzelju 7205: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7206:   color: RGB(80, 80, 80);
                   7207:   vertical-align: middle;
                   7208:   text-align: left;
                   7209:   list-style: none;
1.1075.2.112  raeburn  7210:   position: relative;
1.1075.2.2  raeburn  7211:   float: left;
1.1075.2.112  raeburn  7212:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7213:   line-height: 1.5em;
1.1075.2.2  raeburn  7214: }
                   7215: 
1.1075.2.113  raeburn  7216: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7217: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7218:   display: block;
                   7219:   margin: 0;
                   7220:   padding: 0 5px 0 10px;
                   7221:   text-decoration: none;
                   7222: }
                   7223: 
1.1075.2.112  raeburn  7224: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7225:   display: inline-block;
                   7226:   width: 95%;
                   7227:   text-align: left;
                   7228: }
                   7229: 
                   7230: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7231:   display: inline-block;
                   7232:   width: 5%;
                   7233:   float: right;
                   7234:   text-align: right;
                   7235:   font-size: 70%;
                   7236: }
                   7237: 
                   7238: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7239:   display: none;
1.1075.2.112  raeburn  7240:   width: 15em;
1.1075.2.2  raeburn  7241:   background-color: $data_table_light;
1.1075.2.112  raeburn  7242:   position: absolute;
                   7243:   top: 100%;
                   7244: }
                   7245: 
                   7246: ol.LC_primary_menu ul ul {
                   7247:   left: 100%;
                   7248:   top: 0;
1.1075.2.2  raeburn  7249: }
                   7250: 
1.1075.2.112  raeburn  7251: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7252:   display: block;
                   7253:   position: absolute;
                   7254:   margin: 0;
                   7255:   padding: 0;
1.1075.2.5  raeburn  7256:   z-index: 2;
1.1075.2.2  raeburn  7257: }
                   7258: 
                   7259: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7260: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7261:   font-size: 90%;
1.911     bisitz   7262:   vertical-align: top;
1.1075.2.2  raeburn  7263:   float: none;
1.1075.2.5  raeburn  7264:   border-left: 1px solid black;
                   7265:   border-right: 1px solid black;
1.1075.2.112  raeburn  7266: /* A dark bottom border to visualize different menu options;
                   7267: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7268:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7269: }
                   7270: 
1.1075.2.112  raeburn  7271: ol.LC_primary_menu li li p:hover {
                   7272:   color:$button_hover;
                   7273:   text-decoration:none;
                   7274:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7275: }
                   7276: 
                   7277: ol.LC_primary_menu li li a:hover {
                   7278:    color:$button_hover;
                   7279:    background-color:$data_table_dark;
1.693     droeschl 7280: }
                   7281: 
1.1075.2.112  raeburn  7282: /* Font-size equal to the size of the predecessors*/
                   7283: ol.LC_primary_menu li:hover li li {
                   7284:   font-size: 100%;
                   7285: }
                   7286: 
1.897     wenzelju 7287: ol.LC_primary_menu li img {
1.911     bisitz   7288:   vertical-align: bottom;
1.934     droeschl 7289:   height: 1.1em;
1.1075.2.3  raeburn  7290:   margin: 0.2em 0 0 0;
1.693     droeschl 7291: }
                   7292: 
1.897     wenzelju 7293: ol.LC_primary_menu a {
1.911     bisitz   7294:   color: RGB(80, 80, 80);
                   7295:   text-decoration: none;
1.693     droeschl 7296: }
1.795     www      7297: 
1.949     droeschl 7298: ol.LC_primary_menu a.LC_new_message {
                   7299:   font-weight:bold;
                   7300:   color: darkred;
                   7301: }
                   7302: 
1.975     raeburn  7303: ol.LC_docs_parameters {
                   7304:   margin-left: 0;
                   7305:   padding: 0;
                   7306:   list-style: none;
                   7307: }
                   7308: 
                   7309: ol.LC_docs_parameters li {
                   7310:   margin: 0;
                   7311:   padding-right: 20px;
                   7312:   display: inline;
                   7313: }
                   7314: 
1.976     raeburn  7315: ol.LC_docs_parameters li:before {
                   7316:   content: "\\002022 \\0020";
                   7317: }
                   7318: 
                   7319: li.LC_docs_parameters_title {
                   7320:   font-weight: bold;
                   7321: }
                   7322: 
                   7323: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7324:   content: "";
                   7325: }
                   7326: 
1.897     wenzelju 7327: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7328:   clear: right;
1.911     bisitz   7329:   color: $fontmenu;
                   7330:   background: $tabbg;
                   7331:   list-style: none;
                   7332:   padding: 0;
                   7333:   margin: 0;
                   7334:   width: 100%;
1.995     raeburn  7335:   text-align: left;
1.1075.2.4  raeburn  7336:   float: left;
1.808     droeschl 7337: }
                   7338: 
1.897     wenzelju 7339: ul#LC_secondary_menu li {
1.911     bisitz   7340:   font-weight: bold;
                   7341:   line-height: 1.8em;
                   7342:   border-right: 1px solid black;
1.1075.2.4  raeburn  7343:   float: left;
                   7344: }
                   7345: 
                   7346: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7347:   background-color: $data_table_light;
                   7348: }
                   7349: 
                   7350: ul#LC_secondary_menu li a {
                   7351:   padding: 0 0.8em;
                   7352: }
                   7353: 
                   7354: ul#LC_secondary_menu li ul {
                   7355:   display: none;
                   7356: }
                   7357: 
                   7358: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7359:   display: block;
                   7360:   position: absolute;
                   7361:   margin: 0;
                   7362:   padding: 0;
                   7363:   list-style:none;
                   7364:   float: none;
                   7365:   background-color: $data_table_light;
1.1075.2.5  raeburn  7366:   z-index: 2;
1.1075.2.10  raeburn  7367:   margin-left: -1px;
1.1075.2.4  raeburn  7368: }
                   7369: 
                   7370: ul#LC_secondary_menu li ul li {
                   7371:   font-size: 90%;
                   7372:   vertical-align: top;
                   7373:   border-left: 1px solid black;
                   7374:   border-right: 1px solid black;
1.1075.2.33  raeburn  7375:   background-color: $data_table_light;
1.1075.2.4  raeburn  7376:   list-style:none;
                   7377:   float: none;
                   7378: }
                   7379: 
                   7380: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7381:   background-color: $data_table_dark;
1.807     droeschl 7382: }
                   7383: 
1.847     tempelho 7384: ul.LC_TabContent {
1.911     bisitz   7385:   display:block;
                   7386:   background: $sidebg;
                   7387:   border-bottom: solid 1px $lg_border_color;
                   7388:   list-style:none;
1.1020    raeburn  7389:   margin: -1px -10px 0 -10px;
1.911     bisitz   7390:   padding: 0;
1.693     droeschl 7391: }
                   7392: 
1.795     www      7393: ul.LC_TabContent li,
                   7394: ul.LC_TabContentBigger li {
1.911     bisitz   7395:   float:left;
1.741     harmsja  7396: }
1.795     www      7397: 
1.897     wenzelju 7398: ul#LC_secondary_menu li a {
1.911     bisitz   7399:   color: $fontmenu;
                   7400:   text-decoration: none;
1.693     droeschl 7401: }
1.795     www      7402: 
1.721     harmsja  7403: ul.LC_TabContent {
1.952     onken    7404:   min-height:20px;
1.721     harmsja  7405: }
1.795     www      7406: 
                   7407: ul.LC_TabContent li {
1.911     bisitz   7408:   vertical-align:middle;
1.959     onken    7409:   padding: 0 16px 0 10px;
1.911     bisitz   7410:   background-color:$tabbg;
                   7411:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7412:   border-left: solid 1px $font;
1.721     harmsja  7413: }
1.795     www      7414: 
1.847     tempelho 7415: ul.LC_TabContent .right {
1.911     bisitz   7416:   float:right;
1.847     tempelho 7417: }
                   7418: 
1.911     bisitz   7419: ul.LC_TabContent li a,
                   7420: ul.LC_TabContent li {
                   7421:   color:rgb(47,47,47);
                   7422:   text-decoration:none;
                   7423:   font-size:95%;
                   7424:   font-weight:bold;
1.952     onken    7425:   min-height:20px;
                   7426: }
                   7427: 
1.959     onken    7428: ul.LC_TabContent li a:hover,
                   7429: ul.LC_TabContent li a:focus {
1.952     onken    7430:   color: $button_hover;
1.959     onken    7431:   background:none;
                   7432:   outline:none;
1.952     onken    7433: }
                   7434: 
                   7435: ul.LC_TabContent li:hover {
                   7436:   color: $button_hover;
                   7437:   cursor:pointer;
1.721     harmsja  7438: }
1.795     www      7439: 
1.911     bisitz   7440: ul.LC_TabContent li.active {
1.952     onken    7441:   color: $font;
1.911     bisitz   7442:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7443:   border-bottom:solid 1px #FFFFFF;
                   7444:   cursor: default;
1.744     ehlerst  7445: }
1.795     www      7446: 
1.959     onken    7447: ul.LC_TabContent li.active a {
                   7448:   color:$font;
                   7449:   background:#FFFFFF;
                   7450:   outline: none;
                   7451: }
1.1047    raeburn  7452: 
                   7453: ul.LC_TabContent li.goback {
                   7454:   float: left;
                   7455:   border-left: none;
                   7456: }
                   7457: 
1.870     tempelho 7458: #maincoursedoc {
1.911     bisitz   7459:   clear:both;
1.870     tempelho 7460: }
                   7461: 
                   7462: ul.LC_TabContentBigger {
1.911     bisitz   7463:   display:block;
                   7464:   list-style:none;
                   7465:   padding: 0;
1.870     tempelho 7466: }
                   7467: 
1.795     www      7468: ul.LC_TabContentBigger li {
1.911     bisitz   7469:   vertical-align:bottom;
                   7470:   height: 30px;
                   7471:   font-size:110%;
                   7472:   font-weight:bold;
                   7473:   color: #737373;
1.841     tempelho 7474: }
                   7475: 
1.957     onken    7476: ul.LC_TabContentBigger li.active {
                   7477:   position: relative;
                   7478:   top: 1px;
                   7479: }
                   7480: 
1.870     tempelho 7481: ul.LC_TabContentBigger li a {
1.911     bisitz   7482:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7483:   height: 30px;
                   7484:   line-height: 30px;
                   7485:   text-align: center;
                   7486:   display: block;
                   7487:   text-decoration: none;
1.958     onken    7488:   outline: none;  
1.741     harmsja  7489: }
1.795     www      7490: 
1.870     tempelho 7491: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7492:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7493:   color:$font;
1.744     ehlerst  7494: }
1.795     www      7495: 
1.870     tempelho 7496: ul.LC_TabContentBigger li b {
1.911     bisitz   7497:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7498:   display: block;
                   7499:   float: left;
                   7500:   padding: 0 30px;
1.957     onken    7501:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7502: }
                   7503: 
1.956     onken    7504: ul.LC_TabContentBigger li:hover b {
                   7505:   color:$button_hover;
                   7506: }
                   7507: 
1.870     tempelho 7508: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7509:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7510:   color:$font;
1.957     onken    7511:   border: 0;
1.741     harmsja  7512: }
1.693     droeschl 7513: 
1.870     tempelho 7514: 
1.862     bisitz   7515: ul.LC_CourseBreadcrumbs {
                   7516:   background: $sidebg;
1.1020    raeburn  7517:   height: 2em;
1.862     bisitz   7518:   padding-left: 10px;
1.1020    raeburn  7519:   margin: 0;
1.862     bisitz   7520:   list-style-position: inside;
                   7521: }
                   7522: 
1.911     bisitz   7523: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7524: ol#LC_PathBreadcrumbs {
1.911     bisitz   7525:   padding-left: 10px;
                   7526:   margin: 0;
1.933     droeschl 7527:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7528: }
                   7529: 
1.911     bisitz   7530: ol#LC_MenuBreadcrumbs li,
                   7531: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7532: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7533:   display: inline;
1.933     droeschl 7534:   white-space: normal;  
1.693     droeschl 7535: }
                   7536: 
1.823     bisitz   7537: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7538: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7539:   text-decoration: none;
                   7540:   font-size:90%;
1.693     droeschl 7541: }
1.795     www      7542: 
1.969     droeschl 7543: ol#LC_MenuBreadcrumbs h1 {
                   7544:   display: inline;
                   7545:   font-size: 90%;
                   7546:   line-height: 2.5em;
                   7547:   margin: 0;
                   7548:   padding: 0;
                   7549: }
                   7550: 
1.795     www      7551: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7552:   text-decoration:none;
                   7553:   font-size:100%;
                   7554:   font-weight:bold;
1.693     droeschl 7555: }
1.795     www      7556: 
1.840     bisitz   7557: .LC_Box {
1.911     bisitz   7558:   border: solid 1px $lg_border_color;
                   7559:   padding: 0 10px 10px 10px;
1.746     neumanie 7560: }
1.795     www      7561: 
1.1020    raeburn  7562: .LC_DocsBox {
                   7563:   border: solid 1px $lg_border_color;
                   7564:   padding: 0 0 10px 10px;
                   7565: }
                   7566: 
1.795     www      7567: .LC_AboutMe_Image {
1.911     bisitz   7568:   float:left;
                   7569:   margin-right:10px;
1.747     neumanie 7570: }
1.795     www      7571: 
                   7572: .LC_Clear_AboutMe_Image {
1.911     bisitz   7573:   clear:left;
1.747     neumanie 7574: }
1.795     www      7575: 
1.721     harmsja  7576: dl.LC_ListStyleClean dt {
1.911     bisitz   7577:   padding-right: 5px;
                   7578:   display: table-header-group;
1.693     droeschl 7579: }
                   7580: 
1.721     harmsja  7581: dl.LC_ListStyleClean dd {
1.911     bisitz   7582:   display: table-row;
1.693     droeschl 7583: }
                   7584: 
1.721     harmsja  7585: .LC_ListStyleClean,
                   7586: .LC_ListStyleSimple,
                   7587: .LC_ListStyleNormal,
1.795     www      7588: .LC_ListStyleSpecial {
1.911     bisitz   7589:   /* display:block; */
                   7590:   list-style-position: inside;
                   7591:   list-style-type: none;
                   7592:   overflow: hidden;
                   7593:   padding: 0;
1.693     droeschl 7594: }
                   7595: 
1.721     harmsja  7596: .LC_ListStyleSimple li,
                   7597: .LC_ListStyleSimple dd,
                   7598: .LC_ListStyleNormal li,
                   7599: .LC_ListStyleNormal dd,
                   7600: .LC_ListStyleSpecial li,
1.795     www      7601: .LC_ListStyleSpecial dd {
1.911     bisitz   7602:   margin: 0;
                   7603:   padding: 5px 5px 5px 10px;
                   7604:   clear: both;
1.693     droeschl 7605: }
                   7606: 
1.721     harmsja  7607: .LC_ListStyleClean li,
                   7608: .LC_ListStyleClean dd {
1.911     bisitz   7609:   padding-top: 0;
                   7610:   padding-bottom: 0;
1.693     droeschl 7611: }
                   7612: 
1.721     harmsja  7613: .LC_ListStyleSimple dd,
1.795     www      7614: .LC_ListStyleSimple li {
1.911     bisitz   7615:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7616: }
                   7617: 
1.721     harmsja  7618: .LC_ListStyleSpecial li,
                   7619: .LC_ListStyleSpecial dd {
1.911     bisitz   7620:   list-style-type: none;
                   7621:   background-color: RGB(220, 220, 220);
                   7622:   margin-bottom: 4px;
1.693     droeschl 7623: }
                   7624: 
1.721     harmsja  7625: table.LC_SimpleTable {
1.911     bisitz   7626:   margin:5px;
                   7627:   border:solid 1px $lg_border_color;
1.795     www      7628: }
1.693     droeschl 7629: 
1.721     harmsja  7630: table.LC_SimpleTable tr {
1.911     bisitz   7631:   padding: 0;
                   7632:   border:solid 1px $lg_border_color;
1.693     droeschl 7633: }
1.795     www      7634: 
                   7635: table.LC_SimpleTable thead {
1.911     bisitz   7636:   background:rgb(220,220,220);
1.693     droeschl 7637: }
                   7638: 
1.721     harmsja  7639: div.LC_columnSection {
1.911     bisitz   7640:   display: block;
                   7641:   clear: both;
                   7642:   overflow: hidden;
                   7643:   margin: 0;
1.693     droeschl 7644: }
                   7645: 
1.721     harmsja  7646: div.LC_columnSection>* {
1.911     bisitz   7647:   float: left;
                   7648:   margin: 10px 20px 10px 0;
                   7649:   overflow:hidden;
1.693     droeschl 7650: }
1.721     harmsja  7651: 
1.795     www      7652: table em {
1.911     bisitz   7653:   font-weight: bold;
                   7654:   font-style: normal;
1.748     schulted 7655: }
1.795     www      7656: 
1.779     bisitz   7657: table.LC_tableBrowseRes,
1.795     www      7658: table.LC_tableOfContent {
1.911     bisitz   7659:   border:none;
                   7660:   border-spacing: 1px;
                   7661:   padding: 3px;
                   7662:   background-color: #FFFFFF;
                   7663:   font-size: 90%;
1.753     droeschl 7664: }
1.789     droeschl 7665: 
1.911     bisitz   7666: table.LC_tableOfContent {
                   7667:   border-collapse: collapse;
1.789     droeschl 7668: }
                   7669: 
1.771     droeschl 7670: table.LC_tableBrowseRes a,
1.768     schulted 7671: table.LC_tableOfContent a {
1.911     bisitz   7672:   background-color: transparent;
                   7673:   text-decoration: none;
1.753     droeschl 7674: }
                   7675: 
1.795     www      7676: table.LC_tableOfContent img {
1.911     bisitz   7677:   border: none;
                   7678:   height: 1.3em;
                   7679:   vertical-align: text-bottom;
                   7680:   margin-right: 0.3em;
1.753     droeschl 7681: }
1.757     schulted 7682: 
1.795     www      7683: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7684:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7685: }
                   7686: 
1.795     www      7687: a#LC_content_toolbar_everything {
1.911     bisitz   7688:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7689: }
                   7690: 
1.795     www      7691: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7692:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7693: }
                   7694: 
1.795     www      7695: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7696:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7697: }
                   7698: 
1.795     www      7699: a#LC_content_toolbar_changefolder {
1.911     bisitz   7700:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7701: }
                   7702: 
1.795     www      7703: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7704:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7705: }
                   7706: 
1.1043    raeburn  7707: a#LC_content_toolbar_edittoplevel {
                   7708:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7709: }
                   7710: 
1.795     www      7711: ul#LC_toolbar li a:hover {
1.911     bisitz   7712:   background-position: bottom center;
1.757     schulted 7713: }
                   7714: 
1.795     www      7715: ul#LC_toolbar {
1.911     bisitz   7716:   padding: 0;
                   7717:   margin: 2px;
                   7718:   list-style:none;
                   7719:   position:relative;
                   7720:   background-color:white;
1.1075.2.9  raeburn  7721:   overflow: auto;
1.757     schulted 7722: }
                   7723: 
1.795     www      7724: ul#LC_toolbar li {
1.911     bisitz   7725:   border:1px solid white;
                   7726:   padding: 0;
                   7727:   margin: 0;
                   7728:   float: left;
                   7729:   display:inline;
                   7730:   vertical-align:middle;
1.1075.2.9  raeburn  7731:   white-space: nowrap;
1.911     bisitz   7732: }
1.757     schulted 7733: 
1.783     amueller 7734: 
1.795     www      7735: a.LC_toolbarItem {
1.911     bisitz   7736:   display:block;
                   7737:   padding: 0;
                   7738:   margin: 0;
                   7739:   height: 32px;
                   7740:   width: 32px;
                   7741:   color:white;
                   7742:   border: none;
                   7743:   background-repeat:no-repeat;
                   7744:   background-color:transparent;
1.757     schulted 7745: }
                   7746: 
1.915     droeschl 7747: ul.LC_funclist {
                   7748:     margin: 0;
                   7749:     padding: 0.5em 1em 0.5em 0;
                   7750: }
                   7751: 
1.933     droeschl 7752: ul.LC_funclist > li:first-child {
                   7753:     font-weight:bold; 
                   7754:     margin-left:0.8em;
                   7755: }
                   7756: 
1.915     droeschl 7757: ul.LC_funclist + ul.LC_funclist {
                   7758:     /* 
                   7759:        left border as a seperator if we have more than
                   7760:        one list 
                   7761:     */
                   7762:     border-left: 1px solid $sidebg;
                   7763:     /* 
                   7764:        this hides the left border behind the border of the 
                   7765:        outer box if element is wrapped to the next 'line' 
                   7766:     */
                   7767:     margin-left: -1px;
                   7768: }
                   7769: 
1.843     bisitz   7770: ul.LC_funclist li {
1.915     droeschl 7771:   display: inline;
1.782     bisitz   7772:   white-space: nowrap;
1.915     droeschl 7773:   margin: 0 0 0 25px;
                   7774:   line-height: 150%;
1.782     bisitz   7775: }
                   7776: 
1.974     wenzelju 7777: .LC_hidden {
                   7778:   display: none;
                   7779: }
                   7780: 
1.1030    www      7781: .LCmodal-overlay {
                   7782: 		position:fixed;
                   7783: 		top:0;
                   7784: 		right:0;
                   7785: 		bottom:0;
                   7786: 		left:0;
                   7787: 		height:100%;
                   7788: 		width:100%;
                   7789: 		margin:0;
                   7790: 		padding:0;
                   7791: 		background:#999;
                   7792: 		opacity:.75;
                   7793: 		filter: alpha(opacity=75);
                   7794: 		-moz-opacity: 0.75;
                   7795: 		z-index:101;
                   7796: }
                   7797: 
                   7798: * html .LCmodal-overlay {   
                   7799: 		position: absolute;
                   7800: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7801: }
                   7802: 
                   7803: .LCmodal-window {
                   7804: 		position:fixed;
                   7805: 		top:50%;
                   7806: 		left:50%;
                   7807: 		margin:0;
                   7808: 		padding:0;
                   7809: 		z-index:102;
                   7810: 	}
                   7811: 
                   7812: * html .LCmodal-window {
                   7813: 		position:absolute;
                   7814: }
                   7815: 
                   7816: .LCclose-window {
                   7817: 		position:absolute;
                   7818: 		width:32px;
                   7819: 		height:32px;
                   7820: 		right:8px;
                   7821: 		top:8px;
                   7822: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7823: 		text-indent:-99999px;
                   7824: 		overflow:hidden;
                   7825: 		cursor:pointer;
                   7826: }
                   7827: 
1.1075.2.141  raeburn  7828: pre.LC_wordwrap {
                   7829:   white-space: pre-wrap;
                   7830:   white-space: -moz-pre-wrap;
                   7831:   white-space: -pre-wrap;
                   7832:   white-space: -o-pre-wrap;
                   7833:   word-wrap: break-word;
                   7834: }
                   7835: 
1.1075.2.17  raeburn  7836: /*
                   7837:   styles used by TTH when "Default set of options to pass to tth/m
                   7838:   when converting TeX" in course settings has been set
                   7839: 
                   7840:   option passed: -t
                   7841: 
                   7842: */
                   7843: 
                   7844: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7845: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7846: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7847: td div.norm {line-height:normal;}
                   7848: 
                   7849: /*
                   7850:   option passed -y3
                   7851: */
                   7852: 
                   7853: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7854: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7855: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7856: 
1.1075.2.121  raeburn  7857: #LC_minitab_header {
                   7858:   float:left;
                   7859:   width:100%;
                   7860:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7861:   font-size:93%;
                   7862:   line-height:normal;
                   7863:   margin: 0.5em 0 0.5em 0;
                   7864: }
                   7865: #LC_minitab_header ul {
                   7866:   margin:0;
                   7867:   padding:10px 10px 0;
                   7868:   list-style:none;
                   7869: }
                   7870: #LC_minitab_header li {
                   7871:   float:left;
                   7872:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7873:   margin:0;
                   7874:   padding:0 0 0 9px;
                   7875: }
                   7876: #LC_minitab_header a {
                   7877:   display:block;
                   7878:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7879:   padding:5px 15px 4px 6px;
                   7880: }
                   7881: #LC_minitab_header #LC_current_minitab {
                   7882:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7883: }
                   7884: #LC_minitab_header #LC_current_minitab a {
                   7885:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7886:   padding-bottom:5px;
                   7887: }
                   7888: 
                   7889: 
1.343     albertel 7890: END
                   7891: }
                   7892: 
1.306     albertel 7893: =pod
                   7894: 
                   7895: =item * &headtag()
                   7896: 
                   7897: Returns a uniform footer for LON-CAPA web pages.
                   7898: 
1.307     albertel 7899: Inputs: $title - optional title for the head
                   7900:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7901:         $args - optional arguments
1.319     albertel 7902:             force_register - if is true call registerurl so the remote is 
                   7903:                              informed
1.415     albertel 7904:             redirect       -> array ref of
                   7905:                                    1- seconds before redirect occurs
                   7906:                                    2- url to redirect to
                   7907:                                    3- whether the side effect should occur
1.315     albertel 7908:                            (side effect of setting 
                   7909:                                $env{'internal.head.redirect'} to the url 
                   7910:                                redirected too)
1.352     albertel 7911:             domain         -> force to color decorate a page for a specific
                   7912:                                domain
                   7913:             function       -> force usage of a specific rolish color scheme
                   7914:             bgcolor        -> override the default page bgcolor
1.460     albertel 7915:             no_auto_mt_title
                   7916:                            -> prevent &mt()ing the title arg
1.464     albertel 7917: 
1.306     albertel 7918: =cut
                   7919: 
                   7920: sub headtag {
1.313     albertel 7921:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7922:     
1.363     albertel 7923:     my $function = $args->{'function'} || &get_users_function();
                   7924:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7925:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7926:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7927:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7928: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7929: 		   #time(),
1.418     albertel 7930: 		   $env{'environment.color.timestamp'},
1.363     albertel 7931: 		   $function,$domain,$bgcolor);
                   7932: 
1.369     www      7933:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7934: 
1.308     albertel 7935:     my $result =
                   7936: 	'<head>'.
1.1075.2.56  raeburn  7937: 	&font_settings($args);
1.319     albertel 7938: 
1.1075.2.72  raeburn  7939:     my $inhibitprint;
                   7940:     if ($args->{'print_suppress'}) {
                   7941:         $inhibitprint = &print_suppression();
                   7942:     }
1.1064    raeburn  7943: 
1.461     albertel 7944:     if (!$args->{'frameset'}) {
                   7945: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7946:     }
1.1075.2.12  raeburn  7947:     if ($args->{'force_register'}) {
                   7948:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7949:     }
1.436     albertel 7950:     if (!$args->{'no_nav_bar'} 
                   7951: 	&& !$args->{'only_body'}
                   7952: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7953: 	$result .= &help_menu_js($httphost);
1.1032    www      7954:         $result.=&modal_window();
1.1038    www      7955:         $result.=&togglebox_script();
1.1034    www      7956:         $result.=&wishlist_window();
1.1041    www      7957:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7958:     } else {
                   7959:         if ($args->{'add_modal'}) {
                   7960:            $result.=&modal_window();
                   7961:         }
                   7962:         if ($args->{'add_wishlist'}) {
                   7963:            $result.=&wishlist_window();
                   7964:         }
1.1038    www      7965:         if ($args->{'add_togglebox'}) {
                   7966:            $result.=&togglebox_script();
                   7967:         }
1.1041    www      7968:         if ($args->{'add_progressbar'}) {
                   7969:            $result.=&LCprogressbarUpdate_script();
                   7970:         }
1.436     albertel 7971:     }
1.314     albertel 7972:     if (ref($args->{'redirect'})) {
1.414     albertel 7973: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7974: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7975: 	if (!$inhibit_continue) {
                   7976: 	    $env{'internal.head.redirect'} = $url;
                   7977: 	}
1.313     albertel 7978: 	$result.=<<ADDMETA
                   7979: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7980: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7981: ADDMETA
1.1075.2.89  raeburn  7982:     } else {
                   7983:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7984:             my $requrl = $env{'request.uri'};
                   7985:             if ($requrl eq '') {
                   7986:                 $requrl = $ENV{'REQUEST_URI'};
                   7987:                 $requrl =~ s/\?.+$//;
                   7988:             }
                   7989:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7990:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7991:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7992:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7993:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7994:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  7995:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  7996:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  7997:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7998:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  7999:                             $offload = 1;
1.1075.2.151  raeburn  8000:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8001:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8002:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8003:                                     $offloadoth = 1;
                   8004:                                     $dom_in_use = $env{'user.domain'};
                   8005:                                 }
                   8006:                             }
1.1075.2.145  raeburn  8007:                         }
                   8008:                     }
                   8009:                     unless ($offload) {
                   8010:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8011:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8012:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8013:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8014:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8015:                                         $offload = 1;
1.1075.2.151  raeburn  8016:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8017:                                         $dom_in_use = $env{'user.domain'};
                   8018:                                     }
1.1075.2.89  raeburn  8019:                                 }
1.1075.2.145  raeburn  8020:                             }
                   8021:                         }
                   8022:                     }
                   8023:                     if ($offload) {
                   8024:                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8025:                         if (($newserver eq '') && ($offloadoth)) {
                   8026:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8027:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8028:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8029:                             }
                   8030:                         }
1.1075.2.145  raeburn  8031:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8032:                             my $numsec = 5;
                   8033:                             my $timeout = $numsec * 1000;
                   8034:                             my ($newurl,$locknum,%locks,$msg);
                   8035:                             if ($env{'request.role.adv'}) {
                   8036:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8037:                             }
                   8038:                             my $disable_submit = 0;
                   8039:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8040:                                 $disable_submit = 1;
                   8041:                             }
                   8042:                             if ($locknum) {
                   8043:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8044:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8045:                                        join(", ",sort(values(%locks)))."\n";
                   8046:                                 if (&show_course()) {
                   8047:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8048:                                 } else {
1.1075.2.145  raeburn  8049:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8050:                                 }
                   8051:                             } else {
                   8052:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8053:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8054:                                 }
                   8055:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8056:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8057:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8058:                                     $newurl .= '&role='.$env{'request.role'};
                   8059:                                 }
                   8060:                                 if ($env{'request.symb'}) {
                   8061:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8062:                                     if ($shownsymb =~ m{^/enc/}) {
                   8063:                                         my $reqdmajor = 2;
                   8064:                                         my $reqdminor = 11;
                   8065:                                         my $reqdsubminor = 3;
                   8066:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8067:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8068:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8069:                                         if (($major eq '' && $minor eq '') ||
                   8070:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8071:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8072:                                              ($reqdsubminor > $subminor))))) {
                   8073:                                             undef($shownsymb);
                   8074:                                         }
1.1075.2.89  raeburn  8075:                                     }
1.1075.2.145  raeburn  8076:                                     if ($shownsymb) {
                   8077:                                         &js_escape(\$shownsymb);
                   8078:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8079:                                     }
1.1075.2.145  raeburn  8080:                                 } else {
                   8081:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8082:                                     &js_escape(\$shownurl);
                   8083:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8084:                                 }
1.1075.2.145  raeburn  8085:                             }
                   8086:                             &js_escape(\$msg);
                   8087:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8088: <meta http-equiv="pragma" content="no-cache" />
                   8089: <script type="text/javascript">
1.1075.2.92  raeburn  8090: // <![CDATA[
1.1075.2.89  raeburn  8091: function LC_Offload_Now() {
                   8092:     var dest = "$newurl";
                   8093:     if (dest != '') {
                   8094:         window.location.href="$newurl";
                   8095:     }
                   8096: }
1.1075.2.92  raeburn  8097: \$(document).ready(function () {
                   8098:     window.alert('$msg');
                   8099:     if ($disable_submit) {
1.1075.2.89  raeburn  8100:         \$(".LC_hwk_submit").prop("disabled", true);
                   8101:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8102:     }
                   8103:     setTimeout('LC_Offload_Now()', $timeout);
                   8104: });
                   8105: // ]]>
1.1075.2.89  raeburn  8106: </script>
                   8107: OFFLOAD
                   8108:                         }
                   8109:                     }
                   8110:                 }
                   8111:             }
                   8112:         }
1.313     albertel 8113:     }
1.306     albertel 8114:     if (!defined($title)) {
                   8115: 	$title = 'The LearningOnline Network with CAPA';
                   8116:     }
1.460     albertel 8117:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8118:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8119: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8120:     if (!$args->{'frameset'}) {
                   8121:         $result .= ' /';
                   8122:     }
                   8123:     $result .= '>'
1.1064    raeburn  8124:         .$inhibitprint
1.414     albertel 8125: 	.$head_extra;
1.1075.2.108  raeburn  8126:     my $clientmobile;
                   8127:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8128:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8129:     } else {
                   8130:         $clientmobile = $env{'browser.mobile'};
                   8131:     }
                   8132:     if ($clientmobile) {
1.1075.2.42  raeburn  8133:         $result .= '
                   8134: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8135: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8136:     }
1.1075.2.126  raeburn  8137:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8138:     return $result.'</head>';
1.306     albertel 8139: }
                   8140: 
                   8141: =pod
                   8142: 
1.340     albertel 8143: =item * &font_settings()
                   8144: 
                   8145: Returns neccessary <meta> to set the proper encoding
                   8146: 
1.1075.2.56  raeburn  8147: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8148: 
                   8149: =cut
                   8150: 
                   8151: sub font_settings {
1.1075.2.56  raeburn  8152:     my ($args) = @_;
1.340     albertel 8153:     my $headerstring='';
1.1075.2.56  raeburn  8154:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8155:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8156: 	$headerstring.=
1.1075.2.61  raeburn  8157: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8158:         if (!$args->{'frameset'}) {
                   8159:             $headerstring.= ' /';
                   8160:         }
                   8161:         $headerstring .= '>'."\n";
1.340     albertel 8162:     }
                   8163:     return $headerstring;
                   8164: }
                   8165: 
1.341     albertel 8166: =pod
                   8167: 
1.1064    raeburn  8168: =item * &print_suppression()
                   8169: 
                   8170: In course context returns css which causes the body to be blank when media="print",
                   8171: if printout generation is unavailable for the current resource.
                   8172: 
                   8173: This could be because:
                   8174: 
                   8175: (a) printstartdate is in the future
                   8176: 
                   8177: (b) printenddate is in the past
                   8178: 
                   8179: (c) there is an active exam block with "printout"
                   8180: functionality blocked
                   8181: 
                   8182: Users with pav, pfo or evb privileges are exempt.
                   8183: 
                   8184: Inputs: none
                   8185: 
                   8186: =cut
                   8187: 
                   8188: 
                   8189: sub print_suppression {
                   8190:     my $noprint;
                   8191:     if ($env{'request.course.id'}) {
                   8192:         my $scope = $env{'request.course.id'};
                   8193:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8194:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8195:             return;
                   8196:         }
                   8197:         if ($env{'request.course.sec'} ne '') {
                   8198:             $scope .= "/$env{'request.course.sec'}";
                   8199:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8200:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8201:                 return;
1.1064    raeburn  8202:             }
                   8203:         }
                   8204:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8205:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8206:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8207:         if ($blocked) {
                   8208:             my $checkrole = "cm./$cdom/$cnum";
                   8209:             if ($env{'request.course.sec'} ne '') {
                   8210:                 $checkrole .= "/$env{'request.course.sec'}";
                   8211:             }
                   8212:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8213:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8214:                 $noprint = 1;
                   8215:             }
                   8216:         }
                   8217:         unless ($noprint) {
                   8218:             my $symb = &Apache::lonnet::symbread();
                   8219:             if ($symb ne '') {
                   8220:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8221:                 if (ref($navmap)) {
                   8222:                     my $res = $navmap->getBySymb($symb);
                   8223:                     if (ref($res)) {
                   8224:                         if (!$res->resprintable()) {
                   8225:                             $noprint = 1;
                   8226:                         }
                   8227:                     }
                   8228:                 }
                   8229:             }
                   8230:         }
                   8231:         if ($noprint) {
                   8232:             return <<"ENDSTYLE";
                   8233: <style type="text/css" media="print">
                   8234:     body { display:none }
                   8235: </style>
                   8236: ENDSTYLE
                   8237:         }
                   8238:     }
                   8239:     return;
                   8240: }
                   8241: 
                   8242: =pod
                   8243: 
1.341     albertel 8244: =item * &xml_begin()
                   8245: 
                   8246: Returns the needed doctype and <html>
                   8247: 
                   8248: Inputs: none
                   8249: 
                   8250: =cut
                   8251: 
                   8252: sub xml_begin {
1.1075.2.61  raeburn  8253:     my ($is_frameset) = @_;
1.341     albertel 8254:     my $output='';
                   8255: 
                   8256:     if ($env{'browser.mathml'}) {
                   8257: 	$output='<?xml version="1.0"?>'
                   8258:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8259: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8260:             
                   8261: #	    .'<!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">] >'
                   8262: 	    .'<!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">'
                   8263:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8264: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8265:     } elsif ($is_frameset) {
                   8266:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8267:                 '<html>'."\n";
1.341     albertel 8268:     } else {
1.1075.2.61  raeburn  8269: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8270:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8271:     }
                   8272:     return $output;
                   8273: }
1.340     albertel 8274: 
                   8275: =pod
                   8276: 
1.306     albertel 8277: =item * &start_page()
                   8278: 
                   8279: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8280: 
1.648     raeburn  8281: Inputs:
                   8282: 
                   8283: =over 4
                   8284: 
                   8285: $title - optional title for the page
                   8286: 
                   8287: $head_extra - optional extra HTML to incude inside the <head>
                   8288: 
                   8289: $args - additional optional args supported are:
                   8290: 
                   8291: =over 8
                   8292: 
                   8293:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8294:                                     arg on
1.814     bisitz   8295:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8296:              add_entries    -> additional attributes to add to the  <body>
                   8297:              domain         -> force to color decorate a page for a 
1.317     albertel 8298:                                     specific domain
1.648     raeburn  8299:              function       -> force usage of a specific rolish color
1.317     albertel 8300:                                     scheme
1.648     raeburn  8301:              redirect       -> see &headtag()
                   8302:              bgcolor        -> override the default page bg color
                   8303:              js_ready       -> return a string ready for being used in 
1.317     albertel 8304:                                     a javascript writeln
1.648     raeburn  8305:              html_encode    -> return a string ready for being used in 
1.320     albertel 8306:                                     a html attribute
1.648     raeburn  8307:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8308:                                     $forcereg arg
1.648     raeburn  8309:              frameset       -> if true will start with a <frameset>
1.330     albertel 8310:                                     rather than <body>
1.648     raeburn  8311:              skip_phases    -> hash ref of 
1.338     albertel 8312:                                     head -> skip the <html><head> generation
                   8313:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8314:              no_inline_link -> if true and in remote mode, don't show the
                   8315:                                     'Switch To Inline Menu' link
1.648     raeburn  8316:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8317:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8318:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8319:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8320:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8321:              group          -> includes the current group, if page is for a
                   8322:                                specific group
1.1075.2.133  raeburn  8323:              use_absolute   -> for request for external resource or syllabus, this
                   8324:                                will contain https://<hostname> if server uses
                   8325:                                https (as per hosts.tab), but request is for http
                   8326:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8327: 
1.648     raeburn  8328: =back
1.460     albertel 8329: 
1.648     raeburn  8330: =back
1.562     albertel 8331: 
1.306     albertel 8332: =cut
                   8333: 
                   8334: sub start_page {
1.309     albertel 8335:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8336:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8337: 
1.315     albertel 8338:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8339:     my ($result,@advtools);
1.964     droeschl 8340: 
1.338     albertel 8341:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8342:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8343:     }
                   8344:     
                   8345:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8346: 	if ($args->{'frameset'}) {
                   8347: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8348: 						$args->{'add_entries'});
                   8349: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8350:         } else {
                   8351:             $result .=
                   8352:                 &bodytag($title, 
                   8353:                          $args->{'function'},       $args->{'add_entries'},
                   8354:                          $args->{'only_body'},      $args->{'domain'},
                   8355:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8356:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8357:                          $args,                     \@advtools);
1.831     bisitz   8358:         }
1.330     albertel 8359:     }
1.338     albertel 8360: 
1.315     albertel 8361:     if ($args->{'js_ready'}) {
1.713     kaisler  8362: 		$result = &js_ready($result);
1.315     albertel 8363:     }
1.320     albertel 8364:     if ($args->{'html_encode'}) {
1.713     kaisler  8365: 		$result = &html_encode($result);
                   8366:     }
                   8367: 
1.813     bisitz   8368:     # Preparation for new and consistent functionlist at top of screen
                   8369:     # if ($args->{'functionlist'}) {
                   8370:     #            $result .= &build_functionlist();
                   8371:     #}
                   8372: 
1.964     droeschl 8373:     # Don't add anything more if only_body wanted or in const space
                   8374:     return $result if    $args->{'only_body'} 
                   8375:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8376: 
                   8377:     #Breadcrumbs
1.758     kaisler  8378:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8379: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8380: 		#if any br links exists, add them to the breadcrumbs
                   8381: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8382: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8383: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8384: 			}
                   8385: 		}
1.1075.2.19  raeburn  8386:                 # if @advtools array contains items add then to the breadcrumbs
                   8387:                 if (@advtools > 0) {
                   8388:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8389:                 }
1.1075.2.123  raeburn  8390:                 my $menulink;
                   8391:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8392:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8393:                     $menulink = 0;
                   8394:                 } else {
                   8395:                     undef($menulink);
                   8396:                 }
1.758     kaisler  8397: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8398: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8399: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8400: 		}else{
1.1075.2.123  raeburn  8401: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8402: 		}
1.1075.2.24  raeburn  8403:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8404:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8405:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8406:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8407:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8408:     }
1.315     albertel 8409:     return $result;
1.306     albertel 8410: }
                   8411: 
                   8412: sub end_page {
1.315     albertel 8413:     my ($args) = @_;
                   8414:     $env{'internal.end_page'}++;
1.330     albertel 8415:     my $result;
1.335     albertel 8416:     if ($args->{'discussion'}) {
                   8417: 	my ($target,$parser);
                   8418: 	if (ref($args->{'discussion'})) {
                   8419: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8420: 				$args->{'discussion'}{'parser'});
                   8421: 	}
                   8422: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8423:     }
1.330     albertel 8424:     if ($args->{'frameset'}) {
                   8425: 	$result .= '</frameset>';
                   8426:     } else {
1.635     raeburn  8427: 	$result .= &endbodytag($args);
1.330     albertel 8428:     }
1.1075.2.6  raeburn  8429:     unless ($args->{'notbody'}) {
                   8430:         $result .= "\n</html>";
                   8431:     }
1.330     albertel 8432: 
1.315     albertel 8433:     if ($args->{'js_ready'}) {
1.317     albertel 8434: 	$result = &js_ready($result);
1.315     albertel 8435:     }
1.335     albertel 8436: 
1.320     albertel 8437:     if ($args->{'html_encode'}) {
                   8438: 	$result = &html_encode($result);
                   8439:     }
1.335     albertel 8440: 
1.315     albertel 8441:     return $result;
                   8442: }
                   8443: 
1.1034    www      8444: sub wishlist_window {
                   8445:     return(<<'ENDWISHLIST');
1.1046    raeburn  8446: <script type="text/javascript">
1.1034    www      8447: // <![CDATA[
                   8448: // <!-- BEGIN LON-CAPA Internal
                   8449: function set_wishlistlink(title, path) {
                   8450:     if (!title) {
                   8451:         title = document.title;
                   8452:         title = title.replace(/^LON-CAPA /,'');
                   8453:     }
1.1075.2.65  raeburn  8454:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8455:     title = title.replace("'","\\\'");
1.1034    www      8456:     if (!path) {
                   8457:         path = location.pathname;
                   8458:     }
1.1075.2.65  raeburn  8459:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8460:     path = path.replace("'","\\\'");
1.1034    www      8461:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8462:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8463: }
                   8464: // END LON-CAPA Internal -->
                   8465: // ]]>
                   8466: </script>
                   8467: ENDWISHLIST
                   8468: }
                   8469: 
1.1030    www      8470: sub modal_window {
                   8471:     return(<<'ENDMODAL');
1.1046    raeburn  8472: <script type="text/javascript">
1.1030    www      8473: // <![CDATA[
                   8474: // <!-- BEGIN LON-CAPA Internal
                   8475: var modalWindow = {
                   8476: 	parent:"body",
                   8477: 	windowId:null,
                   8478: 	content:null,
                   8479: 	width:null,
                   8480: 	height:null,
                   8481: 	close:function()
                   8482: 	{
                   8483: 	        $(".LCmodal-window").remove();
                   8484: 	        $(".LCmodal-overlay").remove();
                   8485: 	},
                   8486: 	open:function()
                   8487: 	{
                   8488: 		var modal = "";
                   8489: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8490: 		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;\">";
                   8491: 		modal += this.content;
                   8492: 		modal += "</div>";	
                   8493: 
                   8494: 		$(this.parent).append(modal);
                   8495: 
                   8496: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8497: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8498: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8499: 	}
                   8500: };
1.1075.2.42  raeburn  8501: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8502: 	{
1.1075.2.119  raeburn  8503:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8504: 		modalWindow.windowId = "myModal";
                   8505: 		modalWindow.width = width;
                   8506: 		modalWindow.height = height;
1.1075.2.80  raeburn  8507: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8508: 		modalWindow.open();
1.1075.2.87  raeburn  8509: 	};
1.1030    www      8510: // END LON-CAPA Internal -->
                   8511: // ]]>
                   8512: </script>
                   8513: ENDMODAL
                   8514: }
                   8515: 
                   8516: sub modal_link {
1.1075.2.42  raeburn  8517:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8518:     unless ($width) { $width=480; }
                   8519:     unless ($height) { $height=400; }
1.1031    www      8520:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8521:     unless ($transparency) { $transparency='true'; }
                   8522: 
1.1074    raeburn  8523:     my $target_attr;
                   8524:     if (defined($target)) {
                   8525:         $target_attr = 'target="'.$target.'"';
                   8526:     }
                   8527:     return <<"ENDLINK";
1.1075.2.143  raeburn  8528: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8529: ENDLINK
1.1030    www      8530: }
                   8531: 
1.1032    www      8532: sub modal_adhoc_script {
1.1075.2.155  raeburn  8533:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   8534:     my $mathjax;
                   8535:     if ($possmathjax) {
                   8536:         $mathjax = <<'ENDJAX';
                   8537:                if (typeof MathJax == 'object') {
                   8538:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   8539:                }
                   8540: ENDJAX
                   8541:     }
1.1032    www      8542:     return (<<ENDADHOC);
1.1046    raeburn  8543: <script type="text/javascript">
1.1032    www      8544: // <![CDATA[
                   8545:         var $funcname = function()
                   8546:         {
                   8547:                 modalWindow.windowId = "myModal";
                   8548:                 modalWindow.width = $width;
                   8549:                 modalWindow.height = $height;
                   8550:                 modalWindow.content = '$content';
                   8551:                 modalWindow.open();
1.1075.2.155  raeburn  8552:                 $mathjax
1.1032    www      8553:         };  
                   8554: // ]]>
                   8555: </script>
                   8556: ENDADHOC
                   8557: }
                   8558: 
1.1041    www      8559: sub modal_adhoc_inner {
1.1075.2.155  raeburn  8560:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      8561:     my $innerwidth=$width-20;
                   8562:     $content=&js_ready(
1.1042    www      8563:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8564:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8565:                  $content.
1.1041    www      8566:                  &end_scrollbox().
1.1075.2.42  raeburn  8567:                  &end_page()
1.1041    www      8568:              );
1.1075.2.155  raeburn  8569:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      8570: }
                   8571: 
                   8572: sub modal_adhoc_window {
1.1075.2.155  raeburn  8573:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   8574:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      8575:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8576: }
                   8577: 
                   8578: sub modal_adhoc_launch {
                   8579:     my ($funcname,$width,$height,$content)=@_;
                   8580:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8581: <script type="text/javascript">
                   8582: // <![CDATA[
                   8583: $funcname();
                   8584: // ]]>
                   8585: </script>
                   8586: ENDLAUNCH
                   8587: }
                   8588: 
                   8589: sub modal_adhoc_close {
                   8590:     return (<<ENDCLOSE);
                   8591: <script type="text/javascript">
                   8592: // <![CDATA[
                   8593: modalWindow.close();
                   8594: // ]]>
                   8595: </script>
                   8596: ENDCLOSE
                   8597: }
                   8598: 
1.1038    www      8599: sub togglebox_script {
                   8600:    return(<<ENDTOGGLE);
                   8601: <script type="text/javascript"> 
                   8602: // <![CDATA[
                   8603: function LCtoggleDisplay(id,hidetext,showtext) {
                   8604:    link = document.getElementById(id + "link").childNodes[0];
                   8605:    with (document.getElementById(id).style) {
                   8606:       if (display == "none" ) {
                   8607:           display = "inline";
                   8608:           link.nodeValue = hidetext;
                   8609:         } else {
                   8610:           display = "none";
                   8611:           link.nodeValue = showtext;
                   8612:        }
                   8613:    }
                   8614: }
                   8615: // ]]>
                   8616: </script>
                   8617: ENDTOGGLE
                   8618: }
                   8619: 
1.1039    www      8620: sub start_togglebox {
                   8621:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8622:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8623:     unless ($showtext) { $showtext=&mt('show'); }
                   8624:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8625:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8626:     return &start_data_table().
                   8627:            &start_data_table_header_row().
                   8628:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8629:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8630:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8631:            &end_data_table_header_row().
                   8632:            '<tr id="'.$id.'" style="display:none""><td>';
                   8633: }
                   8634: 
                   8635: sub end_togglebox {
                   8636:     return '</td></tr>'.&end_data_table();
                   8637: }
                   8638: 
1.1041    www      8639: sub LCprogressbar_script {
1.1075.2.130  raeburn  8640:    my ($id,$number_to_do)=@_;
                   8641:    if ($number_to_do) {
                   8642:        return(<<ENDPROGRESS);
1.1041    www      8643: <script type="text/javascript">
                   8644: // <![CDATA[
1.1045    www      8645: \$('#progressbar$id').progressbar({
1.1041    www      8646:   value: 0,
                   8647:   change: function(event, ui) {
                   8648:     var newVal = \$(this).progressbar('option', 'value');
                   8649:     \$('.pblabel', this).text(LCprogressTxt);
                   8650:   }
                   8651: });
                   8652: // ]]>
                   8653: </script>
                   8654: ENDPROGRESS
1.1075.2.130  raeburn  8655:    } else {
                   8656:        return(<<ENDPROGRESS);
                   8657: <script type="text/javascript">
                   8658: // <![CDATA[
                   8659: \$('#progressbar$id').progressbar({
                   8660:   value: false,
                   8661:   create: function(event, ui) {
                   8662:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8663:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8664:   }
                   8665: });
                   8666: // ]]>
                   8667: </script>
                   8668: ENDPROGRESS
                   8669:    }
1.1041    www      8670: }
                   8671: 
                   8672: sub LCprogressbarUpdate_script {
                   8673:    return(<<ENDPROGRESSUPDATE);
                   8674: <style type="text/css">
                   8675: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8676: .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      8677: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8678: </style>
                   8679: <script type="text/javascript">
                   8680: // <![CDATA[
1.1045    www      8681: var LCprogressTxt='---';
                   8682: 
1.1075.2.130  raeburn  8683: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8684:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8685:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8686:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8687:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8688:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8689:    } else {
                   8690:        \$('#progressbar'+id).progressbar('value',percent);
                   8691:    }
1.1041    www      8692: }
                   8693: // ]]>
                   8694: </script>
                   8695: ENDPROGRESSUPDATE
                   8696: }
                   8697: 
1.1042    www      8698: my $LClastpercent;
1.1045    www      8699: my $LCidcnt;
                   8700: my $LCcurrentid;
1.1042    www      8701: 
1.1041    www      8702: sub LCprogressbar {
1.1075.2.130  raeburn  8703:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8704:     $LClastpercent=0;
1.1045    www      8705:     $LCidcnt++;
                   8706:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8707:     my ($starting,$content);
                   8708:     if ($number_to_do) {
                   8709:         $starting=&mt('Starting');
                   8710:         $content=(<<ENDPROGBAR);
                   8711: $preamble
1.1045    www      8712:   <div id="progressbar$LCcurrentid">
1.1041    www      8713:     <span class="pblabel">$starting</span>
                   8714:   </div>
                   8715: ENDPROGBAR
1.1075.2.130  raeburn  8716:     } else {
                   8717:         $starting=&mt('Loading...');
                   8718:         $LClastpercent='false';
                   8719:         $content=(<<ENDPROGBAR);
                   8720: $preamble
                   8721:   <div id="progressbar$LCcurrentid">
                   8722:       <div class="progress-label">$starting</div>
                   8723:   </div>
                   8724: ENDPROGBAR
                   8725:     }
                   8726:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8727: }
                   8728: 
                   8729: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8730:     my ($r,$val,$text,$number_to_do)=@_;
                   8731:     if ($number_to_do) {
                   8732:         unless ($val) { 
                   8733:             if ($LClastpercent) {
                   8734:                 $val=$LClastpercent;
                   8735:             } else {
                   8736:                 $val=0;
                   8737:             }
                   8738:         }
                   8739:         if ($val<0) { $val=0; }
                   8740:         if ($val>100) { $val=0; }
                   8741:         $LClastpercent=$val;
                   8742:         unless ($text) { $text=$val.'%'; }
                   8743:     } else {
                   8744:         $val = 'false';
1.1042    www      8745:     }
1.1041    www      8746:     $text=&js_ready($text);
1.1044    www      8747:     &r_print($r,<<ENDUPDATE);
1.1041    www      8748: <script type="text/javascript">
                   8749: // <![CDATA[
1.1075.2.130  raeburn  8750: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8751: // ]]>
                   8752: </script>
                   8753: ENDUPDATE
1.1035    www      8754: }
                   8755: 
1.1042    www      8756: sub LCprogressbarClose {
                   8757:     my ($r)=@_;
                   8758:     $LClastpercent=0;
1.1044    www      8759:     &r_print($r,<<ENDCLOSE);
1.1042    www      8760: <script type="text/javascript">
                   8761: // <![CDATA[
1.1045    www      8762: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8763: // ]]>
                   8764: </script>
                   8765: ENDCLOSE
1.1044    www      8766: }
                   8767: 
                   8768: sub r_print {
                   8769:     my ($r,$to_print)=@_;
                   8770:     if ($r) {
                   8771:       $r->print($to_print);
                   8772:       $r->rflush();
                   8773:     } else {
                   8774:       print($to_print);
                   8775:     }
1.1042    www      8776: }
                   8777: 
1.320     albertel 8778: sub html_encode {
                   8779:     my ($result) = @_;
                   8780: 
1.322     albertel 8781:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8782:     
                   8783:     return $result;
                   8784: }
1.1044    www      8785: 
1.317     albertel 8786: sub js_ready {
                   8787:     my ($result) = @_;
                   8788: 
1.323     albertel 8789:     $result =~ s/[\n\r]/ /xmsg;
                   8790:     $result =~ s/\\/\\\\/xmsg;
                   8791:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8792:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8793:     
                   8794:     return $result;
                   8795: }
                   8796: 
1.315     albertel 8797: sub validate_page {
                   8798:     if (  exists($env{'internal.start_page'})
1.316     albertel 8799: 	  &&     $env{'internal.start_page'} > 1) {
                   8800: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8801: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8802: 				 $ENV{'request.filename'});
1.315     albertel 8803:     }
                   8804:     if (  exists($env{'internal.end_page'})
1.316     albertel 8805: 	  &&     $env{'internal.end_page'} > 1) {
                   8806: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8807: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8808: 				 $env{'request.filename'});
1.315     albertel 8809:     }
                   8810:     if (     exists($env{'internal.start_page'})
                   8811: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8812: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8813: 				 $env{'request.filename'});
1.315     albertel 8814:     }
                   8815:     if (   ! exists($env{'internal.start_page'})
                   8816: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8817: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8818: 				 $env{'request.filename'});
1.315     albertel 8819:     }
1.306     albertel 8820: }
1.315     albertel 8821: 
1.996     www      8822: 
                   8823: sub start_scrollbox {
1.1075.2.56  raeburn  8824:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8825:     unless ($outerwidth) { $outerwidth='520px'; }
                   8826:     unless ($width) { $width='500px'; }
                   8827:     unless ($height) { $height='200px'; }
1.1075    raeburn  8828:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8829:     if ($id ne '') {
1.1075.2.42  raeburn  8830:         $table_id = ' id="table_'.$id.'"';
                   8831:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8832:     }
1.1075    raeburn  8833:     if ($bgcolor ne '') {
                   8834:         $tdcol = "background-color: $bgcolor;";
                   8835:     }
1.1075.2.42  raeburn  8836:     my $nicescroll_js;
                   8837:     if ($env{'browser.mobile'}) {
                   8838:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8839:     }
1.1075    raeburn  8840:     return <<"END";
1.1075.2.42  raeburn  8841: $nicescroll_js
                   8842: 
                   8843: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8844: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8845: END
1.996     www      8846: }
                   8847: 
                   8848: sub end_scrollbox {
1.1036    www      8849:     return '</div></td></tr></table>';
1.996     www      8850: }
                   8851: 
1.1075.2.42  raeburn  8852: sub nicescroll_javascript {
                   8853:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8854:     my %options;
                   8855:     if (ref($cursor) eq 'HASH') {
                   8856:         %options = %{$cursor};
                   8857:     }
                   8858:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8859:         $options{'railalign'} = 'left';
                   8860:     }
                   8861:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8862:         my $function  = &get_users_function();
                   8863:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8864:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8865:             $options{'cursorcolor'} = '#00F';
                   8866:         }
                   8867:     }
                   8868:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8869:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8870:             $options{'cursoropacity'}='1.0';
                   8871:         }
                   8872:     } else {
                   8873:         $options{'cursoropacity'}='1.0';
                   8874:     }
                   8875:     if ($options{'cursorfixedheight'} eq 'none') {
                   8876:         delete($options{'cursorfixedheight'});
                   8877:     } else {
                   8878:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8879:     }
                   8880:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8881:         delete($options{'railoffset'});
                   8882:     }
                   8883:     my @niceoptions;
                   8884:     while (my($key,$value) = each(%options)) {
                   8885:         if ($value =~ /^\{.+\}$/) {
                   8886:             push(@niceoptions,$key.':'.$value);
                   8887:         } else {
                   8888:             push(@niceoptions,$key.':"'.$value.'"');
                   8889:         }
                   8890:     }
                   8891:     my $nicescroll_js = '
                   8892: $(document).ready(
                   8893:       function() {
                   8894:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8895:       }
                   8896: );
                   8897: ';
                   8898:     if ($framecheck) {
                   8899:         $nicescroll_js .= '
                   8900: function expand_div(caller) {
                   8901:     if (top === self) {
                   8902:         document.getElementById("'.$id.'").style.width = "auto";
                   8903:         document.getElementById("'.$id.'").style.height = "auto";
                   8904:     } else {
                   8905:         try {
                   8906:             if (parent.frames) {
                   8907:                 if (parent.frames.length > 1) {
                   8908:                     var framesrc = parent.frames[1].location.href;
                   8909:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8910:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8911:                         document.getElementById("'.$id.'").style.width = "auto";
                   8912:                         document.getElementById("'.$id.'").style.height = "auto";
                   8913:                     }
                   8914:                 }
                   8915:             }
                   8916:         } catch (e) {
                   8917:             return;
                   8918:         }
                   8919:     }
                   8920:     return;
                   8921: }
                   8922: ';
                   8923:     }
                   8924:     if ($needjsready) {
                   8925:         $nicescroll_js = '
                   8926: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8927:     } else {
                   8928:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8929:     }
                   8930:     return $nicescroll_js;
                   8931: }
                   8932: 
1.318     albertel 8933: sub simple_error_page {
1.1075.2.49  raeburn  8934:     my ($r,$title,$msg,$args) = @_;
                   8935:     if (ref($args) eq 'HASH') {
                   8936:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8937:     } else {
                   8938:         $msg = &mt($msg);
                   8939:     }
                   8940: 
1.318     albertel 8941:     my $page =
                   8942: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8943: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8944: 	&Apache::loncommon::end_page();
                   8945:     if (ref($r)) {
                   8946: 	$r->print($page);
1.327     albertel 8947: 	return;
1.318     albertel 8948:     }
                   8949:     return $page;
                   8950: }
1.347     albertel 8951: 
                   8952: {
1.610     albertel 8953:     my @row_count;
1.961     onken    8954: 
                   8955:     sub start_data_table_count {
                   8956:         unshift(@row_count, 0);
                   8957:         return;
                   8958:     }
                   8959: 
                   8960:     sub end_data_table_count {
                   8961:         shift(@row_count);
                   8962:         return;
                   8963:     }
                   8964: 
1.347     albertel 8965:     sub start_data_table {
1.1018    raeburn  8966: 	my ($add_class,$id) = @_;
1.422     albertel 8967: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8968:         my $table_id;
                   8969:         if (defined($id)) {
                   8970:             $table_id = ' id="'.$id.'"';
                   8971:         }
1.961     onken    8972: 	&start_data_table_count();
1.1018    raeburn  8973: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8974:     }
                   8975: 
                   8976:     sub end_data_table {
1.961     onken    8977: 	&end_data_table_count();
1.389     albertel 8978: 	return '</table>'."\n";;
1.347     albertel 8979:     }
                   8980: 
                   8981:     sub start_data_table_row {
1.974     wenzelju 8982: 	my ($add_class, $id) = @_;
1.610     albertel 8983: 	$row_count[0]++;
                   8984: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8985: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8986:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8987:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8988:     }
1.471     banghart 8989:     
                   8990:     sub continue_data_table_row {
1.974     wenzelju 8991: 	my ($add_class, $id) = @_;
1.610     albertel 8992: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8993: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8994:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8995:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8996:     }
1.347     albertel 8997: 
                   8998:     sub end_data_table_row {
1.389     albertel 8999: 	return '</tr>'."\n";;
1.347     albertel 9000:     }
1.367     www      9001: 
1.421     albertel 9002:     sub start_data_table_empty_row {
1.707     bisitz   9003: #	$row_count[0]++;
1.421     albertel 9004: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9005:     }
                   9006: 
                   9007:     sub end_data_table_empty_row {
                   9008: 	return '</tr>'."\n";;
                   9009:     }
                   9010: 
1.367     www      9011:     sub start_data_table_header_row {
1.389     albertel 9012: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9013:     }
                   9014: 
                   9015:     sub end_data_table_header_row {
1.389     albertel 9016: 	return '</tr>'."\n";;
1.367     www      9017:     }
1.890     droeschl 9018: 
                   9019:     sub data_table_caption {
                   9020:         my $caption = shift;
                   9021:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9022:     }
1.347     albertel 9023: }
                   9024: 
1.548     albertel 9025: =pod
                   9026: 
                   9027: =item * &inhibit_menu_check($arg)
                   9028: 
                   9029: Checks for a inhibitmenu state and generates output to preserve it
                   9030: 
                   9031: Inputs:         $arg - can be any of
                   9032:                      - undef - in which case the return value is a string 
                   9033:                                to add  into arguments list of a uri
                   9034:                      - 'input' - in which case the return value is a HTML
                   9035:                                  <form> <input> field of type hidden to
                   9036:                                  preserve the value
                   9037:                      - a url - in which case the return value is the url with
                   9038:                                the neccesary cgi args added to preserve the
                   9039:                                inhibitmenu state
                   9040:                      - a ref to a url - no return value, but the string is
                   9041:                                         updated to include the neccessary cgi
                   9042:                                         args to preserve the inhibitmenu state
                   9043: 
                   9044: =cut
                   9045: 
                   9046: sub inhibit_menu_check {
                   9047:     my ($arg) = @_;
                   9048:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9049:     if ($arg eq 'input') {
                   9050: 	if ($env{'form.inhibitmenu'}) {
                   9051: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9052: 	} else {
                   9053: 	    return
                   9054: 	}
                   9055:     }
                   9056:     if ($env{'form.inhibitmenu'}) {
                   9057: 	if (ref($arg)) {
                   9058: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9059: 	} elsif ($arg eq '') {
                   9060: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9061: 	} else {
                   9062: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9063: 	}
                   9064:     }
                   9065:     if (!ref($arg)) {
                   9066: 	return $arg;
                   9067:     }
                   9068: }
                   9069: 
1.251     albertel 9070: ###############################################
1.182     matthew  9071: 
                   9072: =pod
                   9073: 
1.549     albertel 9074: =back
                   9075: 
                   9076: =head1 User Information Routines
                   9077: 
                   9078: =over 4
                   9079: 
1.405     albertel 9080: =item * &get_users_function()
1.182     matthew  9081: 
                   9082: Used by &bodytag to determine the current users primary role.
                   9083: Returns either 'student','coordinator','admin', or 'author'.
                   9084: 
                   9085: =cut
                   9086: 
                   9087: ###############################################
                   9088: sub get_users_function {
1.815     tempelho 9089:     my $function = 'norole';
1.818     tempelho 9090:     if ($env{'request.role'}=~/^(st)/) {
                   9091:         $function='student';
                   9092:     }
1.907     raeburn  9093:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9094:         $function='coordinator';
                   9095:     }
1.258     albertel 9096:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9097:         $function='admin';
                   9098:     }
1.826     bisitz   9099:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9100:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9101:         $function='author';
                   9102:     }
                   9103:     return $function;
1.54      www      9104: }
1.99      www      9105: 
                   9106: ###############################################
                   9107: 
1.233     raeburn  9108: =pod
                   9109: 
1.821     raeburn  9110: =item * &show_course()
                   9111: 
                   9112: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9113: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9114: 
                   9115: Inputs:
                   9116: None
                   9117: 
                   9118: Outputs:
                   9119: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9120: 
                   9121: =cut
                   9122: 
                   9123: ###############################################
                   9124: sub show_course {
                   9125:     my $course = !$env{'user.adv'};
                   9126:     if (!$env{'user.adv'}) {
                   9127:         foreach my $env (keys(%env)) {
                   9128:             next if ($env !~ m/^user\.priv\./);
                   9129:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9130:                 $course = 0;
                   9131:                 last;
                   9132:             }
                   9133:         }
                   9134:     }
                   9135:     return $course;
                   9136: }
                   9137: 
                   9138: ###############################################
                   9139: 
                   9140: =pod
                   9141: 
1.542     raeburn  9142: =item * &check_user_status()
1.274     raeburn  9143: 
                   9144: Determines current status of supplied role for a
                   9145: specific user. Roles can be active, previous or future.
                   9146: 
                   9147: Inputs: 
                   9148: user's domain, user's username, course's domain,
1.375     raeburn  9149: course's number, optional section ID.
1.274     raeburn  9150: 
                   9151: Outputs:
                   9152: role status: active, previous or future. 
                   9153: 
                   9154: =cut
                   9155: 
                   9156: sub check_user_status {
1.412     raeburn  9157:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9158:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9159:     my @uroles = keys(%userinfo);
1.274     raeburn  9160:     my $srchstr;
                   9161:     my $active_chk = 'none';
1.412     raeburn  9162:     my $now = time;
1.274     raeburn  9163:     if (@uroles > 0) {
1.908     raeburn  9164:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9165:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9166:         } else {
1.412     raeburn  9167:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9168:         }
                   9169:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9170:             my $role_end = 0;
                   9171:             my $role_start = 0;
                   9172:             $active_chk = 'active';
1.412     raeburn  9173:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9174:                 $role_end = $1;
                   9175:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9176:                     $role_start = $1;
1.274     raeburn  9177:                 }
                   9178:             }
                   9179:             if ($role_start > 0) {
1.412     raeburn  9180:                 if ($now < $role_start) {
1.274     raeburn  9181:                     $active_chk = 'future';
                   9182:                 }
                   9183:             }
                   9184:             if ($role_end > 0) {
1.412     raeburn  9185:                 if ($now > $role_end) {
1.274     raeburn  9186:                     $active_chk = 'previous';
                   9187:                 }
                   9188:             }
                   9189:         }
                   9190:     }
                   9191:     return $active_chk;
                   9192: }
                   9193: 
                   9194: ###############################################
                   9195: 
                   9196: =pod
                   9197: 
1.405     albertel 9198: =item * &get_sections()
1.233     raeburn  9199: 
                   9200: Determines all the sections for a course including
                   9201: sections with students and sections containing other roles.
1.419     raeburn  9202: Incoming parameters: 
                   9203: 
                   9204: 1. domain
                   9205: 2. course number 
                   9206: 3. reference to array containing roles for which sections should 
                   9207: be gathered (optional).
                   9208: 4. reference to array containing status types for which sections 
                   9209: should be gathered (optional).
                   9210: 
                   9211: If the third argument is undefined, sections are gathered for any role. 
                   9212: If the fourth argument is undefined, sections are gathered for any status.
                   9213: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9214:  
1.374     raeburn  9215: Returns section hash (keys are section IDs, values are
                   9216: number of users in each section), subject to the
1.419     raeburn  9217: optional roles filter, optional status filter 
1.233     raeburn  9218: 
                   9219: =cut
                   9220: 
                   9221: ###############################################
                   9222: sub get_sections {
1.419     raeburn  9223:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9224:     if (!defined($cdom) || !defined($cnum)) {
                   9225:         my $cid =  $env{'request.course.id'};
                   9226: 
                   9227: 	return if (!defined($cid));
                   9228: 
                   9229:         $cdom = $env{'course.'.$cid.'.domain'};
                   9230:         $cnum = $env{'course.'.$cid.'.num'};
                   9231:     }
                   9232: 
                   9233:     my %sectioncount;
1.419     raeburn  9234:     my $now = time;
1.240     albertel 9235: 
1.1075.2.33  raeburn  9236:     my $check_students = 1;
                   9237:     my $only_students = 0;
                   9238:     if (ref($possible_roles) eq 'ARRAY') {
                   9239:         if (grep(/^st$/,@{$possible_roles})) {
                   9240:             if (@{$possible_roles} == 1) {
                   9241:                 $only_students = 1;
                   9242:             }
                   9243:         } else {
                   9244:             $check_students = 0;
                   9245:         }
                   9246:     }
                   9247: 
                   9248:     if ($check_students) {
1.276     albertel 9249: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9250: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9251: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9252:         my $start_index = &Apache::loncoursedata::CL_START();
                   9253:         my $end_index = &Apache::loncoursedata::CL_END();
                   9254:         my $status;
1.366     albertel 9255: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9256: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9257: 				                     $data->[$status_index],
                   9258:                                                      $data->[$start_index],
                   9259:                                                      $data->[$end_index]);
                   9260:             if ($stu_status eq 'Active') {
                   9261:                 $status = 'active';
                   9262:             } elsif ($end < $now) {
                   9263:                 $status = 'previous';
                   9264:             } elsif ($start > $now) {
                   9265:                 $status = 'future';
                   9266:             } 
                   9267: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9268:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9269:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9270: 		    $sectioncount{$section}++;
                   9271:                 }
1.240     albertel 9272: 	    }
                   9273: 	}
                   9274:     }
1.1075.2.33  raeburn  9275:     if ($only_students) {
                   9276:         return %sectioncount;
                   9277:     }
1.240     albertel 9278:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9279:     foreach my $user (sort(keys(%courseroles))) {
                   9280: 	if ($user !~ /^(\w{2})/) { next; }
                   9281: 	my ($role) = ($user =~ /^(\w{2})/);
                   9282: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9283: 	my ($section,$status);
1.240     albertel 9284: 	if ($role eq 'cr' &&
                   9285: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9286: 	    $section=$1;
                   9287: 	}
                   9288: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9289: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9290:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9291:         if ($end == -1 && $start == -1) {
                   9292:             next; #deleted role
                   9293:         }
                   9294:         if (!defined($possible_status)) { 
                   9295:             $sectioncount{$section}++;
                   9296:         } else {
                   9297:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9298:                 $status = 'active';
                   9299:             } elsif ($end < $now) {
                   9300:                 $status = 'future';
                   9301:             } elsif ($start > $now) {
                   9302:                 $status = 'previous';
                   9303:             }
                   9304:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9305:                 $sectioncount{$section}++;
                   9306:             }
                   9307:         }
1.233     raeburn  9308:     }
1.366     albertel 9309:     return %sectioncount;
1.233     raeburn  9310: }
                   9311: 
1.274     raeburn  9312: ###############################################
1.294     raeburn  9313: 
                   9314: =pod
1.405     albertel 9315: 
                   9316: =item * &get_course_users()
                   9317: 
1.275     raeburn  9318: Retrieves usernames:domains for users in the specified course
                   9319: with specific role(s), and access status. 
                   9320: 
                   9321: Incoming parameters:
1.277     albertel 9322: 1. course domain
                   9323: 2. course number
                   9324: 3. access status: users must have - either active, 
1.275     raeburn  9325: previous, future, or all.
1.277     albertel 9326: 4. reference to array of permissible roles
1.288     raeburn  9327: 5. reference to array of section restrictions (optional)
                   9328: 6. reference to results object (hash of hashes).
                   9329: 7. reference to optional userdata hash
1.609     raeburn  9330: 8. reference to optional statushash
1.630     raeburn  9331: 9. flag if privileged users (except those set to unhide in
                   9332:    course settings) should be excluded    
1.609     raeburn  9333: Keys of top level results hash are roles.
1.275     raeburn  9334: Keys of inner hashes are username:domain, with 
                   9335: values set to access type.
1.288     raeburn  9336: Optional userdata hash returns an array with arguments in the 
                   9337: same order as loncoursedata::get_classlist() for student data.
                   9338: 
1.609     raeburn  9339: Optional statushash returns
                   9340: 
1.288     raeburn  9341: Entries for end, start, section and status are blank because
                   9342: of the possibility of multiple values for non-student roles.
                   9343: 
1.275     raeburn  9344: =cut
1.405     albertel 9345: 
1.275     raeburn  9346: ###############################################
1.405     albertel 9347: 
1.275     raeburn  9348: sub get_course_users {
1.630     raeburn  9349:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9350:     my %idx = ();
1.419     raeburn  9351:     my %seclists;
1.288     raeburn  9352: 
                   9353:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9354:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9355:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9356:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9357:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9358:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9359:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9360:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9361: 
1.290     albertel 9362:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9363:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9364:         my $now = time;
1.277     albertel 9365:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9366:             my $match = 0;
1.412     raeburn  9367:             my $secmatch = 0;
1.419     raeburn  9368:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9369:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9370:             if ($section eq '') {
                   9371:                 $section = 'none';
                   9372:             }
1.291     albertel 9373:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9374:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9375:                     $secmatch = 1;
                   9376:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9377:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9378:                         $secmatch = 1;
                   9379:                     }
                   9380:                 } else {  
1.419     raeburn  9381: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9382: 		        $secmatch = 1;
                   9383:                     }
1.290     albertel 9384: 		}
1.412     raeburn  9385:                 if (!$secmatch) {
                   9386:                     next;
                   9387:                 }
1.419     raeburn  9388:             }
1.275     raeburn  9389:             if (defined($$types{'active'})) {
1.288     raeburn  9390:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9391:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9392:                     $match = 1;
1.275     raeburn  9393:                 }
                   9394:             }
                   9395:             if (defined($$types{'previous'})) {
1.609     raeburn  9396:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9397:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9398:                     $match = 1;
1.275     raeburn  9399:                 }
                   9400:             }
                   9401:             if (defined($$types{'future'})) {
1.609     raeburn  9402:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9403:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9404:                     $match = 1;
1.275     raeburn  9405:                 }
                   9406:             }
1.609     raeburn  9407:             if ($match) {
                   9408:                 push(@{$seclists{$student}},$section);
                   9409:                 if (ref($userdata) eq 'HASH') {
                   9410:                     $$userdata{$student} = $$classlist{$student};
                   9411:                 }
                   9412:                 if (ref($statushash) eq 'HASH') {
                   9413:                     $statushash->{$student}{'st'}{$section} = $status;
                   9414:                 }
1.288     raeburn  9415:             }
1.275     raeburn  9416:         }
                   9417:     }
1.412     raeburn  9418:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9419:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9420:         my $now = time;
1.609     raeburn  9421:         my %displaystatus = ( previous => 'Expired',
                   9422:                               active   => 'Active',
                   9423:                               future   => 'Future',
                   9424:                             );
1.1075.2.36  raeburn  9425:         my (%nothide,@possdoms);
1.630     raeburn  9426:         if ($hidepriv) {
                   9427:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9428:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9429:                 if ($user !~ /:/) {
                   9430:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9431:                 } else {
                   9432:                     $nothide{$user} = 1;
                   9433:                 }
                   9434:             }
1.1075.2.36  raeburn  9435:             my @possdoms = ($cdom);
                   9436:             if ($coursehash{'checkforpriv'}) {
                   9437:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9438:             }
1.630     raeburn  9439:         }
1.439     raeburn  9440:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9441:             my $match = 0;
1.412     raeburn  9442:             my $secmatch = 0;
1.439     raeburn  9443:             my $status;
1.412     raeburn  9444:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9445:             $user =~ s/:$//;
1.439     raeburn  9446:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9447:             if ($end == -1 || $start == -1) {
                   9448:                 next;
                   9449:             }
                   9450:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9451:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9452:                 my ($uname,$udom) = split(/:/,$user);
                   9453:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9454:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9455:                         $secmatch = 1;
                   9456:                     } elsif ($usec eq '') {
1.420     albertel 9457:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9458:                             $secmatch = 1;
                   9459:                         }
                   9460:                     } else {
                   9461:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9462:                             $secmatch = 1;
                   9463:                         }
                   9464:                     }
                   9465:                     if (!$secmatch) {
                   9466:                         next;
                   9467:                     }
1.288     raeburn  9468:                 }
1.419     raeburn  9469:                 if ($usec eq '') {
                   9470:                     $usec = 'none';
                   9471:                 }
1.275     raeburn  9472:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9473:                     if ($hidepriv) {
1.1075.2.36  raeburn  9474:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9475:                             (!$nothide{$uname.':'.$udom})) {
                   9476:                             next;
                   9477:                         }
                   9478:                     }
1.503     raeburn  9479:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9480:                         $status = 'previous';
                   9481:                     } elsif ($start > $now) {
                   9482:                         $status = 'future';
                   9483:                     } else {
                   9484:                         $status = 'active';
                   9485:                     }
1.277     albertel 9486:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9487:                         if ($status eq $type) {
1.420     albertel 9488:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9489:                                 push(@{$$users{$role}{$user}},$type);
                   9490:                             }
1.288     raeburn  9491:                             $match = 1;
                   9492:                         }
                   9493:                     }
1.419     raeburn  9494:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9495:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9496: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9497:                         }
1.420     albertel 9498:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9499:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9500:                         }
1.609     raeburn  9501:                         if (ref($statushash) eq 'HASH') {
                   9502:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9503:                         }
1.275     raeburn  9504:                     }
                   9505:                 }
                   9506:             }
                   9507:         }
1.290     albertel 9508:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9509:             if ((defined($cdom)) && (defined($cnum))) {
                   9510:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9511:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9512:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9513:                     next if ($owner eq '');
                   9514:                     my ($ownername,$ownerdom);
                   9515:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9516:                         $ownername = $1;
                   9517:                         $ownerdom = $2;
                   9518:                     } else {
                   9519:                         $ownername = $owner;
                   9520:                         $ownerdom = $cdom;
                   9521:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9522:                     }
                   9523:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9524:                     if (defined($userdata) && 
1.609     raeburn  9525: 			!exists($$userdata{$owner})) {
                   9526: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9527:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9528:                             push(@{$seclists{$owner}},'none');
                   9529:                         }
                   9530:                         if (ref($statushash) eq 'HASH') {
                   9531:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9532:                         }
1.290     albertel 9533: 		    }
1.279     raeburn  9534:                 }
                   9535:             }
                   9536:         }
1.419     raeburn  9537:         foreach my $user (keys(%seclists)) {
                   9538:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9539:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9540:         }
1.275     raeburn  9541:     }
                   9542:     return;
                   9543: }
                   9544: 
1.288     raeburn  9545: sub get_user_info {
                   9546:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9547:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9548: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9549:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9550:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9551:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9552:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9553:     return;
                   9554: }
1.275     raeburn  9555: 
1.472     raeburn  9556: ###############################################
                   9557: 
                   9558: =pod
                   9559: 
                   9560: =item * &get_user_quota()
                   9561: 
1.1075.2.41  raeburn  9562: Retrieves quota assigned for storage of user files.
                   9563: Default is to report quota for portfolio files.
1.472     raeburn  9564: 
                   9565: Incoming parameters:
                   9566: 1. user's username
                   9567: 2. user's domain
1.1075.2.41  raeburn  9568: 3. quota name - portfolio, author, or course
                   9569:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9570: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9571:    course
1.472     raeburn  9572: 
                   9573: Returns:
1.1075.2.58  raeburn  9574: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9575: 2. (Optional) Type of setting: custom or default
                   9576:    (individually assigned or default for user's 
                   9577:    institutional status).
                   9578: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9579:    or student - types as defined in localenroll::inst_usertypes 
                   9580:    for user's domain, which determines default quota for user.
                   9581: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9582: 
                   9583: If a value has been stored in the user's environment, 
1.536     raeburn  9584: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9585: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9586: 
                   9587: =cut
                   9588: 
                   9589: ###############################################
                   9590: 
                   9591: 
                   9592: sub get_user_quota {
1.1075.2.42  raeburn  9593:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9594:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9595:     if (!defined($udom)) {
                   9596:         $udom = $env{'user.domain'};
                   9597:     }
                   9598:     if (!defined($uname)) {
                   9599:         $uname = $env{'user.name'};
                   9600:     }
                   9601:     if (($udom eq '' || $uname eq '') ||
                   9602:         ($udom eq 'public') && ($uname eq 'public')) {
                   9603:         $quota = 0;
1.536     raeburn  9604:         $quotatype = 'default';
                   9605:         $defquota = 0; 
1.472     raeburn  9606:     } else {
1.536     raeburn  9607:         my $inststatus;
1.1075.2.41  raeburn  9608:         if ($quotaname eq 'course') {
                   9609:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9610:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9611:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9612:             } else {
                   9613:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9614:                 $quota = $cenv{'internal.uploadquota'};
                   9615:             }
1.536     raeburn  9616:         } else {
1.1075.2.41  raeburn  9617:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9618:                 if ($quotaname eq 'author') {
                   9619:                     $quota = $env{'environment.authorquota'};
                   9620:                 } else {
                   9621:                     $quota = $env{'environment.portfolioquota'};
                   9622:                 }
                   9623:                 $inststatus = $env{'environment.inststatus'};
                   9624:             } else {
                   9625:                 my %userenv = 
                   9626:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9627:                                          'authorquota','inststatus'],$udom,$uname);
                   9628:                 my ($tmp) = keys(%userenv);
                   9629:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9630:                     if ($quotaname eq 'author') {
                   9631:                         $quota = $userenv{'authorquota'};
                   9632:                     } else {
                   9633:                         $quota = $userenv{'portfolioquota'};
                   9634:                     }
                   9635:                     $inststatus = $userenv{'inststatus'};
                   9636:                 } else {
                   9637:                     undef(%userenv);
                   9638:                 }
                   9639:             }
                   9640:         }
                   9641:         if ($quota eq '' || wantarray) {
                   9642:             if ($quotaname eq 'course') {
                   9643:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9644:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9645:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9646:                     $defquota = $domdefs{$crstype.'quota'};
                   9647:                 }
                   9648:                 if ($defquota eq '') {
                   9649:                     $defquota = 500;
                   9650:                 }
1.1075.2.41  raeburn  9651:             } else {
                   9652:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9653:             }
                   9654:             if ($quota eq '') {
                   9655:                 $quota = $defquota;
                   9656:                 $quotatype = 'default';
                   9657:             } else {
                   9658:                 $quotatype = 'custom';
                   9659:             }
1.472     raeburn  9660:         }
                   9661:     }
1.536     raeburn  9662:     if (wantarray) {
                   9663:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9664:     } else {
                   9665:         return $quota;
                   9666:     }
1.472     raeburn  9667: }
                   9668: 
                   9669: ###############################################
                   9670: 
                   9671: =pod
                   9672: 
                   9673: =item * &default_quota()
                   9674: 
1.536     raeburn  9675: Retrieves default quota assigned for storage of user portfolio files,
                   9676: given an (optional) user's institutional status.
1.472     raeburn  9677: 
                   9678: Incoming parameters:
1.1075.2.42  raeburn  9679: 
1.472     raeburn  9680: 1. domain
1.536     raeburn  9681: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9682:    status types (e.g., faculty, staff, student etc.)
                   9683:    which apply to the user for whom the default is being retrieved.
                   9684:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9685:    default quota will be returned.
                   9686: 3.  quota name - portfolio, author, or course
                   9687:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9688: 
                   9689: Returns:
1.1075.2.42  raeburn  9690: 
1.1075.2.58  raeburn  9691: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9692: 2. (Optional) institutional type which determined the value of the
                   9693:    default quota.
1.472     raeburn  9694: 
                   9695: If a value has been stored in the domain's configuration db,
                   9696: it will return that, otherwise it returns 20 (for backwards 
                   9697: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9698: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9699: 
1.536     raeburn  9700: If the user's status includes multiple types (e.g., staff and student),
                   9701: the largest default quota which applies to the user determines the
                   9702: default quota returned.
                   9703: 
1.472     raeburn  9704: =cut
                   9705: 
                   9706: ###############################################
                   9707: 
                   9708: 
                   9709: sub default_quota {
1.1075.2.41  raeburn  9710:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9711:     my ($defquota,$settingstatus);
                   9712:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9713:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9714:     my $key = 'defaultquota';
                   9715:     if ($quotaname eq 'author') {
                   9716:         $key = 'authorquota';
                   9717:     }
1.622     raeburn  9718:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9719:         if ($inststatus ne '') {
1.765     raeburn  9720:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9721:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9722:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9723:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9724:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9725:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9726:                             $settingstatus = $item;
1.1075.2.41  raeburn  9727:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9728:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9729:                             $settingstatus = $item;
                   9730:                         }
                   9731:                     }
1.1075.2.41  raeburn  9732:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9733:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9734:                         if ($defquota eq '') {
                   9735:                             $defquota = $quotahash{'quotas'}{$item};
                   9736:                             $settingstatus = $item;
                   9737:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9738:                             $defquota = $quotahash{'quotas'}{$item};
                   9739:                             $settingstatus = $item;
                   9740:                         }
1.536     raeburn  9741:                     }
                   9742:                 }
                   9743:             }
                   9744:         }
                   9745:         if ($defquota eq '') {
1.1075.2.41  raeburn  9746:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9747:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9748:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9749:                 $defquota = $quotahash{'quotas'}{'default'};
                   9750:             }
1.536     raeburn  9751:             $settingstatus = 'default';
1.1075.2.42  raeburn  9752:             if ($defquota eq '') {
                   9753:                 if ($quotaname eq 'author') {
                   9754:                     $defquota = 500;
                   9755:                 }
                   9756:             }
1.536     raeburn  9757:         }
                   9758:     } else {
                   9759:         $settingstatus = 'default';
1.1075.2.41  raeburn  9760:         if ($quotaname eq 'author') {
                   9761:             $defquota = 500;
                   9762:         } else {
                   9763:             $defquota = 20;
                   9764:         }
1.536     raeburn  9765:     }
                   9766:     if (wantarray) {
                   9767:         return ($defquota,$settingstatus);
1.472     raeburn  9768:     } else {
1.536     raeburn  9769:         return $defquota;
1.472     raeburn  9770:     }
                   9771: }
                   9772: 
1.1075.2.41  raeburn  9773: ###############################################
                   9774: 
                   9775: =pod
                   9776: 
1.1075.2.42  raeburn  9777: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9778: 
                   9779: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9780: of existing file within authoring space will cause quota for the authoring
                   9781: space to be exceeded.
                   9782: 
                   9783: Same, if upload of a file directly to a course/community via Course Editor
                   9784: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9785: 
1.1075.2.61  raeburn  9786: Inputs: 7 
1.1075.2.42  raeburn  9787: 1. username or coursenum
1.1075.2.41  raeburn  9788: 2. domain
1.1075.2.42  raeburn  9789: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9790: 4. filename of file for which action is being requested
                   9791: 5. filesize (kB) of file
                   9792: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9793: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9794: 
                   9795: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9796:          otherwise return null.
                   9797: 
1.1075.2.42  raeburn  9798: =back
                   9799: 
1.1075.2.41  raeburn  9800: =cut
                   9801: 
1.1075.2.42  raeburn  9802: sub excess_filesize_warning {
1.1075.2.59  raeburn  9803:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9804:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9805:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9806:     if ($context eq 'author') {
                   9807:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9808:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9809:     } else {
                   9810:         foreach my $subdir ('docs','supplemental') {
                   9811:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9812:         }
                   9813:     }
1.1075.2.41  raeburn  9814:     $disk_quota = int($disk_quota * 1000);
                   9815:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9816:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9817:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9818:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9819:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9820:                             $disk_quota,$current_disk_usage).
                   9821:                '</p>';
                   9822:     }
                   9823:     return;
                   9824: }
                   9825: 
                   9826: ###############################################
                   9827: 
                   9828: 
1.384     raeburn  9829: sub get_secgrprole_info {
                   9830:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9831:     my %sections_count = &get_sections($cdom,$cnum);
                   9832:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9833:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9834:     my @groups = sort(keys(%curr_groups));
                   9835:     my $allroles = [];
                   9836:     my $rolehash;
                   9837:     my $accesshash = {
                   9838:                      active => 'Currently has access',
                   9839:                      future => 'Will have future access',
                   9840:                      previous => 'Previously had access',
                   9841:                   };
                   9842:     if ($needroles) {
                   9843:         $rolehash = {'all' => 'all'};
1.385     albertel 9844:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9845: 	if (&Apache::lonnet::error(%user_roles)) {
                   9846: 	    undef(%user_roles);
                   9847: 	}
                   9848:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9849:             my ($role)=split(/\:/,$item,2);
                   9850:             if ($role eq 'cr') { next; }
                   9851:             if ($role =~ /^cr/) {
                   9852:                 $$rolehash{$role} = (split('/',$role))[3];
                   9853:             } else {
                   9854:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9855:             }
                   9856:         }
                   9857:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9858:             push(@{$allroles},$key);
                   9859:         }
                   9860:         push (@{$allroles},'st');
                   9861:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9862:     }
                   9863:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9864: }
                   9865: 
1.555     raeburn  9866: sub user_picker {
1.1075.2.127  raeburn  9867:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9868:     my $currdom = $dom;
1.1075.2.114  raeburn  9869:     my @alldoms = &Apache::lonnet::all_domains();
                   9870:     if (@alldoms == 1) {
                   9871:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9872:                                                ['directorysrch'],$alldoms[0]);
                   9873:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9874:         my $showdom = $domdesc;
                   9875:         if ($showdom eq '') {
                   9876:             $showdom = $dom;
                   9877:         }
                   9878:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9879:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9880:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9881:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9882:             }
                   9883:         }
                   9884:     }
1.555     raeburn  9885:     my %curr_selected = (
                   9886:                         srchin => 'dom',
1.580     raeburn  9887:                         srchby => 'lastname',
1.555     raeburn  9888:                       );
                   9889:     my $srchterm;
1.625     raeburn  9890:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9891:         if ($srch->{'srchby'} ne '') {
                   9892:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9893:         }
                   9894:         if ($srch->{'srchin'} ne '') {
                   9895:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9896:         }
                   9897:         if ($srch->{'srchtype'} ne '') {
                   9898:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9899:         }
                   9900:         if ($srch->{'srchdomain'} ne '') {
                   9901:             $currdom = $srch->{'srchdomain'};
                   9902:         }
                   9903:         $srchterm = $srch->{'srchterm'};
                   9904:     }
1.1075.2.98  raeburn  9905:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9906:                     'usr'       => 'Search criteria',
1.563     raeburn  9907:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9908:                     'uname'     => 'username',
                   9909:                     'lastname'  => 'last name',
1.555     raeburn  9910:                     'lastfirst' => 'last name, first name',
1.558     albertel 9911:                     'crs'       => 'in this course',
1.576     raeburn  9912:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9913:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9914:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9915:                     'exact'     => 'is',
                   9916:                     'contains'  => 'contains',
1.569     raeburn  9917:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9918:                                        );
                   9919:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9920:                     'youm'      => "You must include some text to search for.",
                   9921:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9922:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9923:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9924:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9925:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9926:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9927:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9928:                                        );
1.1075.2.98  raeburn  9929:     &html_escape(\%html_lt);
                   9930:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9931:     my $domform;
1.1075.2.126  raeburn  9932:     my $allow_blank = 1;
1.1075.2.115  raeburn  9933:     if ($fixeddom) {
1.1075.2.126  raeburn  9934:         $allow_blank = 0;
                   9935:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9936:     } else {
1.1075.2.126  raeburn  9937:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9938:     }
1.563     raeburn  9939:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9940: 
                   9941:     my @srchins = ('crs','dom','alc','instd');
                   9942: 
                   9943:     foreach my $option (@srchins) {
                   9944:         # FIXME 'alc' option unavailable until 
                   9945:         #       loncreateuser::print_user_query_page()
                   9946:         #       has been completed.
                   9947:         next if ($option eq 'alc');
1.880     raeburn  9948:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9949:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9950:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9951:         if ($curr_selected{'srchin'} eq $option) {
                   9952:             $srchinsel .= ' 
1.1075.2.98  raeburn  9953:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9954:         } else {
                   9955:             $srchinsel .= '
1.1075.2.98  raeburn  9956:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9957:         }
1.555     raeburn  9958:     }
1.563     raeburn  9959:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9960: 
                   9961:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9962:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9963:         if ($curr_selected{'srchby'} eq $option) {
                   9964:             $srchbysel .= '
1.1075.2.98  raeburn  9965:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9966:         } else {
                   9967:             $srchbysel .= '
1.1075.2.98  raeburn  9968:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9969:          }
                   9970:     }
                   9971:     $srchbysel .= "\n  </select>\n";
                   9972: 
                   9973:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9974:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9975:         if ($curr_selected{'srchtype'} eq $option) {
                   9976:             $srchtypesel .= '
1.1075.2.98  raeburn  9977:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9978:         } else {
                   9979:             $srchtypesel .= '
1.1075.2.98  raeburn  9980:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9981:         }
                   9982:     }
                   9983:     $srchtypesel .= "\n  </select>\n";
                   9984: 
1.558     albertel 9985:     my ($newuserscript,$new_user_create);
1.994     raeburn  9986:     my $context_dom = $env{'request.role.domain'};
                   9987:     if ($context eq 'requestcrs') {
                   9988:         if ($env{'form.coursedom'} ne '') { 
                   9989:             $context_dom = $env{'form.coursedom'};
                   9990:         }
                   9991:     }
1.556     raeburn  9992:     if ($forcenewuser) {
1.576     raeburn  9993:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9994:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9995:                 if ($cancreate) {
                   9996:                     $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>';
                   9997:                 } else {
1.799     bisitz   9998:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9999:                     my %usertypetext = (
                   10000:                         official   => 'institutional',
                   10001:                         unofficial => 'non-institutional',
                   10002:                     );
1.799     bisitz   10003:                     $new_user_create = '<p class="LC_warning">'
                   10004:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10005:                                       .' '
                   10006:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10007:                                           ,'<a href="'.$helplink.'">','</a>')
                   10008:                                       .'</p><br />';
1.627     raeburn  10009:                 }
1.576     raeburn  10010:             }
                   10011:         }
                   10012: 
1.556     raeburn  10013:         $newuserscript = <<"ENDSCRIPT";
                   10014: 
1.570     raeburn  10015: function setSearch(createnew,callingForm) {
1.556     raeburn  10016:     if (createnew == 1) {
1.570     raeburn  10017:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10018:             if (callingForm.srchby.options[i].value == 'uname') {
                   10019:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10020:             }
                   10021:         }
1.570     raeburn  10022:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10023:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10024: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10025:             }
                   10026:         }
1.570     raeburn  10027:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10028:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10029:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10030:             }
                   10031:         }
1.570     raeburn  10032:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10033:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10034:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10035:             }
                   10036:         }
                   10037:     }
                   10038: }
                   10039: ENDSCRIPT
1.558     albertel 10040: 
1.556     raeburn  10041:     }
                   10042: 
1.555     raeburn  10043:     my $output = <<"END_BLOCK";
1.556     raeburn  10044: <script type="text/javascript">
1.824     bisitz   10045: // <![CDATA[
1.570     raeburn  10046: function validateEntry(callingForm) {
1.558     albertel 10047: 
1.556     raeburn  10048:     var checkok = 1;
1.558     albertel 10049:     var srchin;
1.570     raeburn  10050:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10051: 	if ( callingForm.srchin[i].checked ) {
                   10052: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10053: 	}
                   10054:     }
                   10055: 
1.570     raeburn  10056:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10057:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10058:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10059:     var srchterm =  callingForm.srchterm.value;
                   10060:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10061:     var msg = "";
                   10062: 
                   10063:     if (srchterm == "") {
                   10064:         checkok = 0;
1.1075.2.98  raeburn  10065:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10066:     }
                   10067: 
1.569     raeburn  10068:     if (srchtype== 'begins') {
                   10069:         if (srchterm.length < 2) {
                   10070:             checkok = 0;
1.1075.2.98  raeburn  10071:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10072:         }
                   10073:     }
                   10074: 
1.556     raeburn  10075:     if (srchtype== 'contains') {
                   10076:         if (srchterm.length < 3) {
                   10077:             checkok = 0;
1.1075.2.98  raeburn  10078:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10079:         }
                   10080:     }
                   10081:     if (srchin == 'instd') {
                   10082:         if (srchdomain == '') {
                   10083:             checkok = 0;
1.1075.2.98  raeburn  10084:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10085:         }
                   10086:     }
                   10087:     if (srchin == 'dom') {
                   10088:         if (srchdomain == '') {
                   10089:             checkok = 0;
1.1075.2.98  raeburn  10090:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10091:         }
                   10092:     }
                   10093:     if (srchby == 'lastfirst') {
                   10094:         if (srchterm.indexOf(",") == -1) {
                   10095:             checkok = 0;
1.1075.2.98  raeburn  10096:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10097:         }
                   10098:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10099:             checkok = 0;
1.1075.2.98  raeburn  10100:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10101:         }
                   10102:     }
                   10103:     if (checkok == 0) {
1.1075.2.98  raeburn  10104:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10105:         return;
                   10106:     }
                   10107:     if (checkok == 1) {
1.570     raeburn  10108:         callingForm.submit();
1.556     raeburn  10109:     }
                   10110: }
                   10111: 
                   10112: $newuserscript
                   10113: 
1.824     bisitz   10114: // ]]>
1.556     raeburn  10115: </script>
1.558     albertel 10116: 
                   10117: $new_user_create
                   10118: 
1.555     raeburn  10119: END_BLOCK
1.558     albertel 10120: 
1.876     raeburn  10121:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10122:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10123:                $domform.
                   10124:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10125:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10126:                $srchbysel.
                   10127:                $srchtypesel. 
                   10128:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10129:                $srchinsel.
                   10130:                &Apache::lonhtmlcommon::row_closure(1). 
                   10131:                &Apache::lonhtmlcommon::end_pick_box().
                   10132:                '<br />';
1.1075.2.114  raeburn  10133:     return ($output,1);
1.555     raeburn  10134: }
                   10135: 
1.612     raeburn  10136: sub user_rule_check {
1.615     raeburn  10137:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10138:     my ($response,%inst_response);
1.612     raeburn  10139:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10140:         if (keys(%{$usershash}) > 1) {
                   10141:             my (%by_username,%by_id,%userdoms);
                   10142:             my $checkid;
1.612     raeburn  10143:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10144:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10145:                     $checkid = 1;
                   10146:                 }
                   10147:             }
                   10148:             foreach my $user (keys(%{$usershash})) {
                   10149:                 my ($uname,$udom) = split(/:/,$user);
                   10150:                 if ($checkid) {
                   10151:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10152:                         if ($usershash->{$user}->{'id'} ne '') {
                   10153:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10154:                             $userdoms{$udom} = 1;
                   10155:                             if (ref($inst_results) eq 'HASH') {
                   10156:                                 $inst_results->{$uname.':'.$udom} = {};
                   10157:                             }
                   10158:                         }
                   10159:                     }
                   10160:                 } else {
                   10161:                     $by_username{$udom}{$uname} = 1;
                   10162:                     $userdoms{$udom} = 1;
                   10163:                     if (ref($inst_results) eq 'HASH') {
                   10164:                         $inst_results->{$uname.':'.$udom} = {};
                   10165:                     }
                   10166:                 }
                   10167:             }
                   10168:             foreach my $udom (keys(%userdoms)) {
                   10169:                 if (!$got_rules->{$udom}) {
                   10170:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10171:                                                              ['usercreation'],$udom);
                   10172:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10173:                         foreach my $item ('username','id') {
                   10174:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10175:                                 $$curr_rules{$udom}{$item} =
                   10176:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10177:                             }
                   10178:                         }
                   10179:                     }
                   10180:                     $got_rules->{$udom} = 1;
                   10181:                 }
                   10182:             }
                   10183:             if ($checkid) {
                   10184:                 foreach my $udom (keys(%by_id)) {
                   10185:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10186:                     if ($outcome eq 'ok') {
                   10187:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10188:                             my $uname = $by_id{$udom}{$id};
                   10189:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10190:                         }
                   10191:                         if (ref($results) eq 'HASH') {
                   10192:                             foreach my $uname (keys(%{$results})) {
                   10193:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10194:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10195:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10196:                                 }
                   10197:                             }
                   10198:                         }
                   10199:                     }
1.612     raeburn  10200:                 }
1.615     raeburn  10201:             } else {
1.1075.2.99  raeburn  10202:                 foreach my $udom (keys(%by_username)) {
                   10203:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10204:                     if ($outcome eq 'ok') {
                   10205:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10206:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10207:                         }
                   10208:                         if (ref($results) eq 'HASH') {
                   10209:                             foreach my $uname (keys(%{$results})) {
                   10210:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10211:                             }
                   10212:                         }
                   10213:                     }
                   10214:                 }
1.612     raeburn  10215:             }
1.1075.2.99  raeburn  10216:         } elsif (keys(%{$usershash}) == 1) {
                   10217:             my $user = (keys(%{$usershash}))[0];
                   10218:             my ($uname,$udom) = split(/:/,$user);
                   10219:             if (($udom ne '') && ($uname ne '')) {
                   10220:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10221:                     if (ref($checks) eq 'HASH') {
                   10222:                         if (defined($checks->{'username'})) {
                   10223:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10224:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10225:                         } elsif (defined($checks->{'id'})) {
                   10226:                             if ($usershash->{$user}->{'id'} ne '') {
                   10227:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10228:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10229:                                                                   $usershash->{$user}->{'id'});
                   10230:                             } else {
                   10231:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10232:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10233:                             }
                   10234:                         }
                   10235:                     } else {
                   10236:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10237:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10238:                        return;
                   10239:                     }
                   10240:                     if (!$got_rules->{$udom}) {
                   10241:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10242:                                                                  ['usercreation'],$udom);
                   10243:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10244:                             foreach my $item ('username','id') {
                   10245:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10246:                                    $$curr_rules{$udom}{$item} =
                   10247:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10248:                                 }
                   10249:                             }
1.585     raeburn  10250:                         }
1.1075.2.99  raeburn  10251:                         $got_rules->{$udom} = 1;
1.585     raeburn  10252:                     }
                   10253:                 }
1.1075.2.99  raeburn  10254:             } else {
                   10255:                 return;
                   10256:             }
                   10257:         } else {
                   10258:             return;
                   10259:         }
                   10260:         foreach my $user (keys(%{$usershash})) {
                   10261:             my ($uname,$udom) = split(/:/,$user);
                   10262:             next if (($udom eq '') || ($uname eq ''));
                   10263:             my $id;
                   10264:             if (ref($inst_results) eq 'HASH') {
                   10265:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10266:                     $id = $inst_results->{$user}->{'id'};
                   10267:                 }
                   10268:             }
                   10269:             if ($id eq '') {
                   10270:                 if (ref($usershash->{$user})) {
                   10271:                     $id = $usershash->{$user}->{'id'};
                   10272:                 }
1.585     raeburn  10273:             }
1.612     raeburn  10274:             foreach my $item (keys(%{$checks})) {
                   10275:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10276:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10277:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10278:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10279:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10280:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10281:                                 if ($rule_check{$rule}) {
                   10282:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10283:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10284:                                         if (ref($inst_results) eq 'HASH') {
                   10285:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10286:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10287:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10288:                                                 } elsif ($item eq 'id') {
                   10289:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10290:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10291:                                                     }
1.615     raeburn  10292:                                                 }
1.612     raeburn  10293:                                             }
                   10294:                                         }
1.615     raeburn  10295:                                     }
                   10296:                                     last;
1.585     raeburn  10297:                                 }
                   10298:                             }
                   10299:                         }
                   10300:                     }
                   10301:                 }
                   10302:             }
                   10303:         }
                   10304:     }
1.612     raeburn  10305:     return;
                   10306: }
                   10307: 
                   10308: sub user_rule_formats {
                   10309:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10310:     my %text = ( 
                   10311:                  'username' => 'Usernames',
                   10312:                  'id'       => 'IDs',
                   10313:                );
                   10314:     my $output;
                   10315:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10316:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10317:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10318:             $output = '<br />'.
                   10319:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10320:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10321:                       ' <ul>';
1.612     raeburn  10322:             foreach my $rule (@{$ruleorder}) {
                   10323:                 if (ref($curr_rules) eq 'ARRAY') {
                   10324:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10325:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10326:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10327:                                         $rules->{$rule}{'desc'}.'</li>';
                   10328:                         }
                   10329:                     }
                   10330:                 }
                   10331:             }
                   10332:             $output .= '</ul>';
                   10333:         }
                   10334:     }
                   10335:     return $output;
                   10336: }
                   10337: 
                   10338: sub instrule_disallow_msg {
1.615     raeburn  10339:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10340:     my $response;
                   10341:     my %text = (
                   10342:                   item   => 'username',
                   10343:                   items  => 'usernames',
                   10344:                   match  => 'matches',
                   10345:                   do     => 'does',
                   10346:                   action => 'a username',
                   10347:                   one    => 'one',
                   10348:                );
                   10349:     if ($count > 1) {
                   10350:         $text{'item'} = 'usernames';
                   10351:         $text{'match'} ='match';
                   10352:         $text{'do'} = 'do';
                   10353:         $text{'action'} = 'usernames',
                   10354:         $text{'one'} = 'ones';
                   10355:     }
                   10356:     if ($checkitem eq 'id') {
                   10357:         $text{'items'} = 'IDs';
                   10358:         $text{'item'} = 'ID';
                   10359:         $text{'action'} = 'an ID';
1.615     raeburn  10360:         if ($count > 1) {
                   10361:             $text{'item'} = 'IDs';
                   10362:             $text{'action'} = 'IDs';
                   10363:         }
1.612     raeburn  10364:     }
1.674     bisitz   10365:     $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  10366:     if ($mode eq 'upload') {
                   10367:         if ($checkitem eq 'username') {
                   10368:             $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'}.");
                   10369:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10370:             $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  10371:         }
1.669     raeburn  10372:     } elsif ($mode eq 'selfcreate') {
                   10373:         if ($checkitem eq 'id') {
                   10374:             $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.");
                   10375:         }
1.615     raeburn  10376:     } else {
                   10377:         if ($checkitem eq 'username') {
                   10378:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10379:         } elsif ($checkitem eq 'id') {
                   10380:             $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.");
                   10381:         }
1.612     raeburn  10382:     }
                   10383:     return $response;
1.585     raeburn  10384: }
                   10385: 
1.624     raeburn  10386: sub personal_data_fieldtitles {
                   10387:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10388:                         id => 'Student/Employee ID',
                   10389:                         permanentemail => 'E-mail address',
                   10390:                         lastname => 'Last Name',
                   10391:                         firstname => 'First Name',
                   10392:                         middlename => 'Middle Name',
                   10393:                         generation => 'Generation',
                   10394:                         gen => 'Generation',
1.765     raeburn  10395:                         inststatus => 'Affiliation',
1.624     raeburn  10396:                    );
                   10397:     return %fieldtitles;
                   10398: }
                   10399: 
1.642     raeburn  10400: sub sorted_inst_types {
                   10401:     my ($dom) = @_;
1.1075.2.70  raeburn  10402:     my ($usertypes,$order);
                   10403:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10404:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10405:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10406:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10407:     } else {
                   10408:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10409:     }
1.642     raeburn  10410:     my $othertitle = &mt('All users');
                   10411:     if ($env{'request.course.id'}) {
1.668     raeburn  10412:         $othertitle  = &mt('Any users');
1.642     raeburn  10413:     }
                   10414:     my @types;
                   10415:     if (ref($order) eq 'ARRAY') {
                   10416:         @types = @{$order};
                   10417:     }
                   10418:     if (@types == 0) {
                   10419:         if (ref($usertypes) eq 'HASH') {
                   10420:             @types = sort(keys(%{$usertypes}));
                   10421:         }
                   10422:     }
                   10423:     if (keys(%{$usertypes}) > 0) {
                   10424:         $othertitle = &mt('Other users');
                   10425:     }
                   10426:     return ($othertitle,$usertypes,\@types);
                   10427: }
                   10428: 
1.645     raeburn  10429: sub get_institutional_codes {
1.1075.2.157! raeburn  10430:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  10431: # Get complete list of course sections to update
                   10432:     my @currsections = ();
                   10433:     my @currxlists = ();
1.1075.2.157! raeburn  10434:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  10435:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157! raeburn  10436:     my $crskey = $crs.':'.$coursecode;
        !          10437:     @{$unclutteredsec{$crskey}} = ();
        !          10438:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  10439: 
                   10440:     if ($$settings{'internal.sectionnums'} ne '') {
                   10441:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10442:     }
                   10443: 
                   10444:     if ($$settings{'internal.crosslistings'} ne '') {
                   10445:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10446:     }
                   10447: 
                   10448:     if (@currxlists > 0) {
1.1075.2.157! raeburn  10449:         foreach my $xl (@currxlists) {
        !          10450:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  10451:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10452:                     push(@{$allcourses},$1);
1.645     raeburn  10453:                     $$LC_code{$1} = $2;
                   10454:                 }
                   10455:             }
                   10456:         }
                   10457:     }
1.1075.2.157! raeburn  10458: 
1.645     raeburn  10459:     if (@currsections > 0) {
1.1075.2.157! raeburn  10460:         foreach my $sec (@currsections) {
        !          10461:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
        !          10462:                 my $instsec = $1;
1.645     raeburn  10463:                 my $lc_sec = $2;
1.1075.2.157! raeburn  10464:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
        !          10465:                     push(@{$unclutteredsec{$crskey}},$instsec);
        !          10466:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
        !          10467:                 }
        !          10468:             }
        !          10469:         }
        !          10470:     }
        !          10471: 
        !          10472:     if (@{$unclutteredsec{$crskey}} > 0) {
        !          10473:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
        !          10474:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
        !          10475:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
        !          10476:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
        !          10477:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  10478:                     push(@{$allcourses},$sec);
1.1075.2.157! raeburn  10479:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  10480:                 }
                   10481:             }
                   10482:         }
                   10483:     }
                   10484:     return;
                   10485: }
                   10486: 
1.971     raeburn  10487: sub get_standard_codeitems {
                   10488:     return ('Year','Semester','Department','Number','Section');
                   10489: }
                   10490: 
1.112     bowersj2 10491: =pod
                   10492: 
1.780     raeburn  10493: =head1 Slot Helpers
                   10494: 
                   10495: =over 4
                   10496: 
                   10497: =item * sorted_slots()
                   10498: 
1.1040    raeburn  10499: Sorts an array of slot names in order of an optional sort key,
                   10500: default sort is by slot start time (earliest first). 
1.780     raeburn  10501: 
                   10502: Inputs:
                   10503: 
                   10504: =over 4
                   10505: 
                   10506: slotsarr  - Reference to array of unsorted slot names.
                   10507: 
                   10508: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10509: 
1.1040    raeburn  10510: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10511: 
1.549     albertel 10512: =back
                   10513: 
1.780     raeburn  10514: Returns:
                   10515: 
                   10516: =over 4
                   10517: 
1.1040    raeburn  10518: sorted   - An array of slot names sorted by a specified sort key 
                   10519:            (default sort key is start time of the slot).
1.780     raeburn  10520: 
                   10521: =back
                   10522: 
                   10523: =cut
                   10524: 
                   10525: 
                   10526: sub sorted_slots {
1.1040    raeburn  10527:     my ($slotsarr,$slots,$sortkey) = @_;
                   10528:     if ($sortkey eq '') {
                   10529:         $sortkey = 'starttime';
                   10530:     }
1.780     raeburn  10531:     my @sorted;
                   10532:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10533:         @sorted =
                   10534:             sort {
                   10535:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10536:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10537:                      }
                   10538:                      if (ref($slots->{$a})) { return -1;}
                   10539:                      if (ref($slots->{$b})) { return 1;}
                   10540:                      return 0;
                   10541:                  } @{$slotsarr};
                   10542:     }
                   10543:     return @sorted;
                   10544: }
                   10545: 
1.1040    raeburn  10546: =pod
                   10547: 
                   10548: =item * get_future_slots()
                   10549: 
                   10550: Inputs:
                   10551: 
                   10552: =over 4
                   10553: 
                   10554: cnum - course number
                   10555: 
                   10556: cdom - course domain
                   10557: 
                   10558: now - current UNIX time
                   10559: 
                   10560: symb - optional symb
                   10561: 
                   10562: =back
                   10563: 
                   10564: Returns:
                   10565: 
                   10566: =over 4
                   10567: 
                   10568: sorted_reservable - ref to array of student_schedulable slots currently 
                   10569:                     reservable, ordered by end date of reservation period.
                   10570: 
                   10571: reservable_now - ref to hash of student_schedulable slots currently
                   10572:                  reservable.
                   10573: 
                   10574:     Keys in inner hash are:
                   10575:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10576:     (b) endreserve: end date of reservation period.
                   10577:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10578:         selected.
1.1040    raeburn  10579: 
                   10580: sorted_future - ref to array of student_schedulable slots reservable in
                   10581:                 the future, ordered by start date of reservation period.
                   10582: 
                   10583: future_reservable - ref to hash of student_schedulable slots reservable
                   10584:                     in the future.
                   10585: 
                   10586:     Keys in inner hash are:
                   10587:     (a) symb: either blank or symb to which slot use is restricted.
                   10588:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10589:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10590:         selected.
1.1040    raeburn  10591: 
                   10592: =back
                   10593: 
                   10594: =cut
                   10595: 
                   10596: sub get_future_slots {
                   10597:     my ($cnum,$cdom,$now,$symb) = @_;
                   10598:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10599:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10600:     foreach my $slot (keys(%slots)) {
                   10601:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10602:         if ($symb) {
                   10603:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10604:                      ($slots{$slot}->{'symb'} ne $symb));
                   10605:         }
                   10606:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10607:             ($slots{$slot}->{'endtime'} > $now)) {
                   10608:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10609:                 my $userallowed = 0;
                   10610:                 if ($slots{$slot}->{'allowedsections'}) {
                   10611:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10612:                     if (!defined($env{'request.role.sec'})
                   10613:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10614:                         $userallowed=1;
                   10615:                     } else {
                   10616:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10617:                             $userallowed=1;
                   10618:                         }
                   10619:                     }
                   10620:                     unless ($userallowed) {
                   10621:                         if (defined($env{'request.course.groups'})) {
                   10622:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10623:                             foreach my $group (@groups) {
                   10624:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10625:                                     $userallowed=1;
                   10626:                                     last;
                   10627:                                 }
                   10628:                             }
                   10629:                         }
                   10630:                     }
                   10631:                 }
                   10632:                 if ($slots{$slot}->{'allowedusers'}) {
                   10633:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10634:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10635:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10636:                         $userallowed = 1;
                   10637:                     }
                   10638:                 }
                   10639:                 next unless($userallowed);
                   10640:             }
                   10641:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10642:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10643:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10644:             my $uniqueperiod;
                   10645:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10646:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10647:             }
1.1040    raeburn  10648:             if (($startreserve < $now) &&
                   10649:                 (!$endreserve || $endreserve > $now)) {
                   10650:                 my $lastres = $endreserve;
                   10651:                 if (!$lastres) {
                   10652:                     $lastres = $slots{$slot}->{'starttime'};
                   10653:                 }
                   10654:                 $reservable_now{$slot} = {
                   10655:                                            symb       => $symb,
1.1075.2.104  raeburn  10656:                                            endreserve => $lastres,
                   10657:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10658:                                          };
                   10659:             } elsif (($startreserve > $now) &&
                   10660:                      (!$endreserve || $endreserve > $startreserve)) {
                   10661:                 $future_reservable{$slot} = {
                   10662:                                               symb         => $symb,
1.1075.2.104  raeburn  10663:                                               startreserve => $startreserve,
                   10664:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10665:                                             };
                   10666:             }
                   10667:         }
                   10668:     }
                   10669:     my @unsorted_reservable = keys(%reservable_now);
                   10670:     if (@unsorted_reservable > 0) {
                   10671:         @sorted_reservable = 
                   10672:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10673:     }
                   10674:     my @unsorted_future = keys(%future_reservable);
                   10675:     if (@unsorted_future > 0) {
                   10676:         @sorted_future =
                   10677:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10678:     }
                   10679:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10680: }
1.780     raeburn  10681: 
                   10682: =pod
                   10683: 
1.1057    foxr     10684: =back
                   10685: 
1.549     albertel 10686: =head1 HTTP Helpers
                   10687: 
                   10688: =over 4
                   10689: 
1.648     raeburn  10690: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10691: 
1.258     albertel 10692: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10693: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10694: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10695: 
                   10696: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10697: $possible_names is an ref to an array of form element names.  As an example:
                   10698: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10699: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10700: 
                   10701: =cut
1.1       albertel 10702: 
1.6       albertel 10703: sub get_unprocessed_cgi {
1.25      albertel 10704:   my ($query,$possible_names)= @_;
1.26      matthew  10705:   # $Apache::lonxml::debug=1;
1.356     albertel 10706:   foreach my $pair (split(/&/,$query)) {
                   10707:     my ($name, $value) = split(/=/,$pair);
1.369     www      10708:     $name = &unescape($name);
1.25      albertel 10709:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10710:       $value =~ tr/+/ /;
                   10711:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10712:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10713:     }
1.16      harris41 10714:   }
1.6       albertel 10715: }
                   10716: 
1.112     bowersj2 10717: =pod
                   10718: 
1.648     raeburn  10719: =item * &cacheheader() 
1.112     bowersj2 10720: 
                   10721: returns cache-controlling header code
                   10722: 
                   10723: =cut
                   10724: 
1.7       albertel 10725: sub cacheheader {
1.258     albertel 10726:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10727:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10728:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10729:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10730:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10731:     return $output;
1.7       albertel 10732: }
                   10733: 
1.112     bowersj2 10734: =pod
                   10735: 
1.648     raeburn  10736: =item * &no_cache($r) 
1.112     bowersj2 10737: 
                   10738: specifies header code to not have cache
                   10739: 
                   10740: =cut
                   10741: 
1.9       albertel 10742: sub no_cache {
1.216     albertel 10743:     my ($r) = @_;
                   10744:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10745: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10746:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10747:     $r->no_cache(1);
                   10748:     $r->header_out("Expires" => $date);
                   10749:     $r->header_out("Pragma" => "no-cache");
1.123     www      10750: }
                   10751: 
                   10752: sub content_type {
1.181     albertel 10753:     my ($r,$type,$charset) = @_;
1.299     foxr     10754:     if ($r) {
                   10755: 	#  Note that printout.pl calls this with undef for $r.
                   10756: 	&no_cache($r);
                   10757:     }
1.258     albertel 10758:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10759:     unless ($charset) {
                   10760: 	$charset=&Apache::lonlocal::current_encoding;
                   10761:     }
                   10762:     if ($charset) { $type.='; charset='.$charset; }
                   10763:     if ($r) {
                   10764: 	$r->content_type($type);
                   10765:     } else {
                   10766: 	print("Content-type: $type\n\n");
                   10767:     }
1.9       albertel 10768: }
1.25      albertel 10769: 
1.112     bowersj2 10770: =pod
                   10771: 
1.648     raeburn  10772: =item * &add_to_env($name,$value) 
1.112     bowersj2 10773: 
1.258     albertel 10774: adds $name to the %env hash with value
1.112     bowersj2 10775: $value, if $name already exists, the entry is converted to an array
                   10776: reference and $value is added to the array.
                   10777: 
                   10778: =cut
                   10779: 
1.25      albertel 10780: sub add_to_env {
                   10781:   my ($name,$value)=@_;
1.258     albertel 10782:   if (defined($env{$name})) {
                   10783:     if (ref($env{$name})) {
1.25      albertel 10784:       #already have multiple values
1.258     albertel 10785:       push(@{ $env{$name} },$value);
1.25      albertel 10786:     } else {
                   10787:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10788:       my $first=$env{$name};
                   10789:       undef($env{$name});
                   10790:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10791:     }
                   10792:   } else {
1.258     albertel 10793:     $env{$name}=$value;
1.25      albertel 10794:   }
1.31      albertel 10795: }
1.149     albertel 10796: 
                   10797: =pod
                   10798: 
1.648     raeburn  10799: =item * &get_env_multiple($name) 
1.149     albertel 10800: 
1.258     albertel 10801: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10802: values may be defined and end up as an array ref.
                   10803: 
                   10804: returns an array of values
                   10805: 
                   10806: =cut
                   10807: 
                   10808: sub get_env_multiple {
                   10809:     my ($name) = @_;
                   10810:     my @values;
1.258     albertel 10811:     if (defined($env{$name})) {
1.149     albertel 10812:         # exists is it an array
1.258     albertel 10813:         if (ref($env{$name})) {
                   10814:             @values=@{ $env{$name} };
1.149     albertel 10815:         } else {
1.258     albertel 10816:             $values[0]=$env{$name};
1.149     albertel 10817:         }
                   10818:     }
                   10819:     return(@values);
                   10820: }
                   10821: 
1.660     raeburn  10822: sub ask_for_embedded_content {
                   10823:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10824:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10825:         %currsubfile,%unused,$rem);
1.1071    raeburn  10826:     my $counter = 0;
                   10827:     my $numnew = 0;
1.987     raeburn  10828:     my $numremref = 0;
                   10829:     my $numinvalid = 0;
                   10830:     my $numpathchg = 0;
                   10831:     my $numexisting = 0;
1.1071    raeburn  10832:     my $numunused = 0;
                   10833:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10834:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10835:     my $heading = &mt('Upload embedded files');
                   10836:     my $buttontext = &mt('Upload');
                   10837: 
1.1075.2.11  raeburn  10838:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10839:         if ($actionurl eq '/adm/dependencies') {
                   10840:             $navmap = Apache::lonnavmaps::navmap->new();
                   10841:         }
                   10842:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10843:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10844:     }
1.1075.2.35  raeburn  10845:     if (($actionurl eq '/adm/portfolio') ||
                   10846:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10847:         my $current_path='/';
                   10848:         if ($env{'form.currentpath'}) {
                   10849:             $current_path = $env{'form.currentpath'};
                   10850:         }
                   10851:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10852:             $udom = $cdom;
                   10853:             $uname = $cnum;
1.984     raeburn  10854:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10855:         } else {
                   10856:             $udom = $env{'user.domain'};
                   10857:             $uname = $env{'user.name'};
                   10858:             $url = '/userfiles/portfolio';
                   10859:         }
1.987     raeburn  10860:         $toplevel = $url.'/';
1.984     raeburn  10861:         $url .= $current_path;
                   10862:         $getpropath = 1;
1.987     raeburn  10863:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10864:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10865:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10866:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10867:         $toplevel = $url;
1.984     raeburn  10868:         if ($rest ne '') {
1.987     raeburn  10869:             $url .= $rest;
                   10870:         }
                   10871:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10872:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10873:             $url = $args->{'docs_url'};
                   10874:             $toplevel = $url;
1.1075.2.11  raeburn  10875:             if ($args->{'context'} eq 'paste') {
                   10876:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10877:                 ($path) =
                   10878:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10879:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10880:                 $fileloc =~ s{^/}{};
                   10881:             }
1.1071    raeburn  10882:         }
                   10883:     } elsif ($actionurl eq '/adm/dependencies') {
                   10884:         if ($env{'request.course.id'} ne '') {
                   10885:             if (ref($args) eq 'HASH') {
                   10886:                 $url = $args->{'docs_url'};
                   10887:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10888:                 $toplevel = $url;
                   10889:                 unless ($toplevel =~ m{^/}) {
                   10890:                     $toplevel = "/$url";
                   10891:                 }
1.1075.2.11  raeburn  10892:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10893:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10894:                     $path = $1;
                   10895:                 } else {
                   10896:                     ($path) =
                   10897:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10898:                 }
1.1075.2.79  raeburn  10899:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10900:                     $fileloc = $toplevel;
                   10901:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10902:                     my ($udom,$uname,$fname) =
                   10903:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10904:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10905:                 } else {
                   10906:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10907:                 }
1.1071    raeburn  10908:                 $fileloc =~ s{^/}{};
                   10909:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10910:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10911:             }
1.987     raeburn  10912:         }
1.1075.2.35  raeburn  10913:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10914:         $udom = $cdom;
                   10915:         $uname = $cnum;
                   10916:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10917:         $toplevel = $url;
                   10918:         $path = $url;
                   10919:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10920:         $fileloc =~ s{^/}{};
                   10921:     }
                   10922:     foreach my $file (keys(%{$allfiles})) {
                   10923:         my $embed_file;
                   10924:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10925:             $embed_file = $1;
                   10926:         } else {
                   10927:             $embed_file = $file;
                   10928:         }
1.1075.2.55  raeburn  10929:         my ($absolutepath,$cleaned_file);
                   10930:         if ($embed_file =~ m{^\w+://}) {
                   10931:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10932:             $newfiles{$cleaned_file} = 1;
                   10933:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10934:         } else {
1.1075.2.55  raeburn  10935:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10936:             if ($embed_file =~ m{^/}) {
                   10937:                 $absolutepath = $embed_file;
                   10938:             }
1.1075.2.47  raeburn  10939:             if ($cleaned_file =~ m{/}) {
                   10940:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10941:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10942:                 my $item = $fname;
                   10943:                 if ($path ne '') {
                   10944:                     $item = $path.'/'.$fname;
                   10945:                     $subdependencies{$path}{$fname} = 1;
                   10946:                 } else {
                   10947:                     $dependencies{$item} = 1;
                   10948:                 }
                   10949:                 if ($absolutepath) {
                   10950:                     $mapping{$item} = $absolutepath;
                   10951:                 } else {
                   10952:                     $mapping{$item} = $embed_file;
                   10953:                 }
                   10954:             } else {
                   10955:                 $dependencies{$embed_file} = 1;
                   10956:                 if ($absolutepath) {
1.1075.2.47  raeburn  10957:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10958:                 } else {
1.1075.2.47  raeburn  10959:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10960:                 }
                   10961:             }
1.984     raeburn  10962:         }
                   10963:     }
1.1071    raeburn  10964:     my $dirptr = 16384;
1.984     raeburn  10965:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10966:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10967:         if (($actionurl eq '/adm/portfolio') ||
                   10968:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10969:             my ($sublistref,$listerror) =
                   10970:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10971:             if (ref($sublistref) eq 'ARRAY') {
                   10972:                 foreach my $line (@{$sublistref}) {
                   10973:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10974:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10975:                 }
1.984     raeburn  10976:             }
1.987     raeburn  10977:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10978:             if (opendir(my $dir,$url.'/'.$path)) {
                   10979:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10980:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10981:             }
1.1075.2.11  raeburn  10982:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10983:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10984:                   ($args->{'context'} eq 'paste')) ||
                   10985:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10986:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10987:                 my $dir;
                   10988:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10989:                     $dir = $fileloc;
                   10990:                 } else {
                   10991:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10992:                 }
1.1071    raeburn  10993:                 if ($dir ne '') {
                   10994:                     my ($sublistref,$listerror) =
                   10995:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10996:                     if (ref($sublistref) eq 'ARRAY') {
                   10997:                         foreach my $line (@{$sublistref}) {
                   10998:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10999:                                 undef,$mtime)=split(/\&/,$line,12);
                   11000:                             unless (($testdir&$dirptr) ||
                   11001:                                     ($file_name =~ /^\.\.?$/)) {
                   11002:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11003:                             }
                   11004:                         }
                   11005:                     }
                   11006:                 }
1.984     raeburn  11007:             }
                   11008:         }
                   11009:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11010:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11011:                 my $item = $path.'/'.$file;
                   11012:                 unless ($mapping{$item} eq $item) {
                   11013:                     $pathchanges{$item} = 1;
                   11014:                 }
                   11015:                 $existing{$item} = 1;
                   11016:                 $numexisting ++;
                   11017:             } else {
                   11018:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11019:             }
                   11020:         }
1.1071    raeburn  11021:         if ($actionurl eq '/adm/dependencies') {
                   11022:             foreach my $path (keys(%currsubfile)) {
                   11023:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11024:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11025:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11026:                              next if (($rem ne '') &&
                   11027:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11028:                                        (ref($navmap) &&
                   11029:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11030:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11031:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11032:                              $unused{$path.'/'.$file} = 1; 
                   11033:                          }
                   11034:                     }
                   11035:                 }
                   11036:             }
                   11037:         }
1.984     raeburn  11038:     }
1.987     raeburn  11039:     my %currfile;
1.1075.2.35  raeburn  11040:     if (($actionurl eq '/adm/portfolio') ||
                   11041:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11042:         my ($dirlistref,$listerror) =
                   11043:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11044:         if (ref($dirlistref) eq 'ARRAY') {
                   11045:             foreach my $line (@{$dirlistref}) {
                   11046:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11047:                 $currfile{$file_name} = 1;
                   11048:             }
1.984     raeburn  11049:         }
1.987     raeburn  11050:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11051:         if (opendir(my $dir,$url)) {
1.987     raeburn  11052:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11053:             map {$currfile{$_} = 1;} @dir_list;
                   11054:         }
1.1075.2.11  raeburn  11055:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11056:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11057:               ($args->{'context'} eq 'paste')) ||
                   11058:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11059:         if ($env{'request.course.id'} ne '') {
                   11060:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11061:             if ($dir ne '') {
                   11062:                 my ($dirlistref,$listerror) =
                   11063:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11064:                 if (ref($dirlistref) eq 'ARRAY') {
                   11065:                     foreach my $line (@{$dirlistref}) {
                   11066:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11067:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11068:                         unless (($testdir&$dirptr) ||
                   11069:                                 ($file_name =~ /^\.\.?$/)) {
                   11070:                             $currfile{$file_name} = [$size,$mtime];
                   11071:                         }
                   11072:                     }
                   11073:                 }
                   11074:             }
                   11075:         }
1.984     raeburn  11076:     }
                   11077:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11078:         if (exists($currfile{$file})) {
1.987     raeburn  11079:             unless ($mapping{$file} eq $file) {
                   11080:                 $pathchanges{$file} = 1;
                   11081:             }
                   11082:             $existing{$file} = 1;
                   11083:             $numexisting ++;
                   11084:         } else {
1.984     raeburn  11085:             $newfiles{$file} = 1;
                   11086:         }
                   11087:     }
1.1071    raeburn  11088:     foreach my $file (keys(%currfile)) {
                   11089:         unless (($file eq $filename) ||
                   11090:                 ($file eq $filename.'.bak') ||
                   11091:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11092:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11093:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11094:                     next if (($rem ne '') &&
                   11095:                              (($env{"httpref.$rem".$file} ne '') ||
                   11096:                               (ref($navmap) &&
                   11097:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11098:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11099:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11100:                 }
1.1075.2.11  raeburn  11101:             }
1.1071    raeburn  11102:             $unused{$file} = 1;
                   11103:         }
                   11104:     }
1.1075.2.11  raeburn  11105:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11106:         ($args->{'context'} eq 'paste')) {
                   11107:         $counter = scalar(keys(%existing));
                   11108:         $numpathchg = scalar(keys(%pathchanges));
                   11109:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11110:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11111:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11112:         $counter = scalar(keys(%existing));
                   11113:         $numpathchg = scalar(keys(%pathchanges));
                   11114:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11115:     }
1.984     raeburn  11116:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11117:         if ($actionurl eq '/adm/dependencies') {
                   11118:             next if ($embed_file =~ m{^\w+://});
                   11119:         }
1.660     raeburn  11120:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11121:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11122:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11123:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11124:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11125:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11126:         }
1.1075.2.35  raeburn  11127:         $upload_output .= '</td>';
1.1071    raeburn  11128:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11129:             $upload_output.='<td align="right">'.
                   11130:                             '<span class="LC_info LC_fontsize_medium">'.
                   11131:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11132:             $numremref++;
1.660     raeburn  11133:         } elsif ($args->{'error_on_invalid_names'}
                   11134:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11135:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11136:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11137:             $numinvalid++;
1.660     raeburn  11138:         } else {
1.1075.2.35  raeburn  11139:             $upload_output .= '<td>'.
                   11140:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11141:                                                      $embed_file,\%mapping,
1.1071    raeburn  11142:                                                      $allfiles,$codebase,'upload');
                   11143:             $counter ++;
                   11144:             $numnew ++;
1.987     raeburn  11145:         }
                   11146:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11147:     }
                   11148:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11149:         if ($actionurl eq '/adm/dependencies') {
                   11150:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11151:             $modify_output .= &start_data_table_row().
                   11152:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11153:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11154:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11155:                               '<td>'.$size.'</td>'.
                   11156:                               '<td>'.$mtime.'</td>'.
                   11157:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11158:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11159:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11160:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11161:                               &embedded_file_element('upload_embedded',$counter,
                   11162:                                                      $embed_file,\%mapping,
                   11163:                                                      $allfiles,$codebase,'modify').
                   11164:                               '</div></td>'.
                   11165:                               &end_data_table_row()."\n";
                   11166:             $counter ++;
                   11167:         } else {
                   11168:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11169:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11170:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11171:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11172:                               &Apache::loncommon::end_data_table_row()."\n";
                   11173:         }
                   11174:     }
                   11175:     my $delidx = $counter;
                   11176:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11177:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11178:         $delete_output .= &start_data_table_row().
                   11179:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11180:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11181:                           '<td>'.$size.'</td>'.
                   11182:                           '<td>'.$mtime.'</td>'.
                   11183:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11184:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11185:                           &embedded_file_element('upload_embedded',$delidx,
                   11186:                                                  $oldfile,\%mapping,$allfiles,
                   11187:                                                  $codebase,'delete').'</td>'.
                   11188:                           &end_data_table_row()."\n"; 
                   11189:         $numunused ++;
                   11190:         $delidx ++;
1.987     raeburn  11191:     }
                   11192:     if ($upload_output) {
                   11193:         $upload_output = &start_data_table().
                   11194:                          $upload_output.
                   11195:                          &end_data_table()."\n";
                   11196:     }
1.1071    raeburn  11197:     if ($modify_output) {
                   11198:         $modify_output = &start_data_table().
                   11199:                          &start_data_table_header_row().
                   11200:                          '<th>'.&mt('File').'</th>'.
                   11201:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11202:                          '<th>'.&mt('Modified').'</th>'.
                   11203:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11204:                          &end_data_table_header_row().
                   11205:                          $modify_output.
                   11206:                          &end_data_table()."\n";
                   11207:     }
                   11208:     if ($delete_output) {
                   11209:         $delete_output = &start_data_table().
                   11210:                          &start_data_table_header_row().
                   11211:                          '<th>'.&mt('File').'</th>'.
                   11212:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11213:                          '<th>'.&mt('Modified').'</th>'.
                   11214:                          '<th>'.&mt('Delete?').'</th>'.
                   11215:                          &end_data_table_header_row().
                   11216:                          $delete_output.
                   11217:                          &end_data_table()."\n";
                   11218:     }
1.987     raeburn  11219:     my $applies = 0;
                   11220:     if ($numremref) {
                   11221:         $applies ++;
                   11222:     }
                   11223:     if ($numinvalid) {
                   11224:         $applies ++;
                   11225:     }
                   11226:     if ($numexisting) {
                   11227:         $applies ++;
                   11228:     }
1.1071    raeburn  11229:     if ($counter || $numunused) {
1.987     raeburn  11230:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11231:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11232:                   $state.'<h3>'.$heading.'</h3>'; 
                   11233:         if ($actionurl eq '/adm/dependencies') {
                   11234:             if ($numnew) {
                   11235:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11236:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11237:                            $upload_output.'<br />'."\n";
                   11238:             }
                   11239:             if ($numexisting) {
                   11240:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11241:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11242:                            $modify_output.'<br />'."\n";
                   11243:                            $buttontext = &mt('Save changes');
                   11244:             }
                   11245:             if ($numunused) {
                   11246:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11247:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11248:                            $delete_output.'<br />'."\n";
                   11249:                            $buttontext = &mt('Save changes');
                   11250:             }
                   11251:         } else {
                   11252:             $output .= $upload_output.'<br />'."\n";
                   11253:         }
                   11254:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11255:                    $counter.'" />'."\n";
                   11256:         if ($actionurl eq '/adm/dependencies') { 
                   11257:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11258:                        $numnew.'" />'."\n";
                   11259:         } elsif ($actionurl eq '') {
1.987     raeburn  11260:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11261:         }
                   11262:     } elsif ($applies) {
                   11263:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11264:         if ($applies > 1) {
                   11265:             $output .=  
1.1075.2.35  raeburn  11266:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11267:             if ($numremref) {
                   11268:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11269:             }
                   11270:             if ($numinvalid) {
                   11271:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11272:             }
                   11273:             if ($numexisting) {
                   11274:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11275:             }
                   11276:             $output .= '</ul><br />';
                   11277:         } elsif ($numremref) {
                   11278:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11279:         } elsif ($numinvalid) {
                   11280:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11281:         } elsif ($numexisting) {
                   11282:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11283:         }
                   11284:         $output .= $upload_output.'<br />';
                   11285:     }
                   11286:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11287:     $chgcount = $counter;
1.987     raeburn  11288:     if (keys(%pathchanges) > 0) {
                   11289:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11290:             if ($counter) {
1.987     raeburn  11291:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11292:                                                   $embed_file,\%mapping,
1.1071    raeburn  11293:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11294:             } else {
                   11295:                 $pathchange_output .= 
                   11296:                     &start_data_table_row().
                   11297:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11298:                     $chgcount.'" checked="checked" /></td>'.
                   11299:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11300:                     '<td>'.$embed_file.
                   11301:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11302:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11303:                     '</td>'.&end_data_table_row();
1.660     raeburn  11304:             }
1.987     raeburn  11305:             $numpathchg ++;
                   11306:             $chgcount ++;
1.660     raeburn  11307:         }
                   11308:     }
1.1075.2.35  raeburn  11309:     if (($counter) || ($numunused)) {
1.987     raeburn  11310:         if ($numpathchg) {
                   11311:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11312:                        $numpathchg.'" />'."\n";
                   11313:         }
                   11314:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11315:             ($actionurl eq '/adm/imsimport')) {
                   11316:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11317:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11318:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11319:         } elsif ($actionurl eq '/adm/dependencies') {
                   11320:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11321:         }
1.1075.2.35  raeburn  11322:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11323:     } elsif ($numpathchg) {
                   11324:         my %pathchange = ();
                   11325:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11326:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11327:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11328:         }
1.987     raeburn  11329:     }
1.1071    raeburn  11330:     return ($output,$counter,$numpathchg);
1.987     raeburn  11331: }
                   11332: 
1.1075.2.47  raeburn  11333: =pod
                   11334: 
                   11335: =item * clean_path($name)
                   11336: 
                   11337: Performs clean-up of directories, subdirectories and filename in an
                   11338: embedded object, referenced in an HTML file which is being uploaded
                   11339: to a course or portfolio, where
                   11340: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11341: checked.
                   11342: 
                   11343: Clean-up is similar to replacements in lonnet::clean_filename()
                   11344: except each / between sub-directory and next level is preserved.
                   11345: 
                   11346: =cut
                   11347: 
                   11348: sub clean_path {
                   11349:     my ($embed_file) = @_;
                   11350:     $embed_file =~s{^/+}{};
                   11351:     my @contents;
                   11352:     if ($embed_file =~ m{/}) {
                   11353:         @contents = split(/\//,$embed_file);
                   11354:     } else {
                   11355:         @contents = ($embed_file);
                   11356:     }
                   11357:     my $lastidx = scalar(@contents)-1;
                   11358:     for (my $i=0; $i<=$lastidx; $i++) {
                   11359:         $contents[$i]=~s{\\}{/}g;
                   11360:         $contents[$i]=~s/\s+/\_/g;
                   11361:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11362:         if ($i == $lastidx) {
                   11363:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11364:         }
                   11365:     }
                   11366:     if ($lastidx > 0) {
                   11367:         return join('/',@contents);
                   11368:     } else {
                   11369:         return $contents[0];
                   11370:     }
                   11371: }
                   11372: 
1.987     raeburn  11373: sub embedded_file_element {
1.1071    raeburn  11374:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11375:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11376:                    (ref($codebase) eq 'HASH'));
                   11377:     my $output;
1.1071    raeburn  11378:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11379:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11380:     }
                   11381:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11382:                &escape($embed_file).'" />';
                   11383:     unless (($context eq 'upload_embedded') && 
                   11384:             ($mapping->{$embed_file} eq $embed_file)) {
                   11385:         $output .='
                   11386:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11387:     }
                   11388:     my $attrib;
                   11389:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11390:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11391:     }
                   11392:     $output .=
                   11393:         "\n\t\t".
                   11394:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11395:         $attrib.'" />';
                   11396:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11397:         $output .=
                   11398:             "\n\t\t".
                   11399:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11400:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11401:     }
1.987     raeburn  11402:     return $output;
1.660     raeburn  11403: }
                   11404: 
1.1071    raeburn  11405: sub get_dependency_details {
                   11406:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11407:     my ($size,$mtime,$showsize,$showmtime);
                   11408:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11409:         if ($embed_file =~ m{/}) {
                   11410:             my ($path,$fname) = split(/\//,$embed_file);
                   11411:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11412:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11413:             }
                   11414:         } else {
                   11415:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11416:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11417:             }
                   11418:         }
                   11419:         $showsize = $size/1024.0;
                   11420:         $showsize = sprintf("%.1f",$showsize);
                   11421:         if ($mtime > 0) {
                   11422:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11423:         }
                   11424:     }
                   11425:     return ($showsize,$showmtime);
                   11426: }
                   11427: 
                   11428: sub ask_embedded_js {
                   11429:     return <<"END";
                   11430: <script type="text/javascript"">
                   11431: // <![CDATA[
                   11432: function toggleBrowse(counter) {
                   11433:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11434:     var fileid = document.getElementById('embedded_item_'+counter);
                   11435:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11436:     if (chkboxid.checked == true) {
                   11437:         uploaddivid.style.display='block';
                   11438:     } else {
                   11439:         uploaddivid.style.display='none';
                   11440:         fileid.value = '';
                   11441:     }
                   11442: }
                   11443: // ]]>
                   11444: </script>
                   11445: 
                   11446: END
                   11447: }
                   11448: 
1.661     raeburn  11449: sub upload_embedded {
                   11450:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11451:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11452:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11453:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11454:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11455:         my $orig_uploaded_filename =
                   11456:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11457:         foreach my $type ('orig','ref','attrib','codebase') {
                   11458:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11459:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11460:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11461:             }
                   11462:         }
1.661     raeburn  11463:         my ($path,$fname) =
                   11464:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11465:         # no path, whole string is fname
                   11466:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11467:         $fname = &Apache::lonnet::clean_filename($fname);
                   11468:         # See if there is anything left
                   11469:         next if ($fname eq '');
                   11470: 
                   11471:         # Check if file already exists as a file or directory.
                   11472:         my ($state,$msg);
                   11473:         if ($context eq 'portfolio') {
                   11474:             my $port_path = $dirpath;
                   11475:             if ($group ne '') {
                   11476:                 $port_path = "groups/$group/$port_path";
                   11477:             }
1.987     raeburn  11478:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11479:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11480:                                               $dir_root,$port_path,$disk_quota,
                   11481:                                               $current_disk_usage,$uname,$udom);
                   11482:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11483:                 || $state eq 'file_locked') {
1.661     raeburn  11484:                 $output .= $msg;
                   11485:                 next;
                   11486:             }
                   11487:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11488:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11489:             if ($state eq 'exists') {
                   11490:                 $output .= $msg;
                   11491:                 next;
                   11492:             }
                   11493:         }
                   11494:         # Check if extension is valid
                   11495:         if (($fname =~ /\.(\w+)$/) &&
                   11496:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11497:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11498:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11499:             next;
                   11500:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11501:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11502:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11503:             next;
                   11504:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11505:             $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  11506:             next;
                   11507:         }
                   11508:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11509:         my $subdir = $path;
                   11510:         $subdir =~ s{/+$}{};
1.661     raeburn  11511:         if ($context eq 'portfolio') {
1.984     raeburn  11512:             my $result;
                   11513:             if ($state eq 'existingfile') {
                   11514:                 $result=
                   11515:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11516:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11517:             } else {
1.984     raeburn  11518:                 $result=
                   11519:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11520:                                                     $dirpath.
1.1075.2.35  raeburn  11521:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11522:                 if ($result !~ m|^/uploaded/|) {
                   11523:                     $output .= '<span class="LC_error">'
                   11524:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11525:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11526:                                .'</span><br />';
                   11527:                     next;
                   11528:                 } else {
1.987     raeburn  11529:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11530:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11531:                 }
1.661     raeburn  11532:             }
1.1075.2.35  raeburn  11533:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11534:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11535:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11536:             my $result =
1.1075.2.35  raeburn  11537:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11538:             if ($result !~ m|^/uploaded/|) {
                   11539:                 $output .= '<span class="LC_error">'
                   11540:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11541:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11542:                            .'</span><br />';
                   11543:                     next;
                   11544:             } else {
                   11545:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11546:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11547:                 if ($context eq 'syllabus') {
                   11548:                     &Apache::lonnet::make_public_indefinitely($result);
                   11549:                 }
1.987     raeburn  11550:             }
1.661     raeburn  11551:         } else {
                   11552: # Save the file
                   11553:             my $target = $env{'form.embedded_item_'.$i};
                   11554:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11555:             my $dest = $fullpath.$fname;
                   11556:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11557:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11558:             my $count;
                   11559:             my $filepath = $dir_root;
1.1027    raeburn  11560:             foreach my $subdir (@parts) {
                   11561:                 $filepath .= "/$subdir";
                   11562:                 if (!-e $filepath) {
1.661     raeburn  11563:                     mkdir($filepath,0770);
                   11564:                 }
                   11565:             }
                   11566:             my $fh;
                   11567:             if (!open($fh,'>'.$dest)) {
                   11568:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11569:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11570:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11571:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11572:                            '</span><br />';
                   11573:             } else {
                   11574:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11575:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11576:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11577:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11578:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11579:                               '</span><br />';
                   11580:                 } else {
1.987     raeburn  11581:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11582:                                $url.'</span>').'<br />';
                   11583:                     unless ($context eq 'testbank') {
                   11584:                         $footer .= &mt('View embedded file: [_1]',
                   11585:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11586:                     }
                   11587:                 }
                   11588:                 close($fh);
                   11589:             }
                   11590:         }
                   11591:         if ($env{'form.embedded_ref_'.$i}) {
                   11592:             $pathchange{$i} = 1;
                   11593:         }
                   11594:     }
                   11595:     if ($output) {
                   11596:         $output = '<p>'.$output.'</p>';
                   11597:     }
                   11598:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11599:     $returnflag = 'ok';
1.1071    raeburn  11600:     my $numpathchgs = scalar(keys(%pathchange));
                   11601:     if ($numpathchgs > 0) {
1.987     raeburn  11602:         if ($context eq 'portfolio') {
                   11603:             $output .= '<p>'.&mt('or').'</p>';
                   11604:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11605:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11606:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11607:             $returnflag = 'modify_orightml';
                   11608:         }
                   11609:     }
1.1071    raeburn  11610:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11611: }
                   11612: 
                   11613: sub modify_html_form {
                   11614:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11615:     my $end = 0;
                   11616:     my $modifyform;
                   11617:     if ($context eq 'upload_embedded') {
                   11618:         return unless (ref($pathchange) eq 'HASH');
                   11619:         if ($env{'form.number_embedded_items'}) {
                   11620:             $end += $env{'form.number_embedded_items'};
                   11621:         }
                   11622:         if ($env{'form.number_pathchange_items'}) {
                   11623:             $end += $env{'form.number_pathchange_items'};
                   11624:         }
                   11625:         if ($end) {
                   11626:             for (my $i=0; $i<$end; $i++) {
                   11627:                 if ($i < $env{'form.number_embedded_items'}) {
                   11628:                     next unless($pathchange->{$i});
                   11629:                 }
                   11630:                 $modifyform .=
                   11631:                     &start_data_table_row().
                   11632:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11633:                     'checked="checked" /></td>'.
                   11634:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11635:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11636:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11637:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11638:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11639:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11640:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11641:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11642:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11643:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11644:                     &end_data_table_row();
1.1071    raeburn  11645:             }
1.987     raeburn  11646:         }
                   11647:     } else {
                   11648:         $modifyform = $pathchgtable;
                   11649:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11650:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11651:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11652:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11653:         }
                   11654:     }
                   11655:     if ($modifyform) {
1.1071    raeburn  11656:         if ($actionurl eq '/adm/dependencies') {
                   11657:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11658:         }
1.987     raeburn  11659:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11660:                '<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".
                   11661:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11662:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11663:                '</ol></p>'."\n".'<p>'.
                   11664:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11665:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11666:                &start_data_table()."\n".
                   11667:                &start_data_table_header_row().
                   11668:                '<th>'.&mt('Change?').'</th>'.
                   11669:                '<th>'.&mt('Current reference').'</th>'.
                   11670:                '<th>'.&mt('Required reference').'</th>'.
                   11671:                &end_data_table_header_row()."\n".
                   11672:                $modifyform.
                   11673:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11674:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11675:                '</form>'."\n";
                   11676:     }
                   11677:     return;
                   11678: }
                   11679: 
                   11680: sub modify_html_refs {
1.1075.2.35  raeburn  11681:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11682:     my $container;
                   11683:     if ($context eq 'portfolio') {
                   11684:         $container = $env{'form.container'};
                   11685:     } elsif ($context eq 'coursedoc') {
                   11686:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11687:     } elsif ($context eq 'manage_dependencies') {
                   11688:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11689:         $container = "/$container";
1.1075.2.35  raeburn  11690:     } elsif ($context eq 'syllabus') {
                   11691:         $container = $url;
1.987     raeburn  11692:     } else {
1.1027    raeburn  11693:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11694:     }
                   11695:     my (%allfiles,%codebase,$output,$content);
                   11696:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11697:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11698:         if (wantarray) {
                   11699:             return ('',0,0); 
                   11700:         } else {
                   11701:             return;
                   11702:         }
                   11703:     }
                   11704:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11705:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11706:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11707:             if (wantarray) {
                   11708:                 return ('',0,0);
                   11709:             } else {
                   11710:                 return;
                   11711:             }
                   11712:         } 
1.987     raeburn  11713:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11714:         if ($content eq '-1') {
                   11715:             if (wantarray) {
                   11716:                 return ('',0,0);
                   11717:             } else {
                   11718:                 return;
                   11719:             }
                   11720:         }
1.987     raeburn  11721:     } else {
1.1071    raeburn  11722:         unless ($container =~ /^\Q$dir_root\E/) {
                   11723:             if (wantarray) {
                   11724:                 return ('',0,0);
                   11725:             } else {
                   11726:                 return;
                   11727:             }
                   11728:         } 
1.1075.2.128  raeburn  11729:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11730:             $content = join('', <$fh>);
                   11731:             close($fh);
                   11732:         } else {
1.1071    raeburn  11733:             if (wantarray) {
                   11734:                 return ('',0,0);
                   11735:             } else {
                   11736:                 return;
                   11737:             }
1.987     raeburn  11738:         }
                   11739:     }
                   11740:     my ($count,$codebasecount) = (0,0);
                   11741:     my $mm = new File::MMagic;
                   11742:     my $mime_type = $mm->checktype_contents($content);
                   11743:     if ($mime_type eq 'text/html') {
                   11744:         my $parse_result = 
                   11745:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11746:                                                     \%codebase,\$content);
                   11747:         if ($parse_result eq 'ok') {
                   11748:             foreach my $i (@changes) {
                   11749:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11750:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11751:                 if ($allfiles{$ref}) {
                   11752:                     my $newname =  $orig;
                   11753:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11754:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11755:                     if ($attrib_regexp =~ /:/) {
                   11756:                         $attrib_regexp =~ s/\:/|/g;
                   11757:                     }
                   11758:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11759:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11760:                         $count += $numchg;
1.1075.2.35  raeburn  11761:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11762:                         delete($allfiles{$ref});
1.987     raeburn  11763:                     }
                   11764:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11765:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11766:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11767:                         $codebasecount ++;
                   11768:                     }
                   11769:                 }
                   11770:             }
1.1075.2.35  raeburn  11771:             my $skiprewrites;
1.987     raeburn  11772:             if ($count || $codebasecount) {
                   11773:                 my $saveresult;
1.1071    raeburn  11774:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11775:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11776:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11777:                     if ($url eq $container) {
                   11778:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11779:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11780:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11781:                                             $fname.'</span>').'</p>';
1.987     raeburn  11782:                     } else {
                   11783:                          $output = '<p class="LC_error">'.
                   11784:                                    &mt('Error: update failed for: [_1].',
                   11785:                                    '<span class="LC_filename">'.
                   11786:                                    $container.'</span>').'</p>';
                   11787:                     }
1.1075.2.35  raeburn  11788:                     if ($context eq 'syllabus') {
                   11789:                         unless ($saveresult eq 'ok') {
                   11790:                             $skiprewrites = 1;
                   11791:                         }
                   11792:                     }
1.987     raeburn  11793:                 } else {
1.1075.2.128  raeburn  11794:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11795:                         print $fh $content;
                   11796:                         close($fh);
                   11797:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11798:                                   $count,'<span class="LC_filename">'.
                   11799:                                   $container.'</span>').'</p>';
1.661     raeburn  11800:                     } else {
1.987     raeburn  11801:                          $output = '<p class="LC_error">'.
                   11802:                                    &mt('Error: could not update [_1].',
                   11803:                                    '<span class="LC_filename">'.
                   11804:                                    $container.'</span>').'</p>';
1.661     raeburn  11805:                     }
                   11806:                 }
                   11807:             }
1.1075.2.35  raeburn  11808:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11809:                 my ($actionurl,$state);
                   11810:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11811:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11812:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11813:                                               \%codebase,
                   11814:                                               {'context' => 'rewrites',
                   11815:                                                'ignore_remote_references' => 1,});
                   11816:                 if (ref($mapping) eq 'HASH') {
                   11817:                     my $rewrites = 0;
                   11818:                     foreach my $key (keys(%{$mapping})) {
                   11819:                         next if ($key =~ m{^https?://});
                   11820:                         my $ref = $mapping->{$key};
                   11821:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11822:                         my $attrib;
                   11823:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11824:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11825:                         }
                   11826:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11827:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11828:                             $rewrites += $numchg;
                   11829:                         }
                   11830:                     }
                   11831:                     if ($rewrites) {
                   11832:                         my $saveresult;
                   11833:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11834:                         if ($url eq $container) {
                   11835:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11836:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11837:                                             $count,'<span class="LC_filename">'.
                   11838:                                             $fname.'</span>').'</p>';
                   11839:                         } else {
                   11840:                             $output .= '<p class="LC_error">'.
                   11841:                                        &mt('Error: could not update links in [_1].',
                   11842:                                        '<span class="LC_filename">'.
                   11843:                                        $container.'</span>').'</p>';
                   11844: 
                   11845:                         }
                   11846:                     }
                   11847:                 }
                   11848:             }
1.987     raeburn  11849:         } else {
                   11850:             &logthis('Failed to parse '.$container.
                   11851:                      ' to modify references: '.$parse_result);
1.661     raeburn  11852:         }
                   11853:     }
1.1071    raeburn  11854:     if (wantarray) {
                   11855:         return ($output,$count,$codebasecount);
                   11856:     } else {
                   11857:         return $output;
                   11858:     }
1.661     raeburn  11859: }
                   11860: 
                   11861: sub check_for_existing {
                   11862:     my ($path,$fname,$element) = @_;
                   11863:     my ($state,$msg);
                   11864:     if (-d $path.'/'.$fname) {
                   11865:         $state = 'exists';
                   11866:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11867:     } elsif (-e $path.'/'.$fname) {
                   11868:         $state = 'exists';
                   11869:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11870:     }
                   11871:     if ($state eq 'exists') {
                   11872:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11873:     }
                   11874:     return ($state,$msg);
                   11875: }
                   11876: 
                   11877: sub check_for_upload {
                   11878:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11879:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11880:     my $filesize = length($env{'form.'.$element});
                   11881:     if (!$filesize) {
                   11882:         my $msg = '<span class="LC_error">'.
                   11883:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11884:                       '<span class="LC_filename">'.$fname.'</span>',
                   11885:                       $filesize).'<br />'.
1.1007    raeburn  11886:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11887:                   '</span>';
                   11888:         return ('zero_bytes',$msg);
                   11889:     }
                   11890:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11891:     my $getpropath = 1;
1.1021    raeburn  11892:     my ($dirlistref,$listerror) =
                   11893:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11894:     my $found_file = 0;
                   11895:     my $locked_file = 0;
1.991     raeburn  11896:     my @lockers;
                   11897:     my $navmap;
                   11898:     if ($env{'request.course.id'}) {
                   11899:         $navmap = Apache::lonnavmaps::navmap->new();
                   11900:     }
1.1021    raeburn  11901:     if (ref($dirlistref) eq 'ARRAY') {
                   11902:         foreach my $line (@{$dirlistref}) {
                   11903:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11904:             if ($file_name eq $fname){
                   11905:                 $file_name = $path.$file_name;
                   11906:                 if ($group ne '') {
                   11907:                     $file_name = $group.$file_name;
                   11908:                 }
                   11909:                 $found_file = 1;
                   11910:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11911:                     foreach my $lock (@lockers) {
                   11912:                         if (ref($lock) eq 'ARRAY') {
                   11913:                             my ($symb,$crsid) = @{$lock};
                   11914:                             if ($crsid eq $env{'request.course.id'}) {
                   11915:                                 if (ref($navmap)) {
                   11916:                                     my $res = $navmap->getBySymb($symb);
                   11917:                                     foreach my $part (@{$res->parts()}) { 
                   11918:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11919:                                         unless (($slot_status == $res->RESERVED) ||
                   11920:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11921:                                             $locked_file = 1;
                   11922:                                         }
1.991     raeburn  11923:                                     }
1.1021    raeburn  11924:                                 } else {
                   11925:                                     $locked_file = 1;
1.991     raeburn  11926:                                 }
                   11927:                             } else {
                   11928:                                 $locked_file = 1;
                   11929:                             }
                   11930:                         }
1.1021    raeburn  11931:                    }
                   11932:                 } else {
                   11933:                     my @info = split(/\&/,$rest);
                   11934:                     my $currsize = $info[6]/1000;
                   11935:                     if ($currsize < $filesize) {
                   11936:                         my $extra = $filesize - $currsize;
                   11937:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11938:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11939:                                       &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  11940:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11941:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11942:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11943:                             return ('will_exceed_quota',$msg);
                   11944:                         }
1.984     raeburn  11945:                     }
                   11946:                 }
1.661     raeburn  11947:             }
                   11948:         }
                   11949:     }
                   11950:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11951:         my $msg = '<p class="LC_warning">'.
                   11952:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11953:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11954:         return ('will_exceed_quota',$msg);
                   11955:     } elsif ($found_file) {
                   11956:         if ($locked_file) {
1.1075.2.69  raeburn  11957:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11958:             $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  11959:             $msg .= '</p>';
1.661     raeburn  11960:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11961:             return ('file_locked',$msg);
                   11962:         } else {
1.1075.2.69  raeburn  11963:             my $msg = '<p class="LC_error">';
1.984     raeburn  11964:             $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  11965:             $msg .= '</p>';
1.984     raeburn  11966:             return ('existingfile',$msg);
1.661     raeburn  11967:         }
                   11968:     }
                   11969: }
                   11970: 
1.987     raeburn  11971: sub check_for_traversal {
                   11972:     my ($path,$url,$toplevel) = @_;
                   11973:     my @parts=split(/\//,$path);
                   11974:     my $cleanpath;
                   11975:     my $fullpath = $url;
                   11976:     for (my $i=0;$i<@parts;$i++) {
                   11977:         next if ($parts[$i] eq '.');
                   11978:         if ($parts[$i] eq '..') {
                   11979:             $fullpath =~ s{([^/]+/)$}{};
                   11980:         } else {
                   11981:             $fullpath .= $parts[$i].'/';
                   11982:         }
                   11983:     }
                   11984:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11985:         $cleanpath = $1;
                   11986:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11987:         my $curr_toprel = $1;
                   11988:         my @parts = split(/\//,$curr_toprel);
                   11989:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11990:         my @urlparts = split(/\//,$url_toprel);
                   11991:         my $doubledots;
                   11992:         my $startdiff = -1;
                   11993:         for (my $i=0; $i<@urlparts; $i++) {
                   11994:             if ($startdiff == -1) {
                   11995:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11996:                     $startdiff = $i;
                   11997:                     $doubledots .= '../';
                   11998:                 }
                   11999:             } else {
                   12000:                 $doubledots .= '../';
                   12001:             }
                   12002:         }
                   12003:         if ($startdiff > -1) {
                   12004:             $cleanpath = $doubledots;
                   12005:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12006:                 $cleanpath .= $parts[$i].'/';
                   12007:             }
                   12008:         }
                   12009:     }
                   12010:     $cleanpath =~ s{(/)$}{};
                   12011:     return $cleanpath;
                   12012: }
1.31      albertel 12013: 
1.1053    raeburn  12014: sub is_archive_file {
                   12015:     my ($mimetype) = @_;
                   12016:     if (($mimetype eq 'application/octet-stream') ||
                   12017:         ($mimetype eq 'application/x-stuffit') ||
                   12018:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12019:         return 1;
                   12020:     }
                   12021:     return;
                   12022: }
                   12023: 
                   12024: sub decompress_form {
1.1065    raeburn  12025:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12026:     my %lt = &Apache::lonlocal::texthash (
                   12027:         this => 'This file is an archive file.',
1.1067    raeburn  12028:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12029:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12030:         youm => 'You may wish to extract its contents.',
                   12031:         extr => 'Extract contents',
1.1067    raeburn  12032:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12033:         proa => 'Process automatically?',
1.1053    raeburn  12034:         yes  => 'Yes',
                   12035:         no   => 'No',
1.1067    raeburn  12036:         fold => 'Title for folder containing movie',
                   12037:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12038:     );
1.1065    raeburn  12039:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12040:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12041:     my $info = &list_archive_contents($fileloc,\@paths);
                   12042:     if (@paths) {
                   12043:         foreach my $path (@paths) {
                   12044:             $path =~ s{^/}{};
1.1067    raeburn  12045:             if ($path =~ m{^([^/]+)/$}) {
                   12046:                 $topdir = $1;
                   12047:             }
1.1065    raeburn  12048:             if ($path =~ m{^([^/]+)/}) {
                   12049:                 $toplevel{$1} = $path;
                   12050:             } else {
                   12051:                 $toplevel{$path} = $path;
                   12052:             }
                   12053:         }
                   12054:     }
1.1067    raeburn  12055:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12056:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12057:                         "$topdir/media/",
                   12058:                         "$topdir/media/$topdir.mp4",
                   12059:                         "$topdir/media/FirstFrame.png",
                   12060:                         "$topdir/media/player.swf",
                   12061:                         "$topdir/media/swfobject.js",
                   12062:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12063:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12064:                          "$topdir/$topdir.mp4",
                   12065:                          "$topdir/$topdir\_config.xml",
                   12066:                          "$topdir/$topdir\_controller.swf",
                   12067:                          "$topdir/$topdir\_embed.css",
                   12068:                          "$topdir/$topdir\_First_Frame.png",
                   12069:                          "$topdir/$topdir\_player.html",
                   12070:                          "$topdir/$topdir\_Thumbnails.png",
                   12071:                          "$topdir/playerProductInstall.swf",
                   12072:                          "$topdir/scripts/",
                   12073:                          "$topdir/scripts/config_xml.js",
                   12074:                          "$topdir/scripts/handlebars.js",
                   12075:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12076:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12077:                          "$topdir/scripts/modernizr.js",
                   12078:                          "$topdir/scripts/player-min.js",
                   12079:                          "$topdir/scripts/swfobject.js",
                   12080:                          "$topdir/skins/",
                   12081:                          "$topdir/skins/configuration_express.xml",
                   12082:                          "$topdir/skins/express_show/",
                   12083:                          "$topdir/skins/express_show/player-min.css",
                   12084:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12085:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12086:                          "$topdir/$topdir.mp4",
                   12087:                          "$topdir/$topdir\_config.xml",
                   12088:                          "$topdir/$topdir\_controller.swf",
                   12089:                          "$topdir/$topdir\_embed.css",
                   12090:                          "$topdir/$topdir\_First_Frame.png",
                   12091:                          "$topdir/$topdir\_player.html",
                   12092:                          "$topdir/$topdir\_Thumbnails.png",
                   12093:                          "$topdir/playerProductInstall.swf",
                   12094:                          "$topdir/scripts/",
                   12095:                          "$topdir/scripts/config_xml.js",
                   12096:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12097:                          "$topdir/skins/",
                   12098:                          "$topdir/skins/configuration_express.xml",
                   12099:                          "$topdir/skins/express_show/",
                   12100:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12101:                          "$topdir/skins/express_show/spritesheet.png",
                   12102:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12103:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12104:         if (@diffs == 0) {
1.1075.2.59  raeburn  12105:             $is_camtasia = 6;
                   12106:         } else {
1.1075.2.81  raeburn  12107:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12108:             if (@diffs == 0) {
                   12109:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12110:             } else {
                   12111:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12112:                 if (@diffs == 0) {
                   12113:                     $is_camtasia = 8;
                   12114:                 }
1.1075.2.59  raeburn  12115:             }
1.1067    raeburn  12116:         }
                   12117:     }
                   12118:     my $output;
                   12119:     if ($is_camtasia) {
                   12120:         $output = <<"ENDCAM";
                   12121: <script type="text/javascript" language="Javascript">
                   12122: // <![CDATA[
                   12123: 
                   12124: function camtasiaToggle() {
                   12125:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12126:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12127:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12128:                 document.getElementById('camtasia_titles').style.display='block';
                   12129:             } else {
                   12130:                 document.getElementById('camtasia_titles').style.display='none';
                   12131:             }
                   12132:         }
                   12133:     }
                   12134:     return;
                   12135: }
                   12136: 
                   12137: // ]]>
                   12138: </script>
                   12139: <p>$lt{'camt'}</p>
                   12140: ENDCAM
1.1065    raeburn  12141:     } else {
1.1067    raeburn  12142:         $output = '<p>'.$lt{'this'};
                   12143:         if ($info eq '') {
                   12144:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12145:         } else {
                   12146:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12147:                        '<div><pre>'.$info.'</pre></div>';
                   12148:         }
1.1065    raeburn  12149:     }
1.1067    raeburn  12150:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12151:     my $duplicates;
                   12152:     my $num = 0;
                   12153:     if (ref($dirlist) eq 'ARRAY') {
                   12154:         foreach my $item (@{$dirlist}) {
                   12155:             if (ref($item) eq 'ARRAY') {
                   12156:                 if (exists($toplevel{$item->[0]})) {
                   12157:                     $duplicates .= 
                   12158:                         &start_data_table_row().
                   12159:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12160:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12161:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12162:                         'value="1" />'.&mt('Yes').'</label>'.
                   12163:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12164:                         '<td>'.$item->[0].'</td>';
                   12165:                     if ($item->[2]) {
                   12166:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12167:                     } else {
                   12168:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12169:                     }
                   12170:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12171:                                    '<td>'.
                   12172:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12173:                                    '</td>'.
                   12174:                                    &end_data_table_row();
                   12175:                     $num ++;
                   12176:                 }
                   12177:             }
                   12178:         }
                   12179:     }
                   12180:     my $itemcount;
                   12181:     if (@paths > 0) {
                   12182:         $itemcount = scalar(@paths);
                   12183:     } else {
                   12184:         $itemcount = 1;
                   12185:     }
1.1067    raeburn  12186:     if ($is_camtasia) {
                   12187:         $output .= $lt{'auto'}.'<br />'.
                   12188:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12189:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12190:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12191:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12192:                    $lt{'no'}.'</label></span><br />'.
                   12193:                    '<div id="camtasia_titles" style="display:block">'.
                   12194:                    &Apache::lonhtmlcommon::start_pick_box().
                   12195:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12196:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12197:                    &Apache::lonhtmlcommon::row_closure().
                   12198:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12199:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12200:                    &Apache::lonhtmlcommon::row_closure(1).
                   12201:                    &Apache::lonhtmlcommon::end_pick_box().
                   12202:                    '</div>';
                   12203:     }
1.1065    raeburn  12204:     $output .= 
                   12205:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12206:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12207:         "\n";
1.1065    raeburn  12208:     if ($duplicates ne '') {
                   12209:         $output .= '<p><span class="LC_warning">'.
                   12210:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12211:                    &start_data_table().
                   12212:                    &start_data_table_header_row().
                   12213:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12214:                    '<th>'.&mt('Name').'</th>'.
                   12215:                    '<th>'.&mt('Type').'</th>'.
                   12216:                    '<th>'.&mt('Size').'</th>'.
                   12217:                    '<th>'.&mt('Last modified').'</th>'.
                   12218:                    &end_data_table_header_row().
                   12219:                    $duplicates.
                   12220:                    &end_data_table().
                   12221:                    '</p>';
                   12222:     }
1.1067    raeburn  12223:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12224:     if (ref($hiddenelements) eq 'HASH') {
                   12225:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12226:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12227:         }
                   12228:     }
                   12229:     $output .= <<"END";
1.1067    raeburn  12230: <br />
1.1053    raeburn  12231: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12232: </form>
                   12233: $noextract
                   12234: END
                   12235:     return $output;
                   12236: }
                   12237: 
1.1065    raeburn  12238: sub decompression_utility {
                   12239:     my ($program) = @_;
                   12240:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12241:     my $location;
                   12242:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12243:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12244:                          '/usr/sbin/') {
                   12245:             if (-x $dir.$program) {
                   12246:                 $location = $dir.$program;
                   12247:                 last;
                   12248:             }
                   12249:         }
                   12250:     }
                   12251:     return $location;
                   12252: }
                   12253: 
                   12254: sub list_archive_contents {
                   12255:     my ($file,$pathsref) = @_;
                   12256:     my (@cmd,$output);
                   12257:     my $needsregexp;
                   12258:     if ($file =~ /\.zip$/) {
                   12259:         @cmd = (&decompression_utility('unzip'),"-l");
                   12260:         $needsregexp = 1;
                   12261:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12262:              ($file =~ /\.tgz$/)) {
                   12263:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12264:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12265:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12266:     } elsif ($file =~ m|\.tar$|) {
                   12267:         @cmd = (&decompression_utility('tar'),"-tf");
                   12268:     }
                   12269:     if (@cmd) {
                   12270:         undef($!);
                   12271:         undef($@);
                   12272:         if (open(my $fh,"-|", @cmd, $file)) {
                   12273:             while (my $line = <$fh>) {
                   12274:                 $output .= $line;
                   12275:                 chomp($line);
                   12276:                 my $item;
                   12277:                 if ($needsregexp) {
                   12278:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12279:                 } else {
                   12280:                     $item = $line;
                   12281:                 }
                   12282:                 if ($item ne '') {
                   12283:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12284:                         push(@{$pathsref},$item);
                   12285:                     } 
                   12286:                 }
                   12287:             }
                   12288:             close($fh);
                   12289:         }
                   12290:     }
                   12291:     return $output;
                   12292: }
                   12293: 
1.1053    raeburn  12294: sub decompress_uploaded_file {
                   12295:     my ($file,$dir) = @_;
                   12296:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12297:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12298:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12299:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12300:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12301:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12302:     my $decompressed = $env{'cgi.decompressed'};
                   12303:     &Apache::lonnet::delenv('cgi.file');
                   12304:     &Apache::lonnet::delenv('cgi.dir');
                   12305:     &Apache::lonnet::delenv('cgi.decompressed');
                   12306:     return ($decompressed,$result);
                   12307: }
                   12308: 
1.1055    raeburn  12309: sub process_decompression {
                   12310:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12311:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12312:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12313:                &mt('Unexpected file path.').'</p>'."\n";
                   12314:     }
                   12315:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12316:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12317:                &mt('Unexpected course context.').'</p>'."\n";
                   12318:     }
                   12319:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12320:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12321:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12322:     }
1.1055    raeburn  12323:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12324:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12325:         $error = &mt('Filename not a supported archive file type.').
                   12326:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12327:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12328:     } else {
                   12329:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12330:         if ($docuhome eq 'no_host') {
                   12331:             $error = &mt('Could not determine home server for course.');
                   12332:         } else {
                   12333:             my @ids=&Apache::lonnet::current_machine_ids();
                   12334:             my $currdir = "$dir_root/$destination";
                   12335:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12336:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12337:                        "$dir_root/$destination";
                   12338:             } else {
                   12339:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12340:                        "$dir_root/$docudom/$docuname/$destination";
                   12341:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12342:                     $error = &mt('Archive file not found.');
                   12343:                 }
                   12344:             }
1.1065    raeburn  12345:             my (@to_overwrite,@to_skip);
                   12346:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12347:                 my $total = $env{'form.archive_overwrite_total'};
                   12348:                 for (my $i=0; $i<$total; $i++) {
                   12349:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12350:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12351:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12352:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12353:                     }
                   12354:                 }
                   12355:             }
                   12356:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12357:             my $numoverwrite = scalar(@to_overwrite);
                   12358:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12359:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12360:             } elsif ($dir eq '') {
1.1055    raeburn  12361:                 $error = &mt('Directory containing archive file unavailable.');
                   12362:             } elsif (!$error) {
1.1065    raeburn  12363:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12364:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12365:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12366:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12367:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12368:                         ($decompressed,$display) =
                   12369:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12370:                         foreach my $item (@to_skip) {
                   12371:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12372:                                 if (-f "$dir/$tempdir/$item") {
                   12373:                                     unlink("$dir/$tempdir/$item");
                   12374:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12375:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12376:                                 }
                   12377:                             }
                   12378:                         }
                   12379:                         foreach my $item (@to_overwrite) {
                   12380:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12381:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12382:                                     if (-f "$dir/$item") {
                   12383:                                         unlink("$dir/$item");
                   12384:                                     } elsif (-d "$dir/$item") {
                   12385:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12386:                                     }
                   12387:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12388:                                 }
1.1065    raeburn  12389:                             }
                   12390:                         }
1.1075.2.128  raeburn  12391:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12392:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12393:                         }
1.1065    raeburn  12394:                     }
                   12395:                 } else {
                   12396:                     ($decompressed,$display) = 
                   12397:                         &decompress_uploaded_file($file,$dir);
                   12398:                 }
1.1055    raeburn  12399:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12400:                     $output = '<p class="LC_info">'.
                   12401:                               &mt('Files extracted successfully from archive.').
                   12402:                               '</p>'."\n";
1.1055    raeburn  12403:                     my ($warning,$result,@contents);
                   12404:                     my ($newdirlistref,$newlisterror) =
                   12405:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12406:                                                  $docuname,1);
                   12407:                     my (%is_dir,%changes,@newitems);
                   12408:                     my $dirptr = 16384;
1.1065    raeburn  12409:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12410:                         foreach my $dir_line (@{$newdirlistref}) {
                   12411:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12412:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12413:                                 push(@newitems,$item);
                   12414:                                 if ($dirptr&$testdir) {
                   12415:                                     $is_dir{$item} = 1;
                   12416:                                 }
                   12417:                                 $changes{$item} = 1;
                   12418:                             }
                   12419:                         }
                   12420:                     }
                   12421:                     if (keys(%changes) > 0) {
                   12422:                         foreach my $item (sort(@newitems)) {
                   12423:                             if ($changes{$item}) {
                   12424:                                 push(@contents,$item);
                   12425:                             }
                   12426:                         }
                   12427:                     }
                   12428:                     if (@contents > 0) {
1.1067    raeburn  12429:                         my $wantform;
                   12430:                         unless ($env{'form.autoextract_camtasia'}) {
                   12431:                             $wantform = 1;
                   12432:                         }
1.1056    raeburn  12433:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12434:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12435:                                                                 $currdir,\%is_dir,
                   12436:                                                                 \%children,\%parent,
1.1056    raeburn  12437:                                                                 \@contents,\%dirorder,
                   12438:                                                                 \%titles,$wantform);
1.1055    raeburn  12439:                         if ($datatable ne '') {
                   12440:                             $output .= &archive_options_form('decompressed',$datatable,
                   12441:                                                              $count,$hiddenelem);
1.1065    raeburn  12442:                             my $startcount = 6;
1.1055    raeburn  12443:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12444:                                                            \%titles,\%children);
1.1055    raeburn  12445:                         }
1.1067    raeburn  12446:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12447:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12448:                             my %displayed;
                   12449:                             my $total = 1;
                   12450:                             $env{'form.archive_directory'} = [];
                   12451:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12452:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12453:                                 $path =~ s{/$}{};
                   12454:                                 my $item;
                   12455:                                 if ($path ne '') {
                   12456:                                     $item = "$path/$titles{$i}";
                   12457:                                 } else {
                   12458:                                     $item = $titles{$i};
                   12459:                                 }
                   12460:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12461:                                 if ($item eq $contents[0]) {
                   12462:                                     push(@{$env{'form.archive_directory'}},$i);
                   12463:                                     $env{'form.archive_'.$i} = 'display';
                   12464:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12465:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12466:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12467:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12468:                                     $env{'form.archive_'.$i} = 'display';
                   12469:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12470:                                     $displayed{'web'} = $i;
                   12471:                                 } else {
1.1075.2.59  raeburn  12472:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12473:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12474:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12475:                                         push(@{$env{'form.archive_directory'}},$i);
                   12476:                                     }
                   12477:                                     $env{'form.archive_'.$i} = 'dependency';
                   12478:                                 }
                   12479:                                 $total ++;
                   12480:                             }
                   12481:                             for (my $i=1; $i<$total; $i++) {
                   12482:                                 next if ($i == $displayed{'web'});
                   12483:                                 next if ($i == $displayed{'folder'});
                   12484:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12485:                             }
                   12486:                             $env{'form.phase'} = 'decompress_cleanup';
                   12487:                             $env{'form.archivedelete'} = 1;
                   12488:                             $env{'form.archive_count'} = $total-1;
                   12489:                             $output .=
                   12490:                                 &process_extracted_files('coursedocs',$docudom,
                   12491:                                                          $docuname,$destination,
                   12492:                                                          $dir_root,$hiddenelem);
                   12493:                         }
1.1055    raeburn  12494:                     } else {
                   12495:                         $warning = &mt('No new items extracted from archive file.');
                   12496:                     }
                   12497:                 } else {
                   12498:                     $output = $display;
                   12499:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12500:                 }
                   12501:             }
                   12502:         }
                   12503:     }
                   12504:     if ($error) {
                   12505:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12506:                    $error.'</p>'."\n";
                   12507:     }
                   12508:     if ($warning) {
                   12509:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12510:     }
                   12511:     return $output;
                   12512: }
                   12513: 
                   12514: sub get_extracted {
1.1056    raeburn  12515:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12516:         $titles,$wantform) = @_;
1.1055    raeburn  12517:     my $count = 0;
                   12518:     my $depth = 0;
                   12519:     my $datatable;
1.1056    raeburn  12520:     my @hierarchy;
1.1055    raeburn  12521:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12522:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12523:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12524:     foreach my $item (@{$contents}) {
                   12525:         $count ++;
1.1056    raeburn  12526:         @{$dirorder->{$count}} = @hierarchy;
                   12527:         $titles->{$count} = $item;
1.1055    raeburn  12528:         &archive_hierarchy($depth,$count,$parent,$children);
                   12529:         if ($wantform) {
                   12530:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12531:                                        $currdir,$depth,$count);
                   12532:         }
                   12533:         if ($is_dir->{$item}) {
                   12534:             $depth ++;
1.1056    raeburn  12535:             push(@hierarchy,$count);
                   12536:             $parent->{$depth} = $count;
1.1055    raeburn  12537:             $datatable .=
                   12538:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12539:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12540:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12541:             $depth --;
1.1056    raeburn  12542:             pop(@hierarchy);
1.1055    raeburn  12543:         }
                   12544:     }
                   12545:     return ($count,$datatable);
                   12546: }
                   12547: 
                   12548: sub recurse_extracted_archive {
1.1056    raeburn  12549:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12550:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12551:     my $result='';
1.1056    raeburn  12552:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12553:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12554:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12555:         return $result;
                   12556:     }
                   12557:     my $dirptr = 16384;
                   12558:     my ($newdirlistref,$newlisterror) =
                   12559:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12560:     if (ref($newdirlistref) eq 'ARRAY') {
                   12561:         foreach my $dir_line (@{$newdirlistref}) {
                   12562:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12563:             unless ($item =~ /^\.+$/) {
                   12564:                 $$count ++;
1.1056    raeburn  12565:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12566:                 $titles->{$$count} = $item;
1.1055    raeburn  12567:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12568: 
1.1055    raeburn  12569:                 my $is_dir;
                   12570:                 if ($dirptr&$testdir) {
                   12571:                     $is_dir = 1;
                   12572:                 }
                   12573:                 if ($wantform) {
                   12574:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12575:                 }
                   12576:                 if ($is_dir) {
                   12577:                     $$depth ++;
1.1056    raeburn  12578:                     push(@{$hierarchy},$$count);
                   12579:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12580:                     $result .=
                   12581:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12582:                                                    $docuname,$depth,$count,
1.1056    raeburn  12583:                                                    $hierarchy,$dirorder,$children,
                   12584:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12585:                     $$depth --;
1.1056    raeburn  12586:                     pop(@{$hierarchy});
1.1055    raeburn  12587:                 }
                   12588:             }
                   12589:         }
                   12590:     }
                   12591:     return $result;
                   12592: }
                   12593: 
                   12594: sub archive_hierarchy {
                   12595:     my ($depth,$count,$parent,$children) =@_;
                   12596:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12597:         if (exists($parent->{$depth})) {
                   12598:              $children->{$parent->{$depth}} .= $count.':';
                   12599:         }
                   12600:     }
                   12601:     return;
                   12602: }
                   12603: 
                   12604: sub archive_row {
                   12605:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12606:     my ($name) = ($item =~ m{([^/]+)$});
                   12607:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12608:                                        'display'    => 'Add as file',
1.1055    raeburn  12609:                                        'dependency' => 'Include as dependency',
                   12610:                                        'discard'    => 'Discard',
                   12611:                                       );
                   12612:     if ($is_dir) {
1.1059    raeburn  12613:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12614:     }
1.1056    raeburn  12615:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12616:     my $offset = 0;
1.1055    raeburn  12617:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12618:         $offset ++;
1.1065    raeburn  12619:         if ($action ne 'display') {
                   12620:             $offset ++;
                   12621:         }  
1.1055    raeburn  12622:         $output .= '<td><span class="LC_nobreak">'.
                   12623:                    '<label><input type="radio" name="archive_'.$count.
                   12624:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12625:         my $text = $choices{$action};
                   12626:         if ($is_dir) {
                   12627:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12628:             if ($action eq 'display') {
1.1059    raeburn  12629:                 $text = &mt('Add as folder');
1.1055    raeburn  12630:             }
1.1056    raeburn  12631:         } else {
                   12632:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12633: 
                   12634:         }
                   12635:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12636:         if ($action eq 'dependency') {
                   12637:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12638:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12639:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12640:                        '<option value=""></option>'."\n".
                   12641:                        '</select>'."\n".
                   12642:                        '</div>';
1.1059    raeburn  12643:         } elsif ($action eq 'display') {
                   12644:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12645:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12646:                        '</div>';
1.1055    raeburn  12647:         }
1.1056    raeburn  12648:         $output .= '</td>';
1.1055    raeburn  12649:     }
                   12650:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12651:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12652:     for (my $i=0; $i<$depth; $i++) {
                   12653:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12654:     }
                   12655:     if ($is_dir) {
                   12656:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12657:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12658:     } else {
                   12659:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12660:     }
                   12661:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12662:                &end_data_table_row();
                   12663:     return $output;
                   12664: }
                   12665: 
                   12666: sub archive_options_form {
1.1065    raeburn  12667:     my ($form,$display,$count,$hiddenelem) = @_;
                   12668:     my %lt = &Apache::lonlocal::texthash(
                   12669:                perm => 'Permanently remove archive file?',
                   12670:                hows => 'How should each extracted item be incorporated in the course?',
                   12671:                cont => 'Content actions for all',
                   12672:                addf => 'Add as folder/file',
                   12673:                incd => 'Include as dependency for a displayed file',
                   12674:                disc => 'Discard',
                   12675:                no   => 'No',
                   12676:                yes  => 'Yes',
                   12677:                save => 'Save',
                   12678:     );
                   12679:     my $output = <<"END";
                   12680: <form name="$form" method="post" action="">
                   12681: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12682: <label>
                   12683:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12684: </label>
                   12685: &nbsp;
                   12686: <label>
                   12687:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12688: </span>
                   12689: </p>
                   12690: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12691: <br />$lt{'hows'}
                   12692: <div class="LC_columnSection">
                   12693:   <fieldset>
                   12694:     <legend>$lt{'cont'}</legend>
                   12695:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12696:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12697:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12698:   </fieldset>
                   12699: </div>
                   12700: END
                   12701:     return $output.
1.1055    raeburn  12702:            &start_data_table()."\n".
1.1065    raeburn  12703:            $display."\n".
1.1055    raeburn  12704:            &end_data_table()."\n".
                   12705:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12706:            $hiddenelem.
1.1065    raeburn  12707:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12708:            '</form>';
                   12709: }
                   12710: 
                   12711: sub archive_javascript {
1.1056    raeburn  12712:     my ($startcount,$numitems,$titles,$children) = @_;
                   12713:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12714:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12715:     my $scripttag = <<START;
                   12716: <script type="text/javascript">
                   12717: // <![CDATA[
                   12718: 
                   12719: function checkAll(form,prefix) {
                   12720:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12721:     for (var i=0; i < form.elements.length; i++) {
                   12722:         var id = form.elements[i].id;
                   12723:         if ((id != '') && (id != undefined)) {
                   12724:             if (idstr.test(id)) {
                   12725:                 if (form.elements[i].type == 'radio') {
                   12726:                     form.elements[i].checked = true;
1.1056    raeburn  12727:                     var nostart = i-$startcount;
1.1059    raeburn  12728:                     var offset = nostart%7;
                   12729:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12730:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12731:                 }
                   12732:             }
                   12733:         }
                   12734:     }
                   12735: }
                   12736: 
                   12737: function propagateCheck(form,count) {
                   12738:     if (count > 0) {
1.1059    raeburn  12739:         var startelement = $startcount + ((count-1) * 7);
                   12740:         for (var j=1; j<6; j++) {
                   12741:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12742:                 var item = startelement + j; 
                   12743:                 if (form.elements[item].type == 'radio') {
                   12744:                     if (form.elements[item].checked) {
                   12745:                         containerCheck(form,count,j);
                   12746:                         break;
                   12747:                     }
1.1055    raeburn  12748:                 }
                   12749:             }
                   12750:         }
                   12751:     }
                   12752: }
                   12753: 
                   12754: numitems = $numitems
1.1056    raeburn  12755: var titles = new Array(numitems);
                   12756: var parents = new Array(numitems);
1.1055    raeburn  12757: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12758:     parents[i] = new Array;
1.1055    raeburn  12759: }
1.1059    raeburn  12760: var maintitle = '$maintitle';
1.1055    raeburn  12761: 
                   12762: START
                   12763: 
1.1056    raeburn  12764:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12765:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12766:         for (my $i=0; $i<@contents; $i ++) {
                   12767:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12768:         }
                   12769:     }
                   12770: 
1.1056    raeburn  12771:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12772:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12773:     }
                   12774: 
1.1055    raeburn  12775:     $scripttag .= <<END;
                   12776: 
                   12777: function containerCheck(form,count,offset) {
                   12778:     if (count > 0) {
1.1056    raeburn  12779:         dependencyCheck(form,count,offset);
1.1059    raeburn  12780:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12781:         form.elements[item].checked = true;
                   12782:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12783:             if (parents[count].length > 0) {
                   12784:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12785:                     containerCheck(form,parents[count][j],offset);
                   12786:                 }
                   12787:             }
                   12788:         }
                   12789:     }
                   12790: }
                   12791: 
                   12792: function dependencyCheck(form,count,offset) {
                   12793:     if (count > 0) {
1.1059    raeburn  12794:         var chosen = (offset+$startcount)+7*(count-1);
                   12795:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12796:         var currtype = form.elements[depitem].type;
                   12797:         if (form.elements[chosen].value == 'dependency') {
                   12798:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12799:             form.elements[depitem].options.length = 0;
                   12800:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12801:             for (var i=1; i<=numitems; i++) {
                   12802:                 if (i == count) {
                   12803:                     continue;
                   12804:                 }
1.1059    raeburn  12805:                 var startelement = $startcount + (i-1) * 7;
                   12806:                 for (var j=1; j<6; j++) {
                   12807:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12808:                         var item = startelement + j;
                   12809:                         if (form.elements[item].type == 'radio') {
                   12810:                             if (form.elements[item].checked) {
                   12811:                                 if (form.elements[item].value == 'display') {
                   12812:                                     var n = form.elements[depitem].options.length;
                   12813:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12814:                                 }
                   12815:                             }
                   12816:                         }
                   12817:                     }
                   12818:                 }
                   12819:             }
                   12820:         } else {
                   12821:             document.getElementById('arc_depon_'+count).style.display='none';
                   12822:             form.elements[depitem].options.length = 0;
                   12823:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12824:         }
1.1059    raeburn  12825:         titleCheck(form,count,offset);
1.1056    raeburn  12826:     }
                   12827: }
                   12828: 
                   12829: function propagateSelect(form,count,offset) {
                   12830:     if (count > 0) {
1.1065    raeburn  12831:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12832:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12833:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12834:             if (parents[count].length > 0) {
                   12835:                 for (var j=0; j<parents[count].length; j++) {
                   12836:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12837:                 }
                   12838:             }
                   12839:         }
                   12840:     }
                   12841: }
1.1056    raeburn  12842: 
                   12843: function containerSelect(form,count,offset,picked) {
                   12844:     if (count > 0) {
1.1065    raeburn  12845:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12846:         if (form.elements[item].type == 'radio') {
                   12847:             if (form.elements[item].value == 'dependency') {
                   12848:                 if (form.elements[item+1].type == 'select-one') {
                   12849:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12850:                         if (form.elements[item+1].options[i].value == picked) {
                   12851:                             form.elements[item+1].selectedIndex = i;
                   12852:                             break;
                   12853:                         }
                   12854:                     }
                   12855:                 }
                   12856:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12857:                     if (parents[count].length > 0) {
                   12858:                         for (var j=0; j<parents[count].length; j++) {
                   12859:                             containerSelect(form,parents[count][j],offset,picked);
                   12860:                         }
                   12861:                     }
                   12862:                 }
                   12863:             }
                   12864:         }
                   12865:     }
                   12866: }
                   12867: 
1.1059    raeburn  12868: function titleCheck(form,count,offset) {
                   12869:     if (count > 0) {
                   12870:         var chosen = (offset+$startcount)+7*(count-1);
                   12871:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12872:         var currtype = form.elements[depitem].type;
                   12873:         if (form.elements[chosen].value == 'display') {
                   12874:             document.getElementById('arc_title_'+count).style.display='block';
                   12875:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12876:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12877:             }
                   12878:         } else {
                   12879:             document.getElementById('arc_title_'+count).style.display='none';
                   12880:             if (currtype == 'text') { 
                   12881:                 document.getElementById('archive_title_'+count).value='';
                   12882:             }
                   12883:         }
                   12884:     }
                   12885:     return;
                   12886: }
                   12887: 
1.1055    raeburn  12888: // ]]>
                   12889: </script>
                   12890: END
                   12891:     return $scripttag;
                   12892: }
                   12893: 
                   12894: sub process_extracted_files {
1.1067    raeburn  12895:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12896:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12897:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12898:     my @ids=&Apache::lonnet::current_machine_ids();
                   12899:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12900:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12901:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12902:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12903:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12904:         $pathtocheck = "$dir_root/$destination";
                   12905:         $dir = $dir_root;
                   12906:         $ishome = 1;
                   12907:     } else {
                   12908:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12909:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12910:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12911:     }
                   12912:     my $currdir = "$dir_root/$destination";
                   12913:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12914:     if ($env{'form.folderpath'}) {
                   12915:         my @items = split('&',$env{'form.folderpath'});
                   12916:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12917:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12918:             $containers{'0'}='page';
                   12919:         } else {
                   12920:             $containers{'0'}='sequence';
                   12921:         }
1.1055    raeburn  12922:     }
                   12923:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12924:     if ($numitems) {
                   12925:         for (my $i=1; $i<=$numitems; $i++) {
                   12926:             my $path = $env{'form.archive_content_'.$i};
                   12927:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12928:                 my $item = $1;
                   12929:                 $toplevelitems{$item} = $i;
                   12930:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12931:                     $is_dir{$item} = 1;
                   12932:                 }
                   12933:             }
                   12934:         }
                   12935:     }
1.1067    raeburn  12936:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12937:     if (keys(%toplevelitems) > 0) {
                   12938:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12939:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12940:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12941:     }
1.1066    raeburn  12942:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12943:     if ($numitems) {
                   12944:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12945:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12946:             my $path = $env{'form.archive_content_'.$i};
                   12947:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12948:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12949:                     if ($prefix ne '' && $path ne '') {
                   12950:                         if (-e $prefix.$path) {
1.1066    raeburn  12951:                             if ((@archdirs > 0) && 
                   12952:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12953:                                 $todeletedir{$prefix.$path} = 1;
                   12954:                             } else {
                   12955:                                 $todelete{$prefix.$path} = 1;
                   12956:                             }
1.1055    raeburn  12957:                         }
                   12958:                     }
                   12959:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12960:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12961:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12962:                     $docstitle = $env{'form.archive_title_'.$i};
                   12963:                     if ($docstitle eq '') {
                   12964:                         $docstitle = $title;
                   12965:                     }
1.1055    raeburn  12966:                     $outer = 0;
1.1056    raeburn  12967:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12968:                         if (@{$dirorder{$i}} > 0) {
                   12969:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12970:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12971:                                     $outer = $item;
                   12972:                                     last;
                   12973:                                 }
                   12974:                             }
                   12975:                         }
                   12976:                     }
                   12977:                     my ($errtext,$fatal) = 
                   12978:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12979:                                                '/'.$folders{$outer}.'.'.
                   12980:                                                $containers{$outer});
                   12981:                     next if ($fatal);
                   12982:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12983:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12984:                             $mapinner{$i} = time;
1.1055    raeburn  12985:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12986:                             $containers{$i} = 'sequence';
                   12987:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12988:                                       $folders{$i}.'.'.$containers{$i};
                   12989:                             my $newidx = &LONCAPA::map::getresidx();
                   12990:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12991:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12992:                             push(@LONCAPA::map::order,$newidx);
                   12993:                             my ($outtext,$errtext) =
                   12994:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12995:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12996:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12997:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12998:                             unless ($errtext) {
1.1075.2.128  raeburn  12999:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13000:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13001:                                             '</li>'."\n";
1.1067    raeburn  13002:                             }
1.1055    raeburn  13003:                         }
                   13004:                     } else {
                   13005:                         if ($context eq 'coursedocs') {
                   13006:                             my $newidx=&LONCAPA::map::getresidx();
                   13007:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13008:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13009:                                       $title;
1.1075.2.128  raeburn  13010:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13011:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13012:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13013:                                 }
1.1075.2.128  raeburn  13014:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13015:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13016:                                 }
                   13017:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13018:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13019:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13020:                                         unless ($ishome) {
                   13021:                                             my $fetch = "$newdest{$i}/$title";
                   13022:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13023:                                             $prompttofetch{$fetch} = 1;
                   13024:                                         }
                   13025:                                    }
                   13026:                                 }
                   13027:                                 $LONCAPA::map::resources[$newidx]=
                   13028:                                     $docstitle.':'.$url.':false:normal:res';
                   13029:                                 push(@LONCAPA::map::order, $newidx);
                   13030:                                 my ($outtext,$errtext)=
                   13031:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13032:                                                             $docuname.'/'.$folders{$outer}.
                   13033:                                                             '.'.$containers{$outer},1,1);
                   13034:                                 unless ($errtext) {
                   13035:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13036:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13037:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13038:                                                    '</li>'."\n";
                   13039:                                     }
1.1067    raeburn  13040:                                 }
1.1075.2.128  raeburn  13041:                             } else {
                   13042:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13043:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13044:                             }
1.1055    raeburn  13045:                         }
                   13046:                     }
1.1075.2.11  raeburn  13047:                 }
                   13048:             } else {
1.1075.2.128  raeburn  13049:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13050:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13051:             }
                   13052:         }
                   13053:         for (my $i=1; $i<=$numitems; $i++) {
                   13054:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13055:             my $path = $env{'form.archive_content_'.$i};
                   13056:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13057:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13058:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13059:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13060:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13061:                         my ($itemidx,$fullpath,$relpath);
                   13062:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13063:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13064:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13065:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13066:                                     $itemidx = $j;
1.1056    raeburn  13067:                                 }
                   13068:                             }
1.1075.2.11  raeburn  13069:                         }
                   13070:                         if ($itemidx eq '') {
                   13071:                             $itemidx =  0;
                   13072:                         }
                   13073:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13074:                             if ($mapinner{$referrer{$i}}) {
                   13075:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13076:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13077:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13078:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13079:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13080:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13081:                                             if (!-e $fullpath) {
                   13082:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13083:                                             }
                   13084:                                         }
1.1075.2.11  raeburn  13085:                                     } else {
                   13086:                                         last;
1.1056    raeburn  13087:                                     }
1.1075.2.11  raeburn  13088:                                 }
                   13089:                             }
                   13090:                         } elsif ($newdest{$referrer{$i}}) {
                   13091:                             $fullpath = $newdest{$referrer{$i}};
                   13092:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13093:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13094:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13095:                                     last;
                   13096:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13097:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13098:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13099:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13100:                                         if (!-e $fullpath) {
                   13101:                                             mkdir($fullpath,0755);
1.1056    raeburn  13102:                                         }
                   13103:                                     }
1.1075.2.11  raeburn  13104:                                 } else {
                   13105:                                     last;
1.1056    raeburn  13106:                                 }
1.1075.2.11  raeburn  13107:                             }
                   13108:                         }
                   13109:                         if ($fullpath ne '') {
                   13110:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13111:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13112:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13113:                                 }
1.1075.2.11  raeburn  13114:                             }
                   13115:                             if (-e "$fullpath/$title") {
                   13116:                                 my $showpath;
                   13117:                                 if ($relpath ne '') {
                   13118:                                     $showpath = "$relpath/$title";
                   13119:                                 } else {
                   13120:                                     $showpath = "/$title";
1.1056    raeburn  13121:                                 }
1.1075.2.128  raeburn  13122:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13123:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13124:                                            '</li>'."\n";
                   13125:                                 unless ($ishome) {
                   13126:                                     my $fetch = "$fullpath/$title";
                   13127:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13128:                                     $prompttofetch{$fetch} = 1;
                   13129:                                 }
1.1055    raeburn  13130:                             }
                   13131:                         }
                   13132:                     }
1.1075.2.11  raeburn  13133:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13134:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13135:                                     &HTML::Entities::encode($path,'<>&"'),
                   13136:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13137:                                 '<br />';
1.1055    raeburn  13138:                 }
                   13139:             } else {
1.1075.2.128  raeburn  13140:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13141:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13142:             }
                   13143:         }
                   13144:         if (keys(%todelete)) {
                   13145:             foreach my $key (keys(%todelete)) {
                   13146:                 unlink($key);
1.1066    raeburn  13147:             }
                   13148:         }
                   13149:         if (keys(%todeletedir)) {
                   13150:             foreach my $key (keys(%todeletedir)) {
                   13151:                 rmdir($key);
                   13152:             }
                   13153:         }
                   13154:         foreach my $dir (sort(keys(%is_dir))) {
                   13155:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13156:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13157:             }
                   13158:         }
1.1067    raeburn  13159:         if ($result ne '') {
                   13160:             $output .= '<ul>'."\n".
                   13161:                        $result."\n".
                   13162:                        '</ul>';
                   13163:         }
                   13164:         unless ($ishome) {
                   13165:             my $replicationfail;
                   13166:             foreach my $item (keys(%prompttofetch)) {
                   13167:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13168:                 unless ($fetchresult eq 'ok') {
                   13169:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13170:                 }
                   13171:             }
                   13172:             if ($replicationfail) {
                   13173:                 $output .= '<p class="LC_error">'.
                   13174:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13175:                            $replicationfail.
                   13176:                            '</ul></p>';
                   13177:             }
                   13178:         }
1.1055    raeburn  13179:     } else {
                   13180:         $warning = &mt('No items found in archive.');
                   13181:     }
                   13182:     if ($error) {
                   13183:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13184:                    $error.'</p>'."\n";
                   13185:     }
                   13186:     if ($warning) {
                   13187:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13188:     }
                   13189:     return $output;
                   13190: }
                   13191: 
1.1066    raeburn  13192: sub cleanup_empty_dirs {
                   13193:     my ($path) = @_;
                   13194:     if (($path ne '') && (-d $path)) {
                   13195:         if (opendir(my $dirh,$path)) {
                   13196:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13197:             my $numitems = 0;
                   13198:             foreach my $item (@dircontents) {
                   13199:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13200:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13201:                     if (-e "$path/$item") {
                   13202:                         $numitems ++;
                   13203:                     }
                   13204:                 } else {
                   13205:                     $numitems ++;
                   13206:                 }
                   13207:             }
                   13208:             if ($numitems == 0) {
                   13209:                 rmdir($path);
                   13210:             }
                   13211:             closedir($dirh);
                   13212:         }
                   13213:     }
                   13214:     return;
                   13215: }
                   13216: 
1.41      ng       13217: =pod
1.45      matthew  13218: 
1.1075.2.56  raeburn  13219: =item * &get_folder_hierarchy()
1.1068    raeburn  13220: 
                   13221: Provides hierarchy of names of folders/sub-folders containing the current
                   13222: item,
                   13223: 
                   13224: Inputs: 3
                   13225:      - $navmap - navmaps object
                   13226: 
                   13227:      - $map - url for map (either the trigger itself, or map containing
                   13228:                            the resource, which is the trigger).
                   13229: 
                   13230:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13231: 
                   13232: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13233: 
                   13234: =cut
                   13235: 
                   13236: sub get_folder_hierarchy {
                   13237:     my ($navmap,$map,$showitem) = @_;
                   13238:     my @pathitems;
                   13239:     if (ref($navmap)) {
                   13240:         my $mapres = $navmap->getResourceByUrl($map);
                   13241:         if (ref($mapres)) {
                   13242:             my $pcslist = $mapres->map_hierarchy();
                   13243:             if ($pcslist ne '') {
                   13244:                 my @pcs = split(/,/,$pcslist);
                   13245:                 foreach my $pc (@pcs) {
                   13246:                     if ($pc == 1) {
1.1075.2.38  raeburn  13247:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13248:                     } else {
                   13249:                         my $res = $navmap->getByMapPc($pc);
                   13250:                         if (ref($res)) {
                   13251:                             my $title = $res->compTitle();
                   13252:                             $title =~ s/\W+/_/g;
                   13253:                             if ($title ne '') {
                   13254:                                 push(@pathitems,$title);
                   13255:                             }
                   13256:                         }
                   13257:                     }
                   13258:                 }
                   13259:             }
1.1071    raeburn  13260:             if ($showitem) {
                   13261:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13262:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13263:                 } else {
                   13264:                     my $maptitle = $mapres->compTitle();
                   13265:                     $maptitle =~ s/\W+/_/g;
                   13266:                     if ($maptitle ne '') {
                   13267:                         push(@pathitems,$maptitle);
                   13268:                     }
1.1068    raeburn  13269:                 }
                   13270:             }
                   13271:         }
                   13272:     }
                   13273:     return @pathitems;
                   13274: }
                   13275: 
                   13276: =pod
                   13277: 
1.1015    raeburn  13278: =item * &get_turnedin_filepath()
                   13279: 
                   13280: Determines path in a user's portfolio file for storage of files uploaded
                   13281: to a specific essayresponse or dropbox item.
                   13282: 
                   13283: Inputs: 3 required + 1 optional.
                   13284: $symb is symb for resource, $uname and $udom are for current user (required).
                   13285: $caller is optional (can be "submission", if routine is called when storing
                   13286: an upoaded file when "Submit Answer" button was pressed).
                   13287: 
                   13288: Returns array containing $path and $multiresp. 
                   13289: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13290: than one file upload item.  Callers of routine should append partid as a 
                   13291: subdirectory to $path in cases where $multiresp is 1.
                   13292: 
                   13293: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13294: 
                   13295: =cut
                   13296: 
                   13297: sub get_turnedin_filepath {
                   13298:     my ($symb,$uname,$udom,$caller) = @_;
                   13299:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13300:     my $turnindir;
                   13301:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13302:     $turnindir = $userhash{'turnindir'};
                   13303:     my ($path,$multiresp);
                   13304:     if ($turnindir eq '') {
                   13305:         if ($caller eq 'submission') {
                   13306:             $turnindir = &mt('turned in');
                   13307:             $turnindir =~ s/\W+/_/g;
                   13308:             my %newhash = (
                   13309:                             'turnindir' => $turnindir,
                   13310:                           );
                   13311:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13312:         }
                   13313:     }
                   13314:     if ($turnindir ne '') {
                   13315:         $path = '/'.$turnindir.'/';
                   13316:         my ($multipart,$turnin,@pathitems);
                   13317:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13318:         if (defined($navmap)) {
                   13319:             my $mapres = $navmap->getResourceByUrl($map);
                   13320:             if (ref($mapres)) {
                   13321:                 my $pcslist = $mapres->map_hierarchy();
                   13322:                 if ($pcslist ne '') {
                   13323:                     foreach my $pc (split(/,/,$pcslist)) {
                   13324:                         my $res = $navmap->getByMapPc($pc);
                   13325:                         if (ref($res)) {
                   13326:                             my $title = $res->compTitle();
                   13327:                             $title =~ s/\W+/_/g;
                   13328:                             if ($title ne '') {
1.1075.2.48  raeburn  13329:                                 if (($pc > 1) && (length($title) > 12)) {
                   13330:                                     $title = substr($title,0,12);
                   13331:                                 }
1.1015    raeburn  13332:                                 push(@pathitems,$title);
                   13333:                             }
                   13334:                         }
                   13335:                     }
                   13336:                 }
                   13337:                 my $maptitle = $mapres->compTitle();
                   13338:                 $maptitle =~ s/\W+/_/g;
                   13339:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13340:                     if (length($maptitle) > 12) {
                   13341:                         $maptitle = substr($maptitle,0,12);
                   13342:                     }
1.1015    raeburn  13343:                     push(@pathitems,$maptitle);
                   13344:                 }
                   13345:                 unless ($env{'request.state'} eq 'construct') {
                   13346:                     my $res = $navmap->getBySymb($symb);
                   13347:                     if (ref($res)) {
                   13348:                         my $partlist = $res->parts();
                   13349:                         my $totaluploads = 0;
                   13350:                         if (ref($partlist) eq 'ARRAY') {
                   13351:                             foreach my $part (@{$partlist}) {
                   13352:                                 my @types = $res->responseType($part);
                   13353:                                 my @ids = $res->responseIds($part);
                   13354:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13355:                                     if ($types[$i] eq 'essay') {
                   13356:                                         my $partid = $part.'_'.$ids[$i];
                   13357:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13358:                                             $totaluploads ++;
                   13359:                                         }
                   13360:                                     }
                   13361:                                 }
                   13362:                             }
                   13363:                             if ($totaluploads > 1) {
                   13364:                                 $multiresp = 1;
                   13365:                             }
                   13366:                         }
                   13367:                     }
                   13368:                 }
                   13369:             } else {
                   13370:                 return;
                   13371:             }
                   13372:         } else {
                   13373:             return;
                   13374:         }
                   13375:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13376:         $restitle =~ s/\W+/_/g;
                   13377:         if ($restitle eq '') {
                   13378:             $restitle = ($resurl =~ m{/[^/]+$});
                   13379:             if ($restitle eq '') {
                   13380:                 $restitle = time;
                   13381:             }
                   13382:         }
1.1075.2.48  raeburn  13383:         if (length($restitle) > 12) {
                   13384:             $restitle = substr($restitle,0,12);
                   13385:         }
1.1015    raeburn  13386:         push(@pathitems,$restitle);
                   13387:         $path .= join('/',@pathitems);
                   13388:     }
                   13389:     return ($path,$multiresp);
                   13390: }
                   13391: 
                   13392: =pod
                   13393: 
1.464     albertel 13394: =back
1.41      ng       13395: 
1.112     bowersj2 13396: =head1 CSV Upload/Handling functions
1.38      albertel 13397: 
1.41      ng       13398: =over 4
                   13399: 
1.648     raeburn  13400: =item * &upfile_store($r)
1.41      ng       13401: 
                   13402: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13403: needs $env{'form.upfile'}
1.41      ng       13404: returns $datatoken to be put into hidden field
                   13405: 
                   13406: =cut
1.31      albertel 13407: 
                   13408: sub upfile_store {
                   13409:     my $r=shift;
1.258     albertel 13410:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13411:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13412:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13413:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13414: 
1.1075.2.128  raeburn  13415:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13416:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13417:                                      time.'_'.$$);
                   13418:     return if ($datatoken eq '');
                   13419: 
1.31      albertel 13420:     {
1.158     raeburn  13421:         my $datafile = $r->dir_config('lonDaemons').
                   13422:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13423:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13424:             print $fh $env{'form.upfile'};
1.158     raeburn  13425:             close($fh);
                   13426:         }
1.31      albertel 13427:     }
                   13428:     return $datatoken;
                   13429: }
                   13430: 
1.56      matthew  13431: =pod
                   13432: 
1.1075.2.128  raeburn  13433: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13434: 
                   13435: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13436: $datatoken is the name to assign to the temporary file.
1.258     albertel 13437: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13438: 
                   13439: =cut
1.31      albertel 13440: 
                   13441: sub load_tmp_file {
1.1075.2.128  raeburn  13442:     my ($r,$datatoken) = @_;
                   13443:     return if ($datatoken eq '');
1.31      albertel 13444:     my @studentdata=();
                   13445:     {
1.158     raeburn  13446:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13447:                               '/tmp/'.$datatoken.'.tmp';
                   13448:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13449:             @studentdata=<$fh>;
                   13450:             close($fh);
                   13451:         }
1.31      albertel 13452:     }
1.258     albertel 13453:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13454: }
                   13455: 
1.1075.2.128  raeburn  13456: sub valid_datatoken {
                   13457:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13458:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13459:         return $datatoken;
                   13460:     }
                   13461:     return;
                   13462: }
                   13463: 
1.56      matthew  13464: =pod
                   13465: 
1.648     raeburn  13466: =item * &upfile_record_sep()
1.41      ng       13467: 
                   13468: Separate uploaded file into records
                   13469: returns array of records,
1.258     albertel 13470: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13471: 
                   13472: =cut
1.31      albertel 13473: 
                   13474: sub upfile_record_sep {
1.258     albertel 13475:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13476:     } else {
1.248     albertel 13477: 	my @records;
1.258     albertel 13478: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13479: 	    if ($line=~/^\s*$/) { next; }
                   13480: 	    push(@records,$line);
                   13481: 	}
                   13482: 	return @records;
1.31      albertel 13483:     }
                   13484: }
                   13485: 
1.56      matthew  13486: =pod
                   13487: 
1.648     raeburn  13488: =item * &record_sep($record)
1.41      ng       13489: 
1.258     albertel 13490: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13491: 
                   13492: =cut
                   13493: 
1.263     www      13494: sub takeleft {
                   13495:     my $index=shift;
                   13496:     return substr('0000'.$index,-4,4);
                   13497: }
                   13498: 
1.31      albertel 13499: sub record_sep {
                   13500:     my $record=shift;
                   13501:     my %components=();
1.258     albertel 13502:     if ($env{'form.upfiletype'} eq 'xml') {
                   13503:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13504:         my $i=0;
1.356     albertel 13505:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13506:             $field=~s/^(\"|\')//;
                   13507:             $field=~s/(\"|\')$//;
1.263     www      13508:             $components{&takeleft($i)}=$field;
1.31      albertel 13509:             $i++;
                   13510:         }
1.258     albertel 13511:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13512:         my $i=0;
1.356     albertel 13513:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13514:             $field=~s/^(\"|\')//;
                   13515:             $field=~s/(\"|\')$//;
1.263     www      13516:             $components{&takeleft($i)}=$field;
1.31      albertel 13517:             $i++;
                   13518:         }
                   13519:     } else {
1.561     www      13520:         my $separator=',';
1.480     banghart 13521:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13522:             $separator=';';
1.480     banghart 13523:         }
1.31      albertel 13524:         my $i=0;
1.561     www      13525: # the character we are looking for to indicate the end of a quote or a record 
                   13526:         my $looking_for=$separator;
                   13527: # do not add the characters to the fields
                   13528:         my $ignore=0;
                   13529: # we just encountered a separator (or the beginning of the record)
                   13530:         my $just_found_separator=1;
                   13531: # store the field we are working on here
                   13532:         my $field='';
                   13533: # work our way through all characters in record
                   13534:         foreach my $character ($record=~/(.)/g) {
                   13535:             if ($character eq $looking_for) {
                   13536:                if ($character ne $separator) {
                   13537: # Found the end of a quote, again looking for separator
                   13538:                   $looking_for=$separator;
                   13539:                   $ignore=1;
                   13540:                } else {
                   13541: # Found a separator, store away what we got
                   13542:                   $components{&takeleft($i)}=$field;
                   13543: 	          $i++;
                   13544:                   $just_found_separator=1;
                   13545:                   $ignore=0;
                   13546:                   $field='';
                   13547:                }
                   13548:                next;
                   13549:             }
                   13550: # single or double quotation marks after a separator indicate beginning of a quote
                   13551: # we are now looking for the end of the quote and need to ignore separators
                   13552:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13553:                $looking_for=$character;
                   13554:                next;
                   13555:             }
                   13556: # ignore would be true after we reached the end of a quote
                   13557:             if ($ignore) { next; }
                   13558:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13559:             $field.=$character;
                   13560:             $just_found_separator=0; 
1.31      albertel 13561:         }
1.561     www      13562: # catch the very last entry, since we never encountered the separator
                   13563:         $components{&takeleft($i)}=$field;
1.31      albertel 13564:     }
                   13565:     return %components;
                   13566: }
                   13567: 
1.144     matthew  13568: ######################################################
                   13569: ######################################################
                   13570: 
1.56      matthew  13571: =pod
                   13572: 
1.648     raeburn  13573: =item * &upfile_select_html()
1.41      ng       13574: 
1.144     matthew  13575: Return HTML code to select a file from the users machine and specify 
                   13576: the file type.
1.41      ng       13577: 
                   13578: =cut
                   13579: 
1.144     matthew  13580: ######################################################
                   13581: ######################################################
1.31      albertel 13582: sub upfile_select_html {
1.144     matthew  13583:     my %Types = (
                   13584:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13585:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13586:                  space => &mt('Space separated'),
                   13587:                  tab   => &mt('Tabulator separated'),
                   13588: #                 xml   => &mt('HTML/XML'),
                   13589:                  );
                   13590:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13591:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13592:     foreach my $type (sort(keys(%Types))) {
                   13593:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13594:     }
                   13595:     $Str .= "</select>\n";
                   13596:     return $Str;
1.31      albertel 13597: }
                   13598: 
1.301     albertel 13599: sub get_samples {
                   13600:     my ($records,$toget) = @_;
                   13601:     my @samples=({});
                   13602:     my $got=0;
                   13603:     foreach my $rec (@$records) {
                   13604: 	my %temp = &record_sep($rec);
                   13605: 	if (! grep(/\S/, values(%temp))) { next; }
                   13606: 	if (%temp) {
                   13607: 	    $samples[$got]=\%temp;
                   13608: 	    $got++;
                   13609: 	    if ($got == $toget) { last; }
                   13610: 	}
                   13611:     }
                   13612:     return \@samples;
                   13613: }
                   13614: 
1.144     matthew  13615: ######################################################
                   13616: ######################################################
                   13617: 
1.56      matthew  13618: =pod
                   13619: 
1.648     raeburn  13620: =item * &csv_print_samples($r,$records)
1.41      ng       13621: 
                   13622: Prints a table of sample values from each column uploaded $r is an
                   13623: Apache Request ref, $records is an arrayref from
                   13624: &Apache::loncommon::upfile_record_sep
                   13625: 
                   13626: =cut
                   13627: 
1.144     matthew  13628: ######################################################
                   13629: ######################################################
1.31      albertel 13630: sub csv_print_samples {
                   13631:     my ($r,$records) = @_;
1.662     bisitz   13632:     my $samples = &get_samples($records,5);
1.301     albertel 13633: 
1.594     raeburn  13634:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13635:               &start_data_table_header_row());
1.356     albertel 13636:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13637:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13638:     $r->print(&end_data_table_header_row());
1.301     albertel 13639:     foreach my $hash (@$samples) {
1.594     raeburn  13640: 	$r->print(&start_data_table_row());
1.356     albertel 13641: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13642: 	    $r->print('<td>');
1.356     albertel 13643: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13644: 	    $r->print('</td>');
                   13645: 	}
1.594     raeburn  13646: 	$r->print(&end_data_table_row());
1.31      albertel 13647:     }
1.594     raeburn  13648:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13649: }
                   13650: 
1.144     matthew  13651: ######################################################
                   13652: ######################################################
                   13653: 
1.56      matthew  13654: =pod
                   13655: 
1.648     raeburn  13656: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13657: 
                   13658: Prints a table to create associations between values and table columns.
1.144     matthew  13659: 
1.41      ng       13660: $r is an Apache Request ref,
                   13661: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13662: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13663: 
                   13664: =cut
                   13665: 
1.144     matthew  13666: ######################################################
                   13667: ######################################################
1.31      albertel 13668: sub csv_print_select_table {
                   13669:     my ($r,$records,$d) = @_;
1.301     albertel 13670:     my $i=0;
                   13671:     my $samples = &get_samples($records,1);
1.144     matthew  13672:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13673: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13674:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13675:               '<th>'.&mt('Column').'</th>'.
                   13676:               &end_data_table_header_row()."\n");
1.356     albertel 13677:     foreach my $array_ref (@$d) {
                   13678: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13679: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13680: 
1.875     bisitz   13681: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13682: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13683: 	$r->print('<option value="none"></option>');
1.356     albertel 13684: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13685: 	    $r->print('<option value="'.$sample.'"'.
                   13686:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13687:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13688: 	}
1.594     raeburn  13689: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13690: 	$i++;
                   13691:     }
1.594     raeburn  13692:     $r->print(&end_data_table());
1.31      albertel 13693:     $i--;
                   13694:     return $i;
                   13695: }
1.56      matthew  13696: 
1.144     matthew  13697: ######################################################
                   13698: ######################################################
                   13699: 
1.56      matthew  13700: =pod
1.31      albertel 13701: 
1.648     raeburn  13702: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13703: 
                   13704: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13705: 
                   13706: $r is an Apache Request ref,
                   13707: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13708: $d is an array of 2 element arrays (internal name, displayed name)
                   13709: 
                   13710: =cut
                   13711: 
1.144     matthew  13712: ######################################################
                   13713: ######################################################
1.31      albertel 13714: sub csv_samples_select_table {
                   13715:     my ($r,$records,$d) = @_;
                   13716:     my $i=0;
1.144     matthew  13717:     #
1.662     bisitz   13718:     my $max_samples = 5;
                   13719:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13720:     $r->print(&start_data_table().
                   13721:               &start_data_table_header_row().'<th>'.
                   13722:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13723:               &end_data_table_header_row());
1.301     albertel 13724: 
                   13725:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13726: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13727: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13728: 	foreach my $option (@$d) {
                   13729: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13730: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13731:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13732:                       $display.'</option>');
1.31      albertel 13733: 	}
                   13734: 	$r->print('</select></td><td>');
1.662     bisitz   13735: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13736: 	    if (defined($samples->[$line]{$key})) { 
                   13737: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13738: 	    }
                   13739: 	}
1.594     raeburn  13740: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13741: 	$i++;
                   13742:     }
1.594     raeburn  13743:     $r->print(&end_data_table());
1.31      albertel 13744:     $i--;
                   13745:     return($i);
1.115     matthew  13746: }
                   13747: 
1.144     matthew  13748: ######################################################
                   13749: ######################################################
                   13750: 
1.115     matthew  13751: =pod
                   13752: 
1.648     raeburn  13753: =item * &clean_excel_name($name)
1.115     matthew  13754: 
                   13755: Returns a replacement for $name which does not contain any illegal characters.
                   13756: 
                   13757: =cut
                   13758: 
1.144     matthew  13759: ######################################################
                   13760: ######################################################
1.115     matthew  13761: sub clean_excel_name {
                   13762:     my ($name) = @_;
                   13763:     $name =~ s/[:\*\?\/\\]//g;
                   13764:     if (length($name) > 31) {
                   13765:         $name = substr($name,0,31);
                   13766:     }
                   13767:     return $name;
1.25      albertel 13768: }
1.84      albertel 13769: 
1.85      albertel 13770: =pod
                   13771: 
1.648     raeburn  13772: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13773: 
                   13774: Returns either 1 or undef
                   13775: 
                   13776: 1 if the part is to be hidden, undef if it is to be shown
                   13777: 
                   13778: Arguments are:
                   13779: 
                   13780: $id the id of the part to be checked
                   13781: $symb, optional the symb of the resource to check
                   13782: $udom, optional the domain of the user to check for
                   13783: $uname, optional the username of the user to check for
                   13784: 
                   13785: =cut
1.84      albertel 13786: 
                   13787: sub check_if_partid_hidden {
                   13788:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13789:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13790: 					 $symb,$udom,$uname);
1.141     albertel 13791:     my $truth=1;
                   13792:     #if the string starts with !, then the list is the list to show not hide
                   13793:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13794:     my @hiddenlist=split(/,/,$hiddenparts);
                   13795:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13796: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13797:     }
1.141     albertel 13798:     return !$truth;
1.84      albertel 13799: }
1.127     matthew  13800: 
1.138     matthew  13801: 
                   13802: ############################################################
                   13803: ############################################################
                   13804: 
                   13805: =pod
                   13806: 
1.157     matthew  13807: =back 
                   13808: 
1.138     matthew  13809: =head1 cgi-bin script and graphing routines
                   13810: 
1.157     matthew  13811: =over 4
                   13812: 
1.648     raeburn  13813: =item * &get_cgi_id()
1.138     matthew  13814: 
                   13815: Inputs: none
                   13816: 
                   13817: Returns an id which can be used to pass environment variables
                   13818: to various cgi-bin scripts.  These environment variables will
                   13819: be removed from the users environment after a given time by
                   13820: the routine &Apache::lonnet::transfer_profile_to_env.
                   13821: 
                   13822: =cut
                   13823: 
                   13824: ############################################################
                   13825: ############################################################
1.152     albertel 13826: my $uniq=0;
1.136     matthew  13827: sub get_cgi_id {
1.154     albertel 13828:     $uniq=($uniq+1)%100000;
1.280     albertel 13829:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13830: }
                   13831: 
1.127     matthew  13832: ############################################################
                   13833: ############################################################
                   13834: 
                   13835: =pod
                   13836: 
1.648     raeburn  13837: =item * &DrawBarGraph()
1.127     matthew  13838: 
1.138     matthew  13839: Facilitates the plotting of data in a (stacked) bar graph.
                   13840: Puts plot definition data into the users environment in order for 
                   13841: graph.png to plot it.  Returns an <img> tag for the plot.
                   13842: The bars on the plot are labeled '1','2',...,'n'.
                   13843: 
                   13844: Inputs:
                   13845: 
                   13846: =over 4
                   13847: 
                   13848: =item $Title: string, the title of the plot
                   13849: 
                   13850: =item $xlabel: string, text describing the X-axis of the plot
                   13851: 
                   13852: =item $ylabel: string, text describing the Y-axis of the plot
                   13853: 
                   13854: =item $Max: scalar, the maximum Y value to use in the plot
                   13855: If $Max is < any data point, the graph will not be rendered.
                   13856: 
1.140     matthew  13857: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13858: they are plotted.  If undefined, default values will be used.
                   13859: 
1.178     matthew  13860: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13861: 
1.138     matthew  13862: =item @Values: An array of array references.  Each array reference holds data
                   13863: to be plotted in a stacked bar chart.
                   13864: 
1.239     matthew  13865: =item If the final element of @Values is a hash reference the key/value
                   13866: pairs will be added to the graph definition.
                   13867: 
1.138     matthew  13868: =back
                   13869: 
                   13870: Returns:
                   13871: 
                   13872: An <img> tag which references graph.png and the appropriate identifying
                   13873: information for the plot.
                   13874: 
1.127     matthew  13875: =cut
                   13876: 
                   13877: ############################################################
                   13878: ############################################################
1.134     matthew  13879: sub DrawBarGraph {
1.178     matthew  13880:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13881:     #
                   13882:     if (! defined($colors)) {
                   13883:         $colors = ['#33ff00', 
                   13884:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13885:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13886:                   ]; 
                   13887:     }
1.228     matthew  13888:     my $extra_settings = {};
                   13889:     if (ref($Values[-1]) eq 'HASH') {
                   13890:         $extra_settings = pop(@Values);
                   13891:     }
1.127     matthew  13892:     #
1.136     matthew  13893:     my $identifier = &get_cgi_id();
                   13894:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13895:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13896:         return '';
                   13897:     }
1.225     matthew  13898:     #
                   13899:     my @Labels;
                   13900:     if (defined($labels)) {
                   13901:         @Labels = @$labels;
                   13902:     } else {
                   13903:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13904:             push(@Labels,$i+1);
1.225     matthew  13905:         }
                   13906:     }
                   13907:     #
1.129     matthew  13908:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13909:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13910:     my %ValuesHash;
                   13911:     my $NumSets=1;
                   13912:     foreach my $array (@Values) {
                   13913:         next if (! ref($array));
1.136     matthew  13914:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13915:             join(',',@$array);
1.129     matthew  13916:     }
1.127     matthew  13917:     #
1.136     matthew  13918:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13919:     if ($NumBars < 3) {
                   13920:         $width = 120+$NumBars*32;
1.220     matthew  13921:         $xskip = 1;
1.225     matthew  13922:         $bar_width = 30;
                   13923:     } elsif ($NumBars < 5) {
                   13924:         $width = 120+$NumBars*20;
                   13925:         $xskip = 1;
                   13926:         $bar_width = 20;
1.220     matthew  13927:     } elsif ($NumBars < 10) {
1.136     matthew  13928:         $width = 120+$NumBars*15;
                   13929:         $xskip = 1;
                   13930:         $bar_width = 15;
                   13931:     } elsif ($NumBars <= 25) {
                   13932:         $width = 120+$NumBars*11;
                   13933:         $xskip = 5;
                   13934:         $bar_width = 8;
                   13935:     } elsif ($NumBars <= 50) {
                   13936:         $width = 120+$NumBars*8;
                   13937:         $xskip = 5;
                   13938:         $bar_width = 4;
                   13939:     } else {
                   13940:         $width = 120+$NumBars*8;
                   13941:         $xskip = 5;
                   13942:         $bar_width = 4;
                   13943:     }
                   13944:     #
1.137     matthew  13945:     $Max = 1 if ($Max < 1);
                   13946:     if ( int($Max) < $Max ) {
                   13947:         $Max++;
                   13948:         $Max = int($Max);
                   13949:     }
1.127     matthew  13950:     $Title  = '' if (! defined($Title));
                   13951:     $xlabel = '' if (! defined($xlabel));
                   13952:     $ylabel = '' if (! defined($ylabel));
1.369     www      13953:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13954:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13955:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13956:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13957:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13958:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13959:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13960:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13961:     $ValuesHash{$id.'.height'}   = $height;
                   13962:     $ValuesHash{$id.'.width'}    = $width;
                   13963:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13964:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13965:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13966:     #
1.228     matthew  13967:     # Deal with other parameters
                   13968:     while (my ($key,$value) = each(%$extra_settings)) {
                   13969:         $ValuesHash{$id.'.'.$key} = $value;
                   13970:     }
                   13971:     #
1.646     raeburn  13972:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13973:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13974: }
                   13975: 
                   13976: ############################################################
                   13977: ############################################################
                   13978: 
                   13979: =pod
                   13980: 
1.648     raeburn  13981: =item * &DrawXYGraph()
1.137     matthew  13982: 
1.138     matthew  13983: Facilitates the plotting of data in an XY graph.
                   13984: Puts plot definition data into the users environment in order for 
                   13985: graph.png to plot it.  Returns an <img> tag for the plot.
                   13986: 
                   13987: Inputs:
                   13988: 
                   13989: =over 4
                   13990: 
                   13991: =item $Title: string, the title of the plot
                   13992: 
                   13993: =item $xlabel: string, text describing the X-axis of the plot
                   13994: 
                   13995: =item $ylabel: string, text describing the Y-axis of the plot
                   13996: 
                   13997: =item $Max: scalar, the maximum Y value to use in the plot
                   13998: If $Max is < any data point, the graph will not be rendered.
                   13999: 
                   14000: =item $colors: Array ref containing the hex color codes for the data to be 
                   14001: plotted in.  If undefined, default values will be used.
                   14002: 
                   14003: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14004: 
                   14005: =item $Ydata: Array ref containing Array refs.  
1.185     www      14006: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14007: 
                   14008: =item %Values: hash indicating or overriding any default values which are 
                   14009: passed to graph.png.  
                   14010: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14011: 
                   14012: =back
                   14013: 
                   14014: Returns:
                   14015: 
                   14016: An <img> tag which references graph.png and the appropriate identifying
                   14017: information for the plot.
                   14018: 
1.137     matthew  14019: =cut
                   14020: 
                   14021: ############################################################
                   14022: ############################################################
                   14023: sub DrawXYGraph {
                   14024:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14025:     #
                   14026:     # Create the identifier for the graph
                   14027:     my $identifier = &get_cgi_id();
                   14028:     my $id = 'cgi.'.$identifier;
                   14029:     #
                   14030:     $Title  = '' if (! defined($Title));
                   14031:     $xlabel = '' if (! defined($xlabel));
                   14032:     $ylabel = '' if (! defined($ylabel));
                   14033:     my %ValuesHash = 
                   14034:         (
1.369     www      14035:          $id.'.title'  => &escape($Title),
                   14036:          $id.'.xlabel' => &escape($xlabel),
                   14037:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14038:          $id.'.y_max_value'=> $Max,
                   14039:          $id.'.labels'     => join(',',@$Xlabels),
                   14040:          $id.'.PlotType'   => 'XY',
                   14041:          );
                   14042:     #
                   14043:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14044:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14045:     }
                   14046:     #
                   14047:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14048:         return '';
                   14049:     }
                   14050:     my $NumSets=1;
1.138     matthew  14051:     foreach my $array (@{$Ydata}){
1.137     matthew  14052:         next if (! ref($array));
                   14053:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14054:     }
1.138     matthew  14055:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14056:     #
                   14057:     # Deal with other parameters
                   14058:     while (my ($key,$value) = each(%Values)) {
                   14059:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14060:     }
                   14061:     #
1.646     raeburn  14062:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14063:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14064: }
                   14065: 
                   14066: ############################################################
                   14067: ############################################################
                   14068: 
                   14069: =pod
                   14070: 
1.648     raeburn  14071: =item * &DrawXYYGraph()
1.138     matthew  14072: 
                   14073: Facilitates the plotting of data in an XY graph with two Y axes.
                   14074: Puts plot definition data into the users environment in order for 
                   14075: graph.png to plot it.  Returns an <img> tag for the plot.
                   14076: 
                   14077: Inputs:
                   14078: 
                   14079: =over 4
                   14080: 
                   14081: =item $Title: string, the title of the plot
                   14082: 
                   14083: =item $xlabel: string, text describing the X-axis of the plot
                   14084: 
                   14085: =item $ylabel: string, text describing the Y-axis of the plot
                   14086: 
                   14087: =item $colors: Array ref containing the hex color codes for the data to be 
                   14088: plotted in.  If undefined, default values will be used.
                   14089: 
                   14090: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14091: 
                   14092: =item $Ydata1: The first data set
                   14093: 
                   14094: =item $Min1: The minimum value of the left Y-axis
                   14095: 
                   14096: =item $Max1: The maximum value of the left Y-axis
                   14097: 
                   14098: =item $Ydata2: The second data set
                   14099: 
                   14100: =item $Min2: The minimum value of the right Y-axis
                   14101: 
                   14102: =item $Max2: The maximum value of the left Y-axis
                   14103: 
                   14104: =item %Values: hash indicating or overriding any default values which are 
                   14105: passed to graph.png.  
                   14106: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14107: 
                   14108: =back
                   14109: 
                   14110: Returns:
                   14111: 
                   14112: An <img> tag which references graph.png and the appropriate identifying
                   14113: information for the plot.
1.136     matthew  14114: 
                   14115: =cut
                   14116: 
                   14117: ############################################################
                   14118: ############################################################
1.137     matthew  14119: sub DrawXYYGraph {
                   14120:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14121:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14122:     #
                   14123:     # Create the identifier for the graph
                   14124:     my $identifier = &get_cgi_id();
                   14125:     my $id = 'cgi.'.$identifier;
                   14126:     #
                   14127:     $Title  = '' if (! defined($Title));
                   14128:     $xlabel = '' if (! defined($xlabel));
                   14129:     $ylabel = '' if (! defined($ylabel));
                   14130:     my %ValuesHash = 
                   14131:         (
1.369     www      14132:          $id.'.title'  => &escape($Title),
                   14133:          $id.'.xlabel' => &escape($xlabel),
                   14134:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14135:          $id.'.labels' => join(',',@$Xlabels),
                   14136:          $id.'.PlotType' => 'XY',
                   14137:          $id.'.NumSets' => 2,
1.137     matthew  14138:          $id.'.two_axes' => 1,
                   14139:          $id.'.y1_max_value' => $Max1,
                   14140:          $id.'.y1_min_value' => $Min1,
                   14141:          $id.'.y2_max_value' => $Max2,
                   14142:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14143:          );
                   14144:     #
1.137     matthew  14145:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14146:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14147:     }
                   14148:     #
                   14149:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14150:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14151:         return '';
                   14152:     }
                   14153:     my $NumSets=1;
1.137     matthew  14154:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14155:         next if (! ref($array));
                   14156:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14157:     }
                   14158:     #
                   14159:     # Deal with other parameters
                   14160:     while (my ($key,$value) = each(%Values)) {
                   14161:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14162:     }
                   14163:     #
1.646     raeburn  14164:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14165:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14166: }
                   14167: 
                   14168: ############################################################
                   14169: ############################################################
                   14170: 
                   14171: =pod
                   14172: 
1.157     matthew  14173: =back 
                   14174: 
1.139     matthew  14175: =head1 Statistics helper routines?  
                   14176: 
                   14177: Bad place for them but what the hell.
                   14178: 
1.157     matthew  14179: =over 4
                   14180: 
1.648     raeburn  14181: =item * &chartlink()
1.139     matthew  14182: 
                   14183: Returns a link to the chart for a specific student.  
                   14184: 
                   14185: Inputs:
                   14186: 
                   14187: =over 4
                   14188: 
                   14189: =item $linktext: The text of the link
                   14190: 
                   14191: =item $sname: The students username
                   14192: 
                   14193: =item $sdomain: The students domain
                   14194: 
                   14195: =back
                   14196: 
1.157     matthew  14197: =back
                   14198: 
1.139     matthew  14199: =cut
                   14200: 
                   14201: ############################################################
                   14202: ############################################################
                   14203: sub chartlink {
                   14204:     my ($linktext, $sname, $sdomain) = @_;
                   14205:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14206:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14207:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14208:        '">'.$linktext.'</a>';
1.153     matthew  14209: }
                   14210: 
                   14211: #######################################################
                   14212: #######################################################
                   14213: 
                   14214: =pod
                   14215: 
                   14216: =head1 Course Environment Routines
1.157     matthew  14217: 
                   14218: =over 4
1.153     matthew  14219: 
1.648     raeburn  14220: =item * &restore_course_settings()
1.153     matthew  14221: 
1.648     raeburn  14222: =item * &store_course_settings()
1.153     matthew  14223: 
                   14224: Restores/Store indicated form parameters from the course environment.
                   14225: Will not overwrite existing values of the form parameters.
                   14226: 
                   14227: Inputs: 
                   14228: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14229: 
                   14230: a hash ref describing the data to be stored.  For example:
                   14231:    
                   14232: %Save_Parameters = ('Status' => 'scalar',
                   14233:     'chartoutputmode' => 'scalar',
                   14234:     'chartoutputdata' => 'scalar',
                   14235:     'Section' => 'array',
1.373     raeburn  14236:     'Group' => 'array',
1.153     matthew  14237:     'StudentData' => 'array',
                   14238:     'Maps' => 'array');
                   14239: 
                   14240: Returns: both routines return nothing
                   14241: 
1.631     raeburn  14242: =back
                   14243: 
1.153     matthew  14244: =cut
                   14245: 
                   14246: #######################################################
                   14247: #######################################################
                   14248: sub store_course_settings {
1.496     albertel 14249:     return &store_settings($env{'request.course.id'},@_);
                   14250: }
                   14251: 
                   14252: sub store_settings {
1.153     matthew  14253:     # save to the environment
                   14254:     # appenv the same items, just to be safe
1.300     albertel 14255:     my $udom  = $env{'user.domain'};
                   14256:     my $uname = $env{'user.name'};
1.496     albertel 14257:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14258:     my %SaveHash;
                   14259:     my %AppHash;
                   14260:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14261:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14262:         my $envname = 'environment.'.$basename;
1.258     albertel 14263:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14264:             # Save this value away
                   14265:             if ($type eq 'scalar' &&
1.258     albertel 14266:                 (! exists($env{$envname}) || 
                   14267:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14268:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14269:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14270:             } elsif ($type eq 'array') {
                   14271:                 my $stored_form;
1.258     albertel 14272:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14273:                     $stored_form = join(',',
                   14274:                                         map {
1.369     www      14275:                                             &escape($_);
1.258     albertel 14276:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14277:                 } else {
                   14278:                     $stored_form = 
1.369     www      14279:                         &escape($env{'form.'.$setting});
1.153     matthew  14280:                 }
                   14281:                 # Determine if the array contents are the same.
1.258     albertel 14282:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14283:                     $SaveHash{$basename} = $stored_form;
                   14284:                     $AppHash{$envname}   = $stored_form;
                   14285:                 }
                   14286:             }
                   14287:         }
                   14288:     }
                   14289:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14290:                                           $udom,$uname);
1.153     matthew  14291:     if ($put_result !~ /^(ok|delayed)/) {
                   14292:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14293:                                  'got error:'.$put_result);
                   14294:     }
                   14295:     # Make sure these settings stick around in this session, too
1.646     raeburn  14296:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14297:     return;
                   14298: }
                   14299: 
                   14300: sub restore_course_settings {
1.499     albertel 14301:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14302: }
                   14303: 
                   14304: sub restore_settings {
                   14305:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14306:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14307:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14308:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14309:             '.'.$setting;
1.258     albertel 14310:         if (exists($env{$envname})) {
1.153     matthew  14311:             if ($type eq 'scalar') {
1.258     albertel 14312:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14313:             } elsif ($type eq 'array') {
1.258     albertel 14314:                 $env{'form.'.$setting} = [ 
1.153     matthew  14315:                                            map { 
1.369     www      14316:                                                &unescape($_); 
1.258     albertel 14317:                                            } split(',',$env{$envname})
1.153     matthew  14318:                                            ];
                   14319:             }
                   14320:         }
                   14321:     }
1.127     matthew  14322: }
                   14323: 
1.618     raeburn  14324: #######################################################
                   14325: #######################################################
                   14326: 
                   14327: =pod
                   14328: 
                   14329: =head1 Domain E-mail Routines  
                   14330: 
                   14331: =over 4
                   14332: 
1.648     raeburn  14333: =item * &build_recipient_list()
1.618     raeburn  14334: 
1.1075.2.44  raeburn  14335: Build recipient lists for following types of e-mail:
1.766     raeburn  14336: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14337: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14338: module change checking, student/employee ID conflict checks, as
                   14339: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14340: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14341: 
                   14342: Inputs:
1.1075.2.44  raeburn  14343: defmail (scalar - email address of default recipient),
                   14344: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14345: requestsmail, updatesmail, or idconflictsmail).
                   14346: 
1.619     raeburn  14347: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14348: 
                   14349: origmail (scalar - email address of recipient from loncapa.conf,
                   14350: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14351: 
1.1075.2.139  raeburn  14352: $requname username of requester (if mailing type is helpdeskmail)
                   14353: 
                   14354: $requdom domain of requester (if mailing type is helpdeskmail)
                   14355: 
                   14356: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14357: 
1.655     raeburn  14358: Returns: comma separated list of addresses to which to send e-mail.
                   14359: 
                   14360: =back
1.618     raeburn  14361: 
                   14362: =cut
                   14363: 
                   14364: ############################################################
                   14365: ############################################################
                   14366: sub build_recipient_list {
1.1075.2.139  raeburn  14367:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14368:     my @recipients;
1.1075.2.122  raeburn  14369:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14370:     my %domconfig =
1.1075.2.122  raeburn  14371:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14372:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14373:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14374:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14375:                 my @contacts = ('adminemail','supportemail');
                   14376:                 foreach my $item (@contacts) {
                   14377:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14378:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14379:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14380:                             push(@recipients,$addr);
                   14381:                         }
1.619     raeburn  14382:                     }
1.1075.2.122  raeburn  14383:                 }
                   14384:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14385:                 if ($mailing eq 'helpdeskmail') {
                   14386:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14387:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14388:                         my @ok_bccs;
                   14389:                         foreach my $bcc (@bccs) {
                   14390:                             $bcc =~ s/^\s+//g;
                   14391:                             $bcc =~ s/\s+$//g;
                   14392:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14393:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14394:                                     push(@ok_bccs,$bcc);
                   14395:                                 }
                   14396:                             }
                   14397:                         }
                   14398:                         if (@ok_bccs > 0) {
                   14399:                             $allbcc = join(', ',@ok_bccs);
                   14400:                         }
                   14401:                     }
                   14402:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14403:                 }
                   14404:             }
1.766     raeburn  14405:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14406:             $lastresort = $origmail;
1.618     raeburn  14407:         }
1.1075.2.139  raeburn  14408:         if ($mailing eq 'helpdeskmail') {
                   14409:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14410:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14411:                 my ($inststatus,$inststatus_checked);
                   14412:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14413:                     ($env{'user.domain'} ne 'public')) {
                   14414:                     $inststatus_checked = 1;
                   14415:                     $inststatus = $env{'environment.inststatus'};
                   14416:                 }
                   14417:                 unless ($inststatus_checked) {
                   14418:                     if (($requname ne '') && ($requdom ne '')) {
                   14419:                         if (($requname =~ /^$match_username$/) &&
                   14420:                             ($requdom =~ /^$match_domain$/) &&
                   14421:                             (&Apache::lonnet::domain($requdom))) {
                   14422:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14423:                                                                       $requdom);
                   14424:                             unless ($requhome eq 'no_host') {
                   14425:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14426:                                 $inststatus = $userenv{'inststatus'};
                   14427:                                 $inststatus_checked = 1;
                   14428:                             }
                   14429:                         }
                   14430:                     }
                   14431:                 }
                   14432:                 unless ($inststatus_checked) {
                   14433:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14434:                         my %srch = (srchby     => 'email',
                   14435:                                     srchdomain => $defdom,
                   14436:                                     srchterm   => $reqemail,
                   14437:                                     srchtype   => 'exact');
                   14438:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14439:                         foreach my $uname (keys(%srch_results)) {
                   14440:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14441:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14442:                                 $inststatus_checked = 1;
                   14443:                                 last;
                   14444:                             }
                   14445:                         }
                   14446:                         unless ($inststatus_checked) {
                   14447:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14448:                             if ($dirsrchres eq 'ok') {
                   14449:                                 foreach my $uname (keys(%srch_results)) {
                   14450:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14451:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14452:                                         $inststatus_checked = 1;
                   14453:                                         last;
                   14454:                                     }
                   14455:                                 }
                   14456:                             }
                   14457:                         }
                   14458:                     }
                   14459:                 }
                   14460:                 if ($inststatus ne '') {
                   14461:                     foreach my $status (split(/\:/,$inststatus)) {
                   14462:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14463:                             my @contacts = ('adminemail','supportemail');
                   14464:                             foreach my $item (@contacts) {
                   14465:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14466:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14467:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14468:                                         push(@recipients,$addr);
                   14469:                                     }
                   14470:                                 }
                   14471:                             }
                   14472:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14473:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14474:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14475:                                 my @ok_bccs;
                   14476:                                 foreach my $bcc (@bccs) {
                   14477:                                     $bcc =~ s/^\s+//g;
                   14478:                                     $bcc =~ s/\s+$//g;
                   14479:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14480:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14481:                                             push(@ok_bccs,$bcc);
                   14482:                                         }
                   14483:                                     }
                   14484:                                 }
                   14485:                                 if (@ok_bccs > 0) {
                   14486:                                     $allbcc = join(', ',@ok_bccs);
                   14487:                                 }
                   14488:                             }
                   14489:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14490:                             last;
                   14491:                         }
                   14492:                     }
                   14493:                 }
                   14494:             }
                   14495:         }
1.619     raeburn  14496:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14497:         $lastresort = $origmail;
                   14498:     }
1.1075.2.128  raeburn  14499:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14500:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14501:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14502:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14503:             my %what = (
                   14504:                           perlvar => 1,
                   14505:                        );
                   14506:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14507:             if ($primary) {
                   14508:                 my $gotaddr;
                   14509:                 my ($result,$returnhash) =
                   14510:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14511:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14512:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14513:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14514:                         $gotaddr = 1;
                   14515:                     }
                   14516:                 }
                   14517:                 unless ($gotaddr) {
                   14518:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14519:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14520:                     unless ($uintdom eq $intdom) {
                   14521:                         my %domconfig =
                   14522:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14523:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14524:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14525:                                 my @contacts = ('adminemail','supportemail');
                   14526:                                 foreach my $item (@contacts) {
                   14527:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14528:                                         my $addr = $domconfig{'contacts'}{$item};
                   14529:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14530:                                             push(@recipients,$addr);
                   14531:                                         }
                   14532:                                     }
                   14533:                                 }
                   14534:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14535:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14536:                                 }
                   14537:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14538:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14539:                                     my @ok_bccs;
                   14540:                                     foreach my $bcc (@bccs) {
                   14541:                                         $bcc =~ s/^\s+//g;
                   14542:                                         $bcc =~ s/\s+$//g;
                   14543:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14544:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14545:                                                 push(@ok_bccs,$bcc);
                   14546:                                             }
                   14547:                                         }
                   14548:                                     }
                   14549:                                     if (@ok_bccs > 0) {
                   14550:                                         $allbcc = join(', ',@ok_bccs);
                   14551:                                     }
                   14552:                                 }
                   14553:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14554:                             }
                   14555:                         }
                   14556:                     }
                   14557:                 }
                   14558:             }
                   14559:         }
1.618     raeburn  14560:     }
1.688     raeburn  14561:     if (defined($defmail)) {
                   14562:         if ($defmail ne '') {
                   14563:             push(@recipients,$defmail);
                   14564:         }
1.618     raeburn  14565:     }
                   14566:     if ($otheremails) {
1.619     raeburn  14567:         my @others;
                   14568:         if ($otheremails =~ /,/) {
                   14569:             @others = split(/,/,$otheremails);
1.618     raeburn  14570:         } else {
1.619     raeburn  14571:             push(@others,$otheremails);
                   14572:         }
                   14573:         foreach my $addr (@others) {
                   14574:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14575:                 push(@recipients,$addr);
                   14576:             }
1.618     raeburn  14577:         }
                   14578:     }
1.1075.2.128  raeburn  14579:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14580:         if ((!@recipients) && ($lastresort ne '')) {
                   14581:             push(@recipients,$lastresort);
                   14582:         }
                   14583:     } elsif ($lastresort ne '') {
                   14584:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14585:             push(@recipients,$lastresort);
                   14586:         }
                   14587:     }
                   14588:     my $recipientlist = join(',',@recipients);
                   14589:     if (wantarray) {
                   14590:         return ($recipientlist,$allbcc,$addtext);
                   14591:     } else {
                   14592:         return $recipientlist;
                   14593:     }
1.618     raeburn  14594: }
                   14595: 
1.127     matthew  14596: ############################################################
                   14597: ############################################################
1.154     albertel 14598: 
1.655     raeburn  14599: =pod
                   14600: 
                   14601: =head1 Course Catalog Routines
                   14602: 
                   14603: =over 4
                   14604: 
                   14605: =item * &gather_categories()
                   14606: 
                   14607: Converts category definitions - keys of categories hash stored in  
                   14608: coursecategories in configuration.db on the primary library server in a 
                   14609: domain - to an array.  Also generates javascript and idx hash used to 
                   14610: generate Domain Coordinator interface for editing Course Categories.
                   14611: 
                   14612: Inputs:
1.663     raeburn  14613: 
1.655     raeburn  14614: categories (reference to hash of category definitions).
1.663     raeburn  14615: 
1.655     raeburn  14616: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14617:       categories and subcategories).
1.663     raeburn  14618: 
1.655     raeburn  14619: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14620:       editing Course Categories).
1.663     raeburn  14621: 
1.655     raeburn  14622: jsarray (reference to array of categories used to create Javascript arrays for
                   14623:          Domain Coordinator interface for editing Course Categories).
                   14624: 
                   14625: Returns: nothing
                   14626: 
                   14627: Side effects: populates cats, idx and jsarray. 
                   14628: 
                   14629: =cut
                   14630: 
                   14631: sub gather_categories {
                   14632:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14633:     my %counters;
                   14634:     my $num = 0;
                   14635:     foreach my $item (keys(%{$categories})) {
                   14636:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14637:         if ($container eq '' && $depth == 0) {
                   14638:             $cats->[$depth][$categories->{$item}] = $cat;
                   14639:         } else {
                   14640:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14641:         }
                   14642:         my ($escitem,$tail) = split(/:/,$item,2);
                   14643:         if ($counters{$tail} eq '') {
                   14644:             $counters{$tail} = $num;
                   14645:             $num ++;
                   14646:         }
                   14647:         if (ref($idx) eq 'HASH') {
                   14648:             $idx->{$item} = $counters{$tail};
                   14649:         }
                   14650:         if (ref($jsarray) eq 'ARRAY') {
                   14651:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14652:         }
                   14653:     }
                   14654:     return;
                   14655: }
                   14656: 
                   14657: =pod
                   14658: 
                   14659: =item * &extract_categories()
                   14660: 
                   14661: Used to generate breadcrumb trails for course categories.
                   14662: 
                   14663: Inputs:
1.663     raeburn  14664: 
1.655     raeburn  14665: categories (reference to hash of category definitions).
1.663     raeburn  14666: 
1.655     raeburn  14667: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14668:       categories and subcategories).
1.663     raeburn  14669: 
1.655     raeburn  14670: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14671: 
1.655     raeburn  14672: allitems (reference to hash - key is category key 
                   14673:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14674: 
1.655     raeburn  14675: idx (reference to hash of counters used in Domain Coordinator interface for
                   14676:       editing Course Categories).
1.663     raeburn  14677: 
1.655     raeburn  14678: jsarray (reference to array of categories used to create Javascript arrays for
                   14679:          Domain Coordinator interface for editing Course Categories).
                   14680: 
1.665     raeburn  14681: subcats (reference to hash of arrays containing all subcategories within each 
                   14682:          category, -recursive)
                   14683: 
1.1075.2.132  raeburn  14684: maxd (reference to hash used to hold max depth for all top-level categories).
                   14685: 
1.655     raeburn  14686: Returns: nothing
                   14687: 
                   14688: Side effects: populates trails and allitems hash references.
                   14689: 
                   14690: =cut
                   14691: 
                   14692: sub extract_categories {
1.1075.2.132  raeburn  14693:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14694:     if (ref($categories) eq 'HASH') {
                   14695:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14696:         if (ref($cats->[0]) eq 'ARRAY') {
                   14697:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14698:                 my $name = $cats->[0][$i];
                   14699:                 my $item = &escape($name).'::0';
                   14700:                 my $trailstr;
                   14701:                 if ($name eq 'instcode') {
                   14702:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14703:                 } elsif ($name eq 'communities') {
                   14704:                     $trailstr = &mt('Communities');
1.655     raeburn  14705:                 } else {
                   14706:                     $trailstr = $name;
                   14707:                 }
                   14708:                 if ($allitems->{$item} eq '') {
                   14709:                     push(@{$trails},$trailstr);
                   14710:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14711:                 }
                   14712:                 my @parents = ($name);
                   14713:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14714:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14715:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14716:                         if (ref($subcats) eq 'HASH') {
                   14717:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14718:                         }
1.1075.2.132  raeburn  14719:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14720:                     }
                   14721:                 } else {
                   14722:                     if (ref($subcats) eq 'HASH') {
                   14723:                         $subcats->{$item} = [];
1.655     raeburn  14724:                     }
1.1075.2.132  raeburn  14725:                     if (ref($maxd) eq 'HASH') {
                   14726:                         $maxd->{$name} = 1;
                   14727:                     }
1.655     raeburn  14728:                 }
                   14729:             }
                   14730:         }
                   14731:     }
                   14732:     return;
                   14733: }
                   14734: 
                   14735: =pod
                   14736: 
1.1075.2.56  raeburn  14737: =item * &recurse_categories()
1.655     raeburn  14738: 
                   14739: Recursively used to generate breadcrumb trails for course categories.
                   14740: 
                   14741: Inputs:
1.663     raeburn  14742: 
1.655     raeburn  14743: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14744:       categories and subcategories).
1.663     raeburn  14745: 
1.655     raeburn  14746: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14747: 
                   14748: category (current course category, for which breadcrumb trail is being generated).
                   14749: 
                   14750: trails (reference to array of breadcrumb trails for each category).
                   14751: 
1.655     raeburn  14752: allitems (reference to hash - key is category key
                   14753:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14754: 
1.655     raeburn  14755: parents (array containing containers directories for current category, 
                   14756:          back to top level). 
                   14757: 
                   14758: Returns: nothing
                   14759: 
                   14760: Side effects: populates trails and allitems hash references
                   14761: 
                   14762: =cut
                   14763: 
                   14764: sub recurse_categories {
1.1075.2.132  raeburn  14765:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14766:     my $shallower = $depth - 1;
                   14767:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14768:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14769:             my $name = $cats->[$depth]{$category}[$k];
                   14770:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14771:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14772:             if ($allitems->{$item} eq '') {
                   14773:                 push(@{$trails},$trailstr);
                   14774:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14775:             }
                   14776:             my $deeper = $depth+1;
                   14777:             push(@{$parents},$category);
1.665     raeburn  14778:             if (ref($subcats) eq 'HASH') {
                   14779:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14780:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14781:                     my $higher;
                   14782:                     if ($j > 0) {
                   14783:                         $higher = &escape($parents->[$j]).':'.
                   14784:                                   &escape($parents->[$j-1]).':'.$j;
                   14785:                     } else {
                   14786:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14787:                     }
                   14788:                     push(@{$subcats->{$higher}},$subcat);
                   14789:                 }
                   14790:             }
                   14791:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14792:                                 $subcats,$maxd);
1.655     raeburn  14793:             pop(@{$parents});
                   14794:         }
                   14795:     } else {
                   14796:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14797:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14798:         if ($allitems->{$item} eq '') {
                   14799:             push(@{$trails},$trailstr);
                   14800:             $allitems->{$item} = scalar(@{$trails})-1;
                   14801:         }
1.1075.2.132  raeburn  14802:         if (ref($maxd) eq 'HASH') {
                   14803:             if ($depth > $maxd->{$parents->[0]}) {
                   14804:                 $maxd->{$parents->[0]} = $depth;
                   14805:             }
                   14806:         }
1.655     raeburn  14807:     }
                   14808:     return;
                   14809: }
                   14810: 
1.663     raeburn  14811: =pod
                   14812: 
1.1075.2.56  raeburn  14813: =item * &assign_categories_table()
1.663     raeburn  14814: 
                   14815: Create a datatable for display of hierarchical categories in a domain,
                   14816: with checkboxes to allow a course to be categorized. 
                   14817: 
                   14818: Inputs:
                   14819: 
                   14820: cathash - reference to hash of categories defined for the domain (from
                   14821:           configuration.db)
                   14822: 
                   14823: currcat - scalar with an & separated list of categories assigned to a course. 
                   14824: 
1.919     raeburn  14825: type    - scalar contains course type (Course or Community).
                   14826: 
1.1075.2.117  raeburn  14827: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14828:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14829: 
1.663     raeburn  14830: Returns: $output (markup to be displayed) 
                   14831: 
                   14832: =cut
                   14833: 
                   14834: sub assign_categories_table {
1.1075.2.117  raeburn  14835:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14836:     my $output;
                   14837:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14838:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14839:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14840:         $maxdepth = scalar(@cats);
                   14841:         if (@cats > 0) {
                   14842:             my $itemcount = 0;
                   14843:             if (ref($cats[0]) eq 'ARRAY') {
                   14844:                 my @currcategories;
                   14845:                 if ($currcat ne '') {
                   14846:                     @currcategories = split('&',$currcat);
                   14847:                 }
1.919     raeburn  14848:                 my $table;
1.663     raeburn  14849:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14850:                     my $parent = $cats[0][$i];
1.919     raeburn  14851:                     next if ($parent eq 'instcode');
                   14852:                     if ($type eq 'Community') {
                   14853:                         next unless ($parent eq 'communities');
                   14854:                     } else {
                   14855:                         next if ($parent eq 'communities');
                   14856:                     }
1.663     raeburn  14857:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14858:                     my $item = &escape($parent).'::0';
                   14859:                     my $checked = '';
                   14860:                     if (@currcategories > 0) {
                   14861:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14862:                             $checked = ' checked="checked"';
1.663     raeburn  14863:                         }
                   14864:                     }
1.919     raeburn  14865:                     my $parent_title = $parent;
                   14866:                     if ($parent eq 'communities') {
                   14867:                         $parent_title = &mt('Communities');
                   14868:                     }
                   14869:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14870:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14871:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14872:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14873:                     my $depth = 1;
                   14874:                     push(@path,$parent);
1.1075.2.117  raeburn  14875:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14876:                     pop(@path);
1.919     raeburn  14877:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14878:                     $itemcount ++;
                   14879:                 }
1.919     raeburn  14880:                 if ($itemcount) {
                   14881:                     $output = &Apache::loncommon::start_data_table().
                   14882:                               $table.
                   14883:                               &Apache::loncommon::end_data_table();
                   14884:                 }
1.663     raeburn  14885:             }
                   14886:         }
                   14887:     }
                   14888:     return $output;
                   14889: }
                   14890: 
                   14891: =pod
                   14892: 
1.1075.2.56  raeburn  14893: =item * &assign_category_rows()
1.663     raeburn  14894: 
                   14895: Create a datatable row for display of nested categories in a domain,
                   14896: with checkboxes to allow a course to be categorized,called recursively.
                   14897: 
                   14898: Inputs:
                   14899: 
                   14900: itemcount - track row number for alternating colors
                   14901: 
                   14902: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14903:       categories and subcategories.
                   14904: 
                   14905: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14906: 
                   14907: parent - parent of current category item
                   14908: 
                   14909: path - Array containing all categories back up through the hierarchy from the
                   14910:        current category to the top level.
                   14911: 
                   14912: currcategories - reference to array of current categories assigned to the course
                   14913: 
1.1075.2.117  raeburn  14914: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14915:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14916: 
1.663     raeburn  14917: Returns: $output (markup to be displayed).
                   14918: 
                   14919: =cut
                   14920: 
                   14921: sub assign_category_rows {
1.1075.2.117  raeburn  14922:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14923:     my ($text,$name,$item,$chgstr);
                   14924:     if (ref($cats) eq 'ARRAY') {
                   14925:         my $maxdepth = scalar(@{$cats});
                   14926:         if (ref($cats->[$depth]) eq 'HASH') {
                   14927:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14928:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14929:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14930:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14931:                 for (my $j=0; $j<$numchildren; $j++) {
                   14932:                     $name = $cats->[$depth]{$parent}[$j];
                   14933:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14934:                     my $deeper = $depth+1;
                   14935:                     my $checked = '';
                   14936:                     if (ref($currcategories) eq 'ARRAY') {
                   14937:                         if (@{$currcategories} > 0) {
                   14938:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14939:                                 $checked = ' checked="checked"';
1.663     raeburn  14940:                             }
                   14941:                         }
                   14942:                     }
1.664     raeburn  14943:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14944:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14945:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14946:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14947:                              '</td><td>';
1.663     raeburn  14948:                     if (ref($path) eq 'ARRAY') {
                   14949:                         push(@{$path},$name);
1.1075.2.117  raeburn  14950:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14951:                         pop(@{$path});
                   14952:                     }
                   14953:                     $text .= '</td></tr>';
                   14954:                 }
                   14955:                 $text .= '</table></td>';
                   14956:             }
                   14957:         }
                   14958:     }
                   14959:     return $text;
                   14960: }
                   14961: 
1.1075.2.69  raeburn  14962: =pod
                   14963: 
                   14964: =back
                   14965: 
                   14966: =cut
                   14967: 
1.655     raeburn  14968: ############################################################
                   14969: ############################################################
                   14970: 
                   14971: 
1.443     albertel 14972: sub commit_customrole {
1.664     raeburn  14973:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14974:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14975:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14976:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14977:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14978:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14979:                  '</b><br />';
                   14980:     return $output;
                   14981: }
                   14982: 
                   14983: sub commit_standardrole {
1.1075.2.31  raeburn  14984:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14985:     my ($output,$logmsg,$linefeed);
                   14986:     if ($context eq 'auto') {
                   14987:         $linefeed = "\n";
                   14988:     } else {
                   14989:         $linefeed = "<br />\n";
                   14990:     }  
1.443     albertel 14991:     if ($three eq 'st') {
1.541     raeburn  14992:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14993:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14994:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14995:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14996:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14997:         } else {
1.541     raeburn  14998:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14999:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15000:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15001:             if ($context eq 'auto') {
                   15002:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15003:             } else {
                   15004:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15005:                &mt('Add to classlist').': <b>ok</b>';
                   15006:             }
                   15007:             $output .= $linefeed;
1.443     albertel 15008:         }
                   15009:     } else {
                   15010:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15011:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15012:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15013:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15014:         if ($context eq 'auto') {
                   15015:             $output .= $result.$linefeed;
                   15016:         } else {
                   15017:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15018:         }
1.443     albertel 15019:     }
                   15020:     return $output;
                   15021: }
                   15022: 
                   15023: sub commit_studentrole {
1.1075.2.31  raeburn  15024:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15025:         $credits) = @_;
1.626     raeburn  15026:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15027:     if ($context eq 'auto') {
                   15028:         $linefeed = "\n";
                   15029:     } else {
                   15030:         $linefeed = '<br />'."\n";
                   15031:     }
1.443     albertel 15032:     if (defined($one) && defined($two)) {
                   15033:         my $cid=$one.'_'.$two;
                   15034:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15035:         my $secchange = 0;
                   15036:         my $expire_role_result;
                   15037:         my $modify_section_result;
1.628     raeburn  15038:         if ($oldsec ne '-1') { 
                   15039:             if ($oldsec ne $sec) {
1.443     albertel 15040:                 $secchange = 1;
1.628     raeburn  15041:                 my $now = time;
1.443     albertel 15042:                 my $uurl='/'.$cid;
                   15043:                 $uurl=~s/\_/\//g;
                   15044:                 if ($oldsec) {
                   15045:                     $uurl.='/'.$oldsec;
                   15046:                 }
1.626     raeburn  15047:                 $oldsecurl = $uurl;
1.628     raeburn  15048:                 $expire_role_result = 
1.652     raeburn  15049:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15050:                 if ($env{'request.course.sec'} ne '') { 
                   15051:                     if ($expire_role_result eq 'refused') {
                   15052:                         my @roles = ('st');
                   15053:                         my @statuses = ('previous');
                   15054:                         my @roledoms = ($one);
                   15055:                         my $withsec = 1;
                   15056:                         my %roleshash = 
                   15057:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15058:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15059:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15060:                             my ($oldstart,$oldend) = 
                   15061:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15062:                             if ($oldend > 0 && $oldend <= $now) {
                   15063:                                 $expire_role_result = 'ok';
                   15064:                             }
                   15065:                         }
                   15066:                     }
                   15067:                 }
1.443     albertel 15068:                 $result = $expire_role_result;
                   15069:             }
                   15070:         }
                   15071:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15072:             $modify_section_result = 
                   15073:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15074:                                                            undef,undef,undef,$sec,
                   15075:                                                            $end,$start,'','',$cid,
                   15076:                                                            '',$context,$credits);
1.443     albertel 15077:             if ($modify_section_result =~ /^ok/) {
                   15078:                 if ($secchange == 1) {
1.628     raeburn  15079:                     if ($sec eq '') {
                   15080:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15081:                     } else {
                   15082:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15083:                     }
1.443     albertel 15084:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15085:                     if ($sec eq '') {
                   15086:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15087:                     } else {
                   15088:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15089:                     }
1.443     albertel 15090:                 } else {
1.628     raeburn  15091:                     if ($sec eq '') {
                   15092:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15093:                     } else {
                   15094:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15095:                     }
1.443     albertel 15096:                 }
                   15097:             } else {
1.628     raeburn  15098:                 if ($secchange) {       
                   15099:                     $$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;
                   15100:                 } else {
                   15101:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15102:                 }
1.443     albertel 15103:             }
                   15104:             $result = $modify_section_result;
                   15105:         } elsif ($secchange == 1) {
1.628     raeburn  15106:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15107:                 $$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  15108:             } else {
                   15109:                 $$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;
                   15110:             }
1.626     raeburn  15111:             if ($expire_role_result eq 'refused') {
                   15112:                 my $newsecurl = '/'.$cid;
                   15113:                 $newsecurl =~ s/\_/\//g;
                   15114:                 if ($sec ne '') {
                   15115:                     $newsecurl.='/'.$sec;
                   15116:                 }
                   15117:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15118:                     if ($sec eq '') {
                   15119:                         $$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;
                   15120:                     } else {
                   15121:                         $$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;
                   15122:                     }
                   15123:                 }
                   15124:             }
1.443     albertel 15125:         }
                   15126:     } else {
1.626     raeburn  15127:         $$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 15128:         $result = "error: incomplete course id\n";
                   15129:     }
                   15130:     return $result;
                   15131: }
                   15132: 
1.1075.2.25  raeburn  15133: sub show_role_extent {
                   15134:     my ($scope,$context,$role) = @_;
                   15135:     $scope =~ s{^/}{};
                   15136:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15137:     push(@courseroles,'co');
                   15138:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15139:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15140:         $scope =~ s{/}{_};
                   15141:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15142:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15143:         my ($audom,$auname) = split(/\//,$scope);
                   15144:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15145:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15146:     } else {
                   15147:         $scope =~ s{/$}{};
                   15148:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15149:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15150:     }
                   15151: }
                   15152: 
1.443     albertel 15153: ############################################################
                   15154: ############################################################
                   15155: 
1.566     albertel 15156: sub check_clone {
1.578     raeburn  15157:     my ($args,$linefeed) = @_;
1.566     albertel 15158:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15159:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15160:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15161:     my $clonemsg;
                   15162:     my $can_clone = 0;
1.944     raeburn  15163:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15164:     if ($lctype ne 'community') {
                   15165:         $lctype = 'course';
                   15166:     }
1.566     albertel 15167:     if ($clonehome eq 'no_host') {
1.944     raeburn  15168:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15169:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15170:         } else {
                   15171:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15172:         }     
1.566     albertel 15173:     } else {
                   15174: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15175:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15176:             if ($clonedesc{'type'} ne 'Community') {
                   15177:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15178:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15179:             }
                   15180:         }
1.1075.2.119  raeburn  15181: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15182:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15183: 	    $can_clone = 1;
                   15184: 	} else {
1.1075.2.95  raeburn  15185: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15186: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15187:             if ($clonehash{'cloners'} eq '') {
                   15188:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15189:                 if ($domdefs{'canclone'}) {
                   15190:                     unless ($domdefs{'canclone'} eq 'none') {
                   15191:                         if ($domdefs{'canclone'} eq 'domain') {
                   15192:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15193:                                 $can_clone = 1;
                   15194:                             }
                   15195:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15196:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15197:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15198:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15199:                                 $can_clone = 1;
                   15200:                             }
                   15201:                         }
                   15202:                     }
1.908     raeburn  15203:                 }
1.1075.2.95  raeburn  15204:             } else {
                   15205: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15206:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15207:                     $can_clone = 1;
1.1075.2.95  raeburn  15208:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15209:                     $can_clone = 1;
1.1075.2.96  raeburn  15210:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15211:                     $can_clone = 1;
1.1075.2.95  raeburn  15212:                 }
                   15213:                 unless ($can_clone) {
1.1075.2.96  raeburn  15214:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15215:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15216:                         my (%gotdomdefaults,%gotcodedefaults);
                   15217:                         foreach my $cloner (@cloners) {
                   15218:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15219:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15220:                                 my (%codedefaults,@code_order);
                   15221:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15222:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15223:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15224:                                     }
                   15225:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15226:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15227:                                     }
                   15228:                                 } else {
                   15229:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15230:                                                                             \%codedefaults,
                   15231:                                                                             \@code_order);
                   15232:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15233:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15234:                                 }
                   15235:                                 if (@code_order > 0) {
                   15236:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15237:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15238:                                                                                 $args->{'crscode'})) {
                   15239:                                         $can_clone = 1;
                   15240:                                         last;
                   15241:                                     }
                   15242:                                 }
                   15243:                             }
                   15244:                         }
                   15245:                     }
1.1075.2.96  raeburn  15246:                 }
                   15247:             }
                   15248:             unless ($can_clone) {
                   15249:                 my $ccrole = 'cc';
                   15250:                 if ($args->{'crstype'} eq 'Community') {
                   15251:                     $ccrole = 'co';
                   15252:                 }
                   15253:                 my %roleshash =
                   15254:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15255:                                                   $args->{'ccdomain'},
                   15256:                                                   'userroles',['active'],[$ccrole],
                   15257:                                                   [$args->{'clonedomain'}]);
                   15258:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15259:                     $can_clone = 1;
                   15260:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15261:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15262:                     $can_clone = 1;
1.1075.2.95  raeburn  15263:                 }
                   15264:             }
                   15265:             unless ($can_clone) {
                   15266:                 if ($args->{'crstype'} eq 'Community') {
                   15267:                     $clonemsg = &mt('No new community created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   15268:                 } else {
                   15269:                     $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.578     raeburn  15270: 	        }
1.566     albertel 15271: 	    }
1.578     raeburn  15272:         }
1.566     albertel 15273:     }
                   15274:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15275: }
                   15276: 
1.444     albertel 15277: sub construct_course {
1.1075.2.119  raeburn  15278:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15279:         $cnum,$category,$coderef) = @_;
1.444     albertel 15280:     my $outcome;
1.541     raeburn  15281:     my $linefeed =  '<br />'."\n";
                   15282:     if ($context eq 'auto') {
                   15283:         $linefeed = "\n";
                   15284:     }
1.566     albertel 15285: 
                   15286: #
                   15287: # Are we cloning?
                   15288: #
                   15289:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15290:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15291: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15292: 	if ($context ne 'auto') {
1.578     raeburn  15293:             if ($clonemsg ne '') {
                   15294: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15295:             }
1.566     albertel 15296: 	}
                   15297: 	$outcome .= $clonemsg.$linefeed;
                   15298: 
                   15299:         if (!$can_clone) {
                   15300: 	    return (0,$outcome);
                   15301: 	}
                   15302:     }
                   15303: 
1.444     albertel 15304: #
                   15305: # Open course
                   15306: #
                   15307:     my $crstype = lc($args->{'crstype'});
                   15308:     my %cenv=();
                   15309:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15310:                                              $args->{'cdescr'},
                   15311:                                              $args->{'curl'},
                   15312:                                              $args->{'course_home'},
                   15313:                                              $args->{'nonstandard'},
                   15314:                                              $args->{'crscode'},
                   15315:                                              $args->{'ccuname'}.':'.
                   15316:                                              $args->{'ccdomain'},
1.882     raeburn  15317:                                              $args->{'crstype'},
1.885     raeburn  15318:                                              $cnum,$context,$category);
1.444     albertel 15319: 
                   15320:     # Note: The testing routines depend on this being output; see 
                   15321:     # Utils::Course. This needs to at least be output as a comment
                   15322:     # if anyone ever decides to not show this, and Utils::Course::new
                   15323:     # will need to be suitably modified.
1.541     raeburn  15324:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  15325:     if ($$courseid =~ /^error:/) {
                   15326:         return (0,$outcome);
                   15327:     }
                   15328: 
1.444     albertel 15329: #
                   15330: # Check if created correctly
                   15331: #
1.479     albertel 15332:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15333:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15334:     if ($crsuhome eq 'no_host') {
                   15335:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15336:         return (0,$outcome);
                   15337:     }
1.541     raeburn  15338:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15339: 
1.444     albertel 15340: #
1.566     albertel 15341: # Do the cloning
                   15342: #   
                   15343:     if ($can_clone && $cloneid) {
                   15344: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15345: 	if ($context ne 'auto') {
                   15346: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15347: 	}
                   15348: 	$outcome .= $clonemsg.$linefeed;
                   15349: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15350: # Copy all files
1.637     www      15351: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15352: # Restore URL
1.566     albertel 15353: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15354: # Restore title
1.566     albertel 15355: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15356: # Restore creation date, creator and creation context.
                   15357:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15358:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15359:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15360: # Mark as cloned
1.566     albertel 15361: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15362: # Need to clone grading mode
                   15363:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15364:         $cenv{'grading'}=$newenv{'grading'};
                   15365: # Do not clone these environment entries
                   15366:         &Apache::lonnet::del('environment',
                   15367:                   ['default_enrollment_start_date',
                   15368:                    'default_enrollment_end_date',
                   15369:                    'question.email',
                   15370:                    'policy.email',
                   15371:                    'comment.email',
                   15372:                    'pch.users.denied',
1.725     raeburn  15373:                    'plc.users.denied',
                   15374:                    'hidefromcat',
1.1075.2.36  raeburn  15375:                    'checkforpriv',
1.1075.2.59  raeburn  15376:                    'categories',
                   15377:                    'internal.uniquecode'],
1.638     www      15378:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15379:         if ($args->{'textbook'}) {
                   15380:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15381:         }
1.444     albertel 15382:     }
1.566     albertel 15383: 
1.444     albertel 15384: #
                   15385: # Set environment (will override cloned, if existing)
                   15386: #
                   15387:     my @sections = ();
                   15388:     my @xlists = ();
                   15389:     if ($args->{'crstype'}) {
                   15390:         $cenv{'type'}=$args->{'crstype'};
                   15391:     }
                   15392:     if ($args->{'crsid'}) {
                   15393:         $cenv{'courseid'}=$args->{'crsid'};
                   15394:     }
                   15395:     if ($args->{'crscode'}) {
                   15396:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15397:     }
                   15398:     if ($args->{'crsquota'} ne '') {
                   15399:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15400:     } else {
                   15401:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15402:     }
                   15403:     if ($args->{'ccuname'}) {
                   15404:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15405:                                         ':'.$args->{'ccdomain'};
                   15406:     } else {
                   15407:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15408:     }
1.1075.2.31  raeburn  15409:     if ($args->{'defaultcredits'}) {
                   15410:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15411:     }
1.444     albertel 15412:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15413:     if ($args->{'crssections'}) {
                   15414:         $cenv{'internal.sectionnums'} = '';
                   15415:         if ($args->{'crssections'} =~ m/,/) {
                   15416:             @sections = split/,/,$args->{'crssections'};
                   15417:         } else {
                   15418:             $sections[0] = $args->{'crssections'};
                   15419:         }
                   15420:         if (@sections > 0) {
                   15421:             foreach my $item (@sections) {
                   15422:                 my ($sec,$gp) = split/:/,$item;
                   15423:                 my $class = $args->{'crscode'}.$sec;
                   15424:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15425:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15426:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15427:                     push(@badclasses,$class);
1.444     albertel 15428:                 }
                   15429:             }
                   15430:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15431:         }
                   15432:     }
                   15433: # do not hide course coordinator from staff listing, 
                   15434: # even if privileged
                   15435:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15436: # add course coordinator's domain to domains to check for privileged users
                   15437: # if different to course domain
                   15438:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15439:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15440:     }
1.444     albertel 15441: # add crosslistings
                   15442:     if ($args->{'crsxlist'}) {
                   15443:         $cenv{'internal.crosslistings'}='';
                   15444:         if ($args->{'crsxlist'} =~ m/,/) {
                   15445:             @xlists = split/,/,$args->{'crsxlist'};
                   15446:         } else {
                   15447:             $xlists[0] = $args->{'crsxlist'};
                   15448:         }
                   15449:         if (@xlists > 0) {
                   15450:             foreach my $item (@xlists) {
                   15451:                 my ($xl,$gp) = split/:/,$item;
                   15452:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15453:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15454:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15455:                     push(@badclasses,$xl);
1.444     albertel 15456:                 }
                   15457:             }
                   15458:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15459:         }
                   15460:     }
                   15461:     if ($args->{'autoadds'}) {
                   15462:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15463:     }
                   15464:     if ($args->{'autodrops'}) {
                   15465:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15466:     }
                   15467: # check for notification of enrollment changes
                   15468:     my @notified = ();
                   15469:     if ($args->{'notify_owner'}) {
                   15470:         if ($args->{'ccuname'} ne '') {
                   15471:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15472:         }
                   15473:     }
                   15474:     if ($args->{'notify_dc'}) {
                   15475:         if ($uname ne '') { 
1.630     raeburn  15476:             push(@notified,$uname.':'.$udom);
1.444     albertel 15477:         }
                   15478:     }
                   15479:     if (@notified > 0) {
                   15480:         my $notifylist;
                   15481:         if (@notified > 1) {
                   15482:             $notifylist = join(',',@notified);
                   15483:         } else {
                   15484:             $notifylist = $notified[0];
                   15485:         }
                   15486:         $cenv{'internal.notifylist'} = $notifylist;
                   15487:     }
                   15488:     if (@badclasses > 0) {
                   15489:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15490:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15491:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15492:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15493:         );
1.1075.2.119  raeburn  15494:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15495:                            &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  15496:         if ($context eq 'auto') {
                   15497:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15498:         } else {
1.566     albertel 15499:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15500:         }
                   15501:         foreach my $item (@badclasses) {
1.541     raeburn  15502:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15503:                 $outcome .= " - $item\n";
1.541     raeburn  15504:             } else {
1.1075.2.119  raeburn  15505:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15506:             }
1.1075.2.119  raeburn  15507:         }
                   15508:         if ($context eq 'auto') {
                   15509:             $outcome .= $linefeed;
                   15510:         } else {
                   15511:             $outcome .= "</ul><br /><br /></div>\n";
                   15512:         }
1.444     albertel 15513:     }
                   15514:     if ($args->{'no_end_date'}) {
                   15515:         $args->{'endaccess'} = 0;
                   15516:     }
                   15517:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15518:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15519:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15520:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15521:     if ($args->{'showphotos'}) {
                   15522:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15523:     }
                   15524:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15525:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15526:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15527:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15528:             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'); 
                   15529:             if ($context eq 'auto') {
                   15530:                 $outcome .= $krb_msg;
                   15531:             } else {
1.566     albertel 15532:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15533:             }
                   15534:             $outcome .= $linefeed;
1.444     albertel 15535:         }
                   15536:     }
                   15537:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15538:        if ($args->{'setpolicy'}) {
                   15539:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15540:        }
                   15541:        if ($args->{'setcontent'}) {
                   15542:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15543:        }
1.1075.2.110  raeburn  15544:        if ($args->{'setcomment'}) {
                   15545:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15546:        }
1.444     albertel 15547:     }
                   15548:     if ($args->{'reshome'}) {
                   15549: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15550: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15551:     }
                   15552: #
                   15553: # course has keyed access
                   15554: #
                   15555:     if ($args->{'setkeys'}) {
                   15556:        $cenv{'keyaccess'}='yes';
                   15557:     }
                   15558: # if specified, key authority is not course, but user
                   15559: # only active if keyaccess is yes
                   15560:     if ($args->{'keyauth'}) {
1.487     albertel 15561: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15562: 	$user = &LONCAPA::clean_username($user);
                   15563: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15564: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15565: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15566: 	}
                   15567:     }
                   15568: 
1.1075.2.59  raeburn  15569: #
                   15570: #  generate and store uniquecode (available to course requester), if course should have one.
                   15571: #
                   15572:     if ($args->{'uniquecode'}) {
                   15573:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15574:         if ($code) {
                   15575:             $cenv{'internal.uniquecode'} = $code;
                   15576:             my %crsinfo =
                   15577:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15578:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15579:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15580:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15581:             }
                   15582:             if (ref($coderef)) {
                   15583:                 $$coderef = $code;
                   15584:             }
                   15585:         }
                   15586:     }
                   15587: 
1.444     albertel 15588:     if ($args->{'disresdis'}) {
                   15589:         $cenv{'pch.roles.denied'}='st';
                   15590:     }
                   15591:     if ($args->{'disablechat'}) {
                   15592:         $cenv{'plc.roles.denied'}='st';
                   15593:     }
                   15594: 
                   15595:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15596:     # course
                   15597:     $cenv{'course.helper.not.run'} = 1;
                   15598:     #
                   15599:     # Use new Randomseed
                   15600:     #
                   15601:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15602:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15603:     #
                   15604:     # The encryption code and receipt prefix for this course
                   15605:     #
                   15606:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15607:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15608:     #
                   15609:     # By default, use standard grading
                   15610:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15611: 
1.541     raeburn  15612:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15613:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15614: #
                   15615: # Open all assignments
                   15616: #
                   15617:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  15618:        my $opendate = time;
                   15619:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15620:            $opendate = $args->{'openallfrom'};
                   15621:        }
1.444     albertel 15622:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  15623:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15624:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  15625:        $outcome .= &mt('All assignments open starting [_1]',
                   15626:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15627:                    &Apache::lonnet::cput
                   15628:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15629:    }
                   15630: #
                   15631: # Set first page
                   15632: #
                   15633:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15634: 	    || ($cloneid)) {
1.445     albertel 15635: 	use LONCAPA::map;
1.444     albertel 15636: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15637: 
                   15638: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15639:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15640: 
1.444     albertel 15641:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15642:         my $title; my $url;
                   15643:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15644: 	    $title=&mt('Syllabus');
1.444     albertel 15645:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15646:         } else {
1.963     raeburn  15647:             $title=&mt('Table of Contents');
1.444     albertel 15648:             $url='/adm/navmaps';
                   15649:         }
1.445     albertel 15650: 
                   15651:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15652: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15653: 
                   15654: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15655:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15656:     }
1.566     albertel 15657: 
                   15658:     return (1,$outcome);
1.444     albertel 15659: }
                   15660: 
1.1075.2.59  raeburn  15661: sub make_unique_code {
                   15662:     my ($cdom,$cnum) = @_;
                   15663:     # get lock on uniquecodes db
                   15664:     my $lockhash = {
                   15665:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15666:                                                   ':'.$env{'user.domain'},
                   15667:                    };
                   15668:     my $tries = 0;
                   15669:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15670:     my ($code,$error);
                   15671: 
                   15672:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15673:         $tries ++;
                   15674:         sleep 1;
                   15675:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15676:     }
                   15677:     if ($gotlock eq 'ok') {
                   15678:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15679:         my $gotcode;
                   15680:         my $attempts = 0;
                   15681:         while ((!$gotcode) && ($attempts < 100)) {
                   15682:             $code = &generate_code();
                   15683:             if (!exists($currcodes{$code})) {
                   15684:                 $gotcode = 1;
                   15685:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15686:                     $error = 'nostore';
                   15687:                 }
                   15688:             }
                   15689:             $attempts ++;
                   15690:         }
                   15691:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15692:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15693:     } else {
                   15694:         $error = 'nolock';
                   15695:     }
                   15696:     return ($code,$error);
                   15697: }
                   15698: 
                   15699: sub generate_code {
                   15700:     my $code;
                   15701:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15702:     for (my $i=0; $i<6; $i++) {
                   15703:         my $lettnum = int (rand 2);
                   15704:         my $item = '';
                   15705:         if ($lettnum) {
                   15706:             $item = $letts[int( rand(18) )];
                   15707:         } else {
                   15708:             $item = 1+int( rand(8) );
                   15709:         }
                   15710:         $code .= $item;
                   15711:     }
                   15712:     return $code;
                   15713: }
                   15714: 
1.444     albertel 15715: ############################################################
                   15716: ############################################################
                   15717: 
1.953     droeschl 15718: #SD
                   15719: # only Community and Course, or anything else?
1.378     raeburn  15720: sub course_type {
                   15721:     my ($cid) = @_;
                   15722:     if (!defined($cid)) {
                   15723:         $cid = $env{'request.course.id'};
                   15724:     }
1.404     albertel 15725:     if (defined($env{'course.'.$cid.'.type'})) {
                   15726:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15727:     } else {
                   15728:         return 'Course';
1.377     raeburn  15729:     }
                   15730: }
1.156     albertel 15731: 
1.406     raeburn  15732: sub group_term {
                   15733:     my $crstype = &course_type();
                   15734:     my %names = (
                   15735:                   'Course' => 'group',
1.865     raeburn  15736:                   'Community' => 'group',
1.406     raeburn  15737:                 );
                   15738:     return $names{$crstype};
                   15739: }
                   15740: 
1.902     raeburn  15741: sub course_types {
1.1075.2.59  raeburn  15742:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15743:     my %typename = (
                   15744:                          official   => 'Official course',
                   15745:                          unofficial => 'Unofficial course',
                   15746:                          community  => 'Community',
1.1075.2.59  raeburn  15747:                          textbook   => 'Textbook course',
1.902     raeburn  15748:                    );
                   15749:     return (\@types,\%typename);
                   15750: }
                   15751: 
1.156     albertel 15752: sub icon {
                   15753:     my ($file)=@_;
1.505     albertel 15754:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15755:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15756:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15757:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15758: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15759: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15760: 	            $curfext.".gif") {
                   15761: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15762: 		$curfext.".gif";
                   15763: 	}
                   15764:     }
1.249     albertel 15765:     return &lonhttpdurl($iconname);
1.154     albertel 15766: } 
1.84      albertel 15767: 
1.575     albertel 15768: sub lonhttpdurl {
1.692     www      15769: #
                   15770: # Had been used for "small fry" static images on separate port 8080.
                   15771: # Modify here if lightweight http functionality desired again.
                   15772: # Currently eliminated due to increasing firewall issues.
                   15773: #
1.575     albertel 15774:     my ($url)=@_;
1.692     www      15775:     return $url;
1.215     albertel 15776: }
                   15777: 
1.213     albertel 15778: sub connection_aborted {
                   15779:     my ($r)=@_;
                   15780:     $r->print(" ");$r->rflush();
                   15781:     my $c = $r->connection;
                   15782:     return $c->aborted();
                   15783: }
                   15784: 
1.221     foxr     15785: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15786: #    strings as 'strings'.
                   15787: sub escape_single {
1.221     foxr     15788:     my ($input) = @_;
1.223     albertel 15789:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15790:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15791:     return $input;
                   15792: }
1.223     albertel 15793: 
1.222     foxr     15794: #  Same as escape_single, but escape's "'s  This 
                   15795: #  can be used for  "strings"
                   15796: sub escape_double {
                   15797:     my ($input) = @_;
                   15798:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15799:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15800:     return $input;
                   15801: }
1.223     albertel 15802:  
1.222     foxr     15803: #   Escapes the last element of a full URL.
                   15804: sub escape_url {
                   15805:     my ($url)   = @_;
1.238     raeburn  15806:     my @urlslices = split(/\//, $url,-1);
1.369     www      15807:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15808:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15809: }
1.462     albertel 15810: 
1.820     raeburn  15811: sub compare_arrays {
                   15812:     my ($arrayref1,$arrayref2) = @_;
                   15813:     my (@difference,%count);
                   15814:     @difference = ();
                   15815:     %count = ();
                   15816:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15817:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15818:         foreach my $element (keys(%count)) {
                   15819:             if ($count{$element} == 1) {
                   15820:                 push(@difference,$element);
                   15821:             }
                   15822:         }
                   15823:     }
                   15824:     return @difference;
                   15825: }
                   15826: 
1.1075.2.152  raeburn  15827: sub lon_status_items {
                   15828:     my %defaults = (
                   15829:                      E         => 100,
                   15830:                      W         => 4,
                   15831:                      N         => 1,
                   15832:                      U         => 5,
                   15833:                      threshold => 200,
                   15834:                      sysmail   => 2500,
                   15835:                    );
                   15836:     my %names = (
                   15837:                    E => 'Errors',
                   15838:                    W => 'Warnings',
                   15839:                    N => 'Notices',
                   15840:                    U => 'Unsent',
                   15841:                 );
                   15842:     return (\%defaults,\%names);
                   15843: }
                   15844: 
1.817     bisitz   15845: # -------------------------------------------------------- Initialize user login
1.462     albertel 15846: sub init_user_environment {
1.463     albertel 15847:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15848:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15849: 
                   15850:     my $public=($username eq 'public' && $domain eq 'public');
                   15851: 
                   15852: # See if old ID present, if so, remove
                   15853: 
1.1062    raeburn  15854:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15855:     my $now=time;
                   15856: 
                   15857:     if ($public) {
                   15858: 	my $max_public=100;
                   15859: 	my $oldest;
                   15860: 	my $oldest_time=0;
                   15861: 	for(my $next=1;$next<=$max_public;$next++) {
                   15862: 	    if (-e $lonids."/publicuser_$next.id") {
                   15863: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15864: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15865: 		    $oldest_time=$mtime;
                   15866: 		    $oldest=$next;
                   15867: 		}
                   15868: 	    } else {
                   15869: 		$cookie="publicuser_$next";
                   15870: 		last;
                   15871: 	    }
                   15872: 	}
                   15873: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15874:     } else {
1.463     albertel 15875: 	# if this isn't a robot, kill any existing non-robot sessions
                   15876: 	if (!$args->{'robot'}) {
                   15877: 	    opendir(DIR,$lonids);
                   15878: 	    while ($filename=readdir(DIR)) {
                   15879: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15880:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15881:                             &GDBM_READER(),0640)) {
                   15882:                         my $linkedfile;
                   15883:                         if (exists($oldenv{'user.linkedenv'})) {
                   15884:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15885:                         }
                   15886:                         untie(%oldenv);
                   15887:                         if (unlink("$lonids/$filename")) {
                   15888:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15889:                                 if (-l "$lonids/$linkedfile.id") {
                   15890:                                     unlink("$lonids/$linkedfile.id");
                   15891:                                 }
                   15892:                             }
                   15893:                         }
                   15894:                     } else {
                   15895:                         unlink($lonids.'/'.$filename);
                   15896:                     }
1.463     albertel 15897: 		}
1.462     albertel 15898: 	    }
1.463     albertel 15899: 	    closedir(DIR);
1.1075.2.84  raeburn  15900: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15901:             my $namespace = 'nohist_courseeditor';
                   15902:             my $lockingkey = 'paste'."\0".'locked_num';
                   15903:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15904:                                                 $domain,$username);
                   15905:             if (exists($lockhash{$lockingkey})) {
                   15906:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15907:                 unless ($delresult eq 'ok') {
                   15908:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15909:                 }
                   15910:             }
1.462     albertel 15911: 	}
                   15912: # Give them a new cookie
1.463     albertel 15913: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15914: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15915: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15916:     
                   15917: # Initialize roles
                   15918: 
1.1062    raeburn  15919: 	($userroles,$firstaccenv,$timerintenv) = 
                   15920:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15921:     }
                   15922: # ------------------------------------ Check browser type and MathML capability
                   15923: 
1.1075.2.77  raeburn  15924:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15925:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15926: 
                   15927: # ------------------------------------------------------------- Get environment
                   15928: 
                   15929:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15930:     my ($tmp) = keys(%userenv);
                   15931:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15932:     } else {
                   15933: 	undef(%userenv);
                   15934:     }
                   15935:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15936: 	$form->{'interface'}=$userenv{'interface'};
                   15937:     }
                   15938:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15939: 
                   15940: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15941:     foreach my $option ('interface','localpath','localres') {
                   15942:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15943:     }
                   15944: # --------------------------------------------------------- Write first profile
                   15945: 
                   15946:     {
1.1075.2.150  raeburn  15947:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 15948: 	my %initial_env = 
                   15949: 	    ("user.name"          => $username,
                   15950: 	     "user.domain"        => $domain,
                   15951: 	     "user.home"          => $authhost,
                   15952: 	     "browser.type"       => $clientbrowser,
                   15953: 	     "browser.version"    => $clientversion,
                   15954: 	     "browser.mathml"     => $clientmathml,
                   15955: 	     "browser.unicode"    => $clientunicode,
                   15956: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15957:              "browser.mobile"     => $clientmobile,
                   15958:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15959:              "browser.osversion"  => $clientosversion,
1.462     albertel 15960: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15961: 	     "request.course.fn"  => '',
                   15962: 	     "request.course.uri" => '',
                   15963: 	     "request.course.sec" => '',
                   15964: 	     "request.role"       => 'cm',
                   15965: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  15966: 	     "request.host"       => $ip,);
1.462     albertel 15967: 
                   15968:         if ($form->{'localpath'}) {
                   15969: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15970: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15971:         }
                   15972: 	
                   15973: 	if ($form->{'interface'}) {
                   15974: 	    $form->{'interface'}=~s/\W//gs;
                   15975: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15976: 	    $env{'browser.interface'}=$form->{'interface'};
                   15977: 	}
                   15978: 
1.1075.2.54  raeburn  15979:         if ($form->{'iptoken'}) {
                   15980:             my $lonhost = $r->dir_config('lonHostID');
                   15981:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15982:             $env{'user.noloadbalance'} = $lonhost;
                   15983:         }
                   15984: 
1.1075.2.120  raeburn  15985:         if ($form->{'noloadbalance'}) {
                   15986:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15987:             my $hosthere = $form->{'noloadbalance'};
                   15988:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15989:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15990:                 $env{'user.noloadbalance'} = $hosthere;
                   15991:             }
                   15992:         }
                   15993: 
1.1016    raeburn  15994:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15995:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15996:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15997: 
1.1075.2.125  raeburn  15998:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15999:                 $userenv{'availabletools.'.$tool} = 
                   16000:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16001:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16002:             }
1.724     raeburn  16003: 
1.1075.2.125  raeburn  16004:             foreach my $crstype ('official','unofficial','community','textbook') {
                   16005:                 $userenv{'canrequest.'.$crstype} =
                   16006:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16007:                                                       'reload','requestcourses',
                   16008:                                                       \%userenv,\%domdef,\%is_adv);
                   16009:             }
1.765     raeburn  16010: 
1.1075.2.125  raeburn  16011:             $userenv{'canrequest.author'} =
                   16012:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16013:                                                   'reload','requestauthor',
                   16014:                                                   \%userenv,\%domdef,\%is_adv);
                   16015:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16016:                                                  $domain,$username);
                   16017:             my $reqstatus = $reqauthor{'author_status'};
                   16018:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16019:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16020:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16021:                                                       $reqauthor{'author'}{'timestamp'};
                   16022:                 }
1.1075.2.14  raeburn  16023:             }
                   16024:         }
                   16025: 
1.462     albertel 16026: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16027: 
1.462     albertel 16028: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16029: 		 &GDBM_WRCREAT(),0640)) {
                   16030: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16031: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16032: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16033:             if (ref($firstaccenv) eq 'HASH') {
                   16034:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16035:             }
                   16036:             if (ref($timerintenv) eq 'HASH') {
                   16037:                 &_add_to_env(\%disk_env,$timerintenv);
                   16038:             }
1.463     albertel 16039: 	    if (ref($args->{'extra_env'})) {
                   16040: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16041: 	    }
1.462     albertel 16042: 	    untie(%disk_env);
                   16043: 	} else {
1.705     tempelho 16044: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16045: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16046: 	    return 'error: '.$!;
                   16047: 	}
                   16048:     }
                   16049:     $env{'request.role'}='cm';
                   16050:     $env{'request.role.adv'}=$env{'user.adv'};
                   16051:     $env{'browser.type'}=$clientbrowser;
                   16052: 
                   16053:     return $cookie;
                   16054: 
                   16055: }
                   16056: 
                   16057: sub _add_to_env {
                   16058:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16059:     if (ref($env_data) eq 'HASH') {
                   16060:         while (my ($key,$value) = each(%$env_data)) {
                   16061: 	    $idf->{$prefix.$key} = $value;
                   16062: 	    $env{$prefix.$key}   = $value;
                   16063:         }
1.462     albertel 16064:     }
                   16065: }
                   16066: 
1.685     tempelho 16067: # --- Get the symbolic name of a problem and the url
                   16068: sub get_symb {
                   16069:     my ($request,$silent) = @_;
1.726     raeburn  16070:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16071:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16072:     if ($symb eq '') {
                   16073:         if (!$silent) {
1.1071    raeburn  16074:             if (ref($request)) { 
                   16075:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16076:             }
1.685     tempelho 16077:             return ();
                   16078:         }
                   16079:     }
                   16080:     &Apache::lonenc::check_decrypt(\$symb);
                   16081:     return ($symb);
                   16082: }
                   16083: 
                   16084: # --------------------------------------------------------------Get annotation
                   16085: 
                   16086: sub get_annotation {
                   16087:     my ($symb,$enc) = @_;
                   16088: 
                   16089:     my $key = $symb;
                   16090:     if (!$enc) {
                   16091:         $key =
                   16092:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16093:     }
                   16094:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16095:     return $annotation{$key};
                   16096: }
                   16097: 
                   16098: sub clean_symb {
1.731     raeburn  16099:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16100: 
                   16101:     &Apache::lonenc::check_decrypt(\$symb);
                   16102:     my $enc = $env{'request.enc'};
1.731     raeburn  16103:     if ($delete_enc) {
1.730     raeburn  16104:         delete($env{'request.enc'});
                   16105:     }
1.685     tempelho 16106: 
                   16107:     return ($symb,$enc);
                   16108: }
1.462     albertel 16109: 
1.1075.2.69  raeburn  16110: ############################################################
                   16111: ############################################################
                   16112: 
                   16113: =pod
                   16114: 
                   16115: =head1 Routines for building display used to search for courses
                   16116: 
                   16117: 
                   16118: =over 4
                   16119: 
                   16120: =item * &build_filters()
                   16121: 
                   16122: Create markup for a table used to set filters to use when selecting
                   16123: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16124: and quotacheck.pl
                   16125: 
                   16126: 
                   16127: Inputs:
                   16128: 
                   16129: filterlist - anonymous array of fields to include as potential filters
                   16130: 
                   16131: crstype - course type
                   16132: 
                   16133: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16134:               to pop-open a course selector (will contain "extra element").
                   16135: 
                   16136: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16137: 
                   16138: filter - anonymous hash of criteria and their values
                   16139: 
                   16140: action - form action
                   16141: 
                   16142: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16143: 
                   16144: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16145: 
                   16146: cloneruname - username of owner of new course who wants to clone
                   16147: 
                   16148: clonerudom - domain of owner of new course who wants to clone
                   16149: 
                   16150: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16151: 
                   16152: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16153: 
                   16154: codedom - domain
                   16155: 
                   16156: formname - value of form element named "form".
                   16157: 
                   16158: fixeddom - domain, if fixed.
                   16159: 
                   16160: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16161: 
                   16162: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16163: 
                   16164: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16165: 
                   16166: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16167: 
                   16168: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16169: 
                   16170: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16171: 
                   16172: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16173: 
                   16174: 
                   16175: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16176: 
                   16177: 
                   16178: Side Effects: None
                   16179: 
                   16180: =cut
                   16181: 
                   16182: # ---------------------------------------------- search for courses based on last activity etc.
                   16183: 
                   16184: sub build_filters {
                   16185:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16186:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16187:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16188:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16189:         $clonetext,$clonewarning) = @_;
                   16190:     my ($list,$jscript);
                   16191:     my $onchange = 'javascript:updateFilters(this)';
                   16192:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16193:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16194:         $typeselectform,$instcodetitle);
                   16195:     if ($formname eq '') {
                   16196:         $formname = $caller;
                   16197:     }
                   16198:     foreach my $item (@{$filterlist}) {
                   16199:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16200:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16201:             if ($item eq 'domainfilter') {
                   16202:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16203:             } elsif ($item eq 'coursefilter') {
                   16204:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16205:             } elsif ($item eq 'ownerfilter') {
                   16206:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16207:             } elsif ($item eq 'ownerdomfilter') {
                   16208:                 $filter->{'ownerdomfilter'} =
                   16209:                     &LONCAPA::clean_domain($filter->{$item});
                   16210:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16211:                                                        'ownerdomfilter',1);
                   16212:             } elsif ($item eq 'personfilter') {
                   16213:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16214:             } elsif ($item eq 'persondomfilter') {
                   16215:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16216:                                                         'persondomfilter',1);
                   16217:             } else {
                   16218:                 $filter->{$item} =~ s/\W//g;
                   16219:             }
                   16220:             if (!$filter->{$item}) {
                   16221:                 $filter->{$item} = '';
                   16222:             }
                   16223:         }
                   16224:         if ($item eq 'domainfilter') {
                   16225:             my $allow_blank = 1;
                   16226:             if ($formname eq 'portform') {
                   16227:                 $allow_blank=0;
                   16228:             } elsif ($formname eq 'studentform') {
                   16229:                 $allow_blank=0;
                   16230:             }
                   16231:             if ($fixeddom) {
                   16232:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16233:                                     ' value="'.$codedom.'" />'.
                   16234:                                     &Apache::lonnet::domain($codedom,'description');
                   16235:             } else {
                   16236:                 $domainselectform = &select_dom_form($filter->{$item},
                   16237:                                                      'domainfilter',
                   16238:                                                       $allow_blank,'',$onchange);
                   16239:             }
                   16240:         } else {
                   16241:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16242:         }
                   16243:     }
                   16244: 
                   16245:     # last course activity filter and selection
                   16246:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16247: 
                   16248:     # course created filter and selection
                   16249:     if (exists($filter->{'createdfilter'})) {
                   16250:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16251:     }
                   16252: 
                   16253:     my %lt = &Apache::lonlocal::texthash(
                   16254:                 'cac' => "$crstype Activity",
                   16255:                 'ccr' => "$crstype Created",
                   16256:                 'cde' => "$crstype Title",
                   16257:                 'cdo' => "$crstype Domain",
                   16258:                 'ins' => 'Institutional Code',
                   16259:                 'inc' => 'Institutional Categorization',
                   16260:                 'cow' => "$crstype Owner/Co-owner",
                   16261:                 'cop' => "$crstype Personnel Includes",
                   16262:                 'cog' => 'Type',
                   16263:              );
                   16264: 
                   16265:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16266:         my $typeval = 'Course';
                   16267:         if ($crstype eq 'Community') {
                   16268:             $typeval = 'Community';
                   16269:         }
                   16270:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16271:     } else {
                   16272:         $typeselectform =  '<select name="type" size="1"';
                   16273:         if ($onchange) {
                   16274:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16275:         }
                   16276:         $typeselectform .= '>'."\n";
                   16277:         foreach my $posstype ('Course','Community') {
                   16278:             $typeselectform.='<option value="'.$posstype.'"'.
                   16279:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16280:         }
                   16281:         $typeselectform.="</select>";
                   16282:     }
                   16283: 
                   16284:     my ($cloneableonlyform,$cloneabletitle);
                   16285:     if (exists($filter->{'cloneableonly'})) {
                   16286:         my $cloneableon = '';
                   16287:         my $cloneableoff = ' checked="checked"';
                   16288:         if ($filter->{'cloneableonly'}) {
                   16289:             $cloneableon = $cloneableoff;
                   16290:             $cloneableoff = '';
                   16291:         }
                   16292:         $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>';
                   16293:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16294:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16295:         } else {
                   16296:             $cloneabletitle = &mt('Cloneable by you');
                   16297:         }
                   16298:     }
                   16299:     my $officialjs;
                   16300:     if ($crstype eq 'Course') {
                   16301:         if (exists($filter->{'instcodefilter'})) {
                   16302: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16303: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16304:             if ($codedom) {
                   16305:                 $officialjs = 1;
                   16306:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16307:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16308:                                                                   $officialjs,$codetitlesref);
                   16309:                 if ($jscript) {
                   16310:                     $jscript = '<script type="text/javascript">'."\n".
                   16311:                                '// <![CDATA['."\n".
                   16312:                                $jscript."\n".
                   16313:                                '// ]]>'."\n".
                   16314:                                '</script>'."\n";
                   16315:                 }
                   16316:             }
                   16317:             if ($instcodeform eq '') {
                   16318:                 $instcodeform =
                   16319:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16320:                     $list->{'instcodefilter'}.'" />';
                   16321:                 $instcodetitle = $lt{'ins'};
                   16322:             } else {
                   16323:                 $instcodetitle = $lt{'inc'};
                   16324:             }
                   16325:             if ($fixeddom) {
                   16326:                 $instcodetitle .= '<br />('.$codedom.')';
                   16327:             }
                   16328:         }
                   16329:     }
                   16330:     my $output = qq|
                   16331: <form method="post" name="filterpicker" action="$action">
                   16332: <input type="hidden" name="form" value="$formname" />
                   16333: |;
                   16334:     if ($formname eq 'modifycourse') {
                   16335:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16336:                    '<input type="hidden" name="prevphase" value="'.
                   16337:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16338:     } elsif ($formname eq 'quotacheck') {
                   16339:         $output .= qq|
                   16340: <input type="hidden" name="sortby" value="" />
                   16341: <input type="hidden" name="sortorder" value="" />
                   16342: |;
                   16343:     } else {
1.1075.2.69  raeburn  16344:         my $name_input;
                   16345:         if ($cnameelement ne '') {
                   16346:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16347:                           $cnameelement.'" />';
                   16348:         }
                   16349:         $output .= qq|
                   16350: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16351: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16352: $name_input
                   16353: $roleelement
                   16354: $multelement
                   16355: $typeelement
                   16356: |;
                   16357:         if ($formname eq 'portform') {
                   16358:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16359:         }
                   16360:     }
                   16361:     if ($fixeddom) {
                   16362:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16363:     }
                   16364:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16365:     if ($sincefilterform) {
                   16366:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16367:                   .$sincefilterform
                   16368:                   .&Apache::lonhtmlcommon::row_closure();
                   16369:     }
                   16370:     if ($createdfilterform) {
                   16371:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16372:                   .$createdfilterform
                   16373:                   .&Apache::lonhtmlcommon::row_closure();
                   16374:     }
                   16375:     if ($domainselectform) {
                   16376:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16377:                   .$domainselectform
                   16378:                   .&Apache::lonhtmlcommon::row_closure();
                   16379:     }
                   16380:     if ($typeselectform) {
                   16381:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16382:             $output .= $typeselectform;
                   16383:         } else {
                   16384:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16385:                       .$typeselectform
                   16386:                       .&Apache::lonhtmlcommon::row_closure();
                   16387:         }
                   16388:     }
                   16389:     if ($instcodeform) {
                   16390:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16391:                   .$instcodeform
                   16392:                   .&Apache::lonhtmlcommon::row_closure();
                   16393:     }
                   16394:     if (exists($filter->{'ownerfilter'})) {
                   16395:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16396:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16397:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16398:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16399:                    $ownerdomselectform.'</td></tr></table>'.
                   16400:                    &Apache::lonhtmlcommon::row_closure();
                   16401:     }
                   16402:     if (exists($filter->{'personfilter'})) {
                   16403:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16404:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16405:                    '<input type="text" name="personfilter" size="20" value="'.
                   16406:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16407:                    $persondomselectform.'</td></tr></table>'.
                   16408:                    &Apache::lonhtmlcommon::row_closure();
                   16409:     }
                   16410:     if (exists($filter->{'coursefilter'})) {
                   16411:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16412:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16413:                   .$list->{'coursefilter'}.'" />'
                   16414:                   .&Apache::lonhtmlcommon::row_closure();
                   16415:     }
                   16416:     if ($cloneableonlyform) {
                   16417:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16418:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16419:     }
                   16420:     if (exists($filter->{'descriptfilter'})) {
                   16421:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16422:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16423:                   .$list->{'descriptfilter'}.'" />'
                   16424:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16425:     }
                   16426:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16427:                '<input type="hidden" name="updater" value="" />'."\n".
                   16428:                '<input type="submit" name="gosearch" value="'.
                   16429:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16430:     return $jscript.$clonewarning.$output;
                   16431: }
                   16432: 
                   16433: =pod
                   16434: 
                   16435: =item * &timebased_select_form()
                   16436: 
                   16437: Create markup for a dropdown list used to select a time-based
                   16438: filter e.g., Course Activity, Course Created, when searching for courses
                   16439: or communities
                   16440: 
                   16441: Inputs:
                   16442: 
                   16443: item - name of form element (sincefilter or createdfilter)
                   16444: 
                   16445: filter - anonymous hash of criteria and their values
                   16446: 
                   16447: Returns: HTML for a select box contained a blank, then six time selections,
                   16448:          with value set in incoming form variables currently selected.
                   16449: 
                   16450: Side Effects: None
                   16451: 
                   16452: =cut
                   16453: 
                   16454: sub timebased_select_form {
                   16455:     my ($item,$filter) = @_;
                   16456:     if (ref($filter) eq 'HASH') {
                   16457:         $filter->{$item} =~ s/[^\d-]//g;
                   16458:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16459:         return &select_form(
                   16460:                             $filter->{$item},
                   16461:                             $item,
                   16462:                             {      '-1' => '',
                   16463:                                 '86400' => &mt('today'),
                   16464:                                '604800' => &mt('last week'),
                   16465:                               '2592000' => &mt('last month'),
                   16466:                               '7776000' => &mt('last three months'),
                   16467:                              '15552000' => &mt('last six months'),
                   16468:                              '31104000' => &mt('last year'),
                   16469:                     'select_form_order' =>
                   16470:                            ['-1','86400','604800','2592000','7776000',
                   16471:                             '15552000','31104000']});
                   16472:     }
                   16473: }
                   16474: 
                   16475: =pod
                   16476: 
                   16477: =item * &js_changer()
                   16478: 
                   16479: Create script tag containing Javascript used to submit course search form
                   16480: when course type or domain is changed, and also to hide 'Searching ...' on
                   16481: page load completion for page showing search result.
                   16482: 
                   16483: Inputs: None
                   16484: 
                   16485: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16486: 
                   16487: Side Effects: None
                   16488: 
                   16489: =cut
                   16490: 
                   16491: sub js_changer {
                   16492:     return <<ENDJS;
                   16493: <script type="text/javascript">
                   16494: // <![CDATA[
                   16495: function updateFilters(caller) {
                   16496:     if (typeof(caller) != "undefined") {
                   16497:         document.filterpicker.updater.value = caller.name;
                   16498:     }
                   16499:     document.filterpicker.submit();
                   16500: }
                   16501: 
                   16502: function hideSearching() {
                   16503:     if (document.getElementById('searching')) {
                   16504:         document.getElementById('searching').style.display = 'none';
                   16505:     }
                   16506:     return;
                   16507: }
                   16508: 
                   16509: // ]]>
                   16510: </script>
                   16511: 
                   16512: ENDJS
                   16513: }
                   16514: 
                   16515: =pod
                   16516: 
                   16517: =item * &search_courses()
                   16518: 
                   16519: Process selected filters form course search form and pass to lonnet::courseiddump
                   16520: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16521: 
                   16522: Inputs:
                   16523: 
                   16524: dom - domain being searched
                   16525: 
                   16526: type - course type ('Course' or 'Community' or '.' if any).
                   16527: 
                   16528: filter - anonymous hash of criteria and their values
                   16529: 
                   16530: numtitles - for institutional codes - number of categories
                   16531: 
                   16532: cloneruname - optional username of new course owner
                   16533: 
                   16534: clonerudom - optional domain of new course owner
                   16535: 
1.1075.2.95  raeburn  16536: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16537:             (used when DC is using course creation form)
                   16538: 
                   16539: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16540: 
1.1075.2.95  raeburn  16541: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16542:            (and so can clone automatically)
                   16543: 
                   16544: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16545: 
                   16546: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16547:               courses to clone
1.1075.2.69  raeburn  16548: 
                   16549: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16550: 
                   16551: 
                   16552: Side Effects: None
                   16553: 
                   16554: =cut
                   16555: 
                   16556: 
                   16557: sub search_courses {
1.1075.2.95  raeburn  16558:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16559:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16560:     my (%courses,%showcourses,$cloner);
                   16561:     if (($filter->{'ownerfilter'} ne '') ||
                   16562:         ($filter->{'ownerdomfilter'} ne '')) {
                   16563:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16564:                                        $filter->{'ownerdomfilter'};
                   16565:     }
                   16566:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16567:         if (!$filter->{$item}) {
                   16568:             $filter->{$item}='.';
                   16569:         }
                   16570:     }
                   16571:     my $now = time;
                   16572:     my $timefilter =
                   16573:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16574:     my ($createdbefore,$createdafter);
                   16575:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16576:         $createdbefore = $now;
                   16577:         $createdafter = $now-$filter->{'createdfilter'};
                   16578:     }
                   16579:     my ($instcodefilter,$regexpok);
                   16580:     if ($numtitles) {
                   16581:         if ($env{'form.official'} eq 'on') {
                   16582:             $instcodefilter =
                   16583:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16584:             $regexpok = 1;
                   16585:         } elsif ($env{'form.official'} eq 'off') {
                   16586:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16587:             unless ($instcodefilter eq '') {
                   16588:                 $regexpok = -1;
                   16589:             }
                   16590:         }
                   16591:     } else {
                   16592:         $instcodefilter = $filter->{'instcodefilter'};
                   16593:     }
                   16594:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16595:     if ($type eq '') { $type = '.'; }
                   16596: 
                   16597:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16598:         $cloner = $cloneruname.':'.$clonerudom;
                   16599:     }
                   16600:     %courses = &Apache::lonnet::courseiddump($dom,
                   16601:                                              $filter->{'descriptfilter'},
                   16602:                                              $timefilter,
                   16603:                                              $instcodefilter,
                   16604:                                              $filter->{'combownerfilter'},
                   16605:                                              $filter->{'coursefilter'},
                   16606:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16607:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16608:                                              $filter->{'cloneableonly'},
                   16609:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16610:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16611:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16612:         my $ccrole;
                   16613:         if ($type eq 'Community') {
                   16614:             $ccrole = 'co';
                   16615:         } else {
                   16616:             $ccrole = 'cc';
                   16617:         }
                   16618:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16619:                                                      $filter->{'persondomfilter'},
                   16620:                                                      'userroles',undef,
                   16621:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16622:                                                      $dom);
                   16623:         foreach my $role (keys(%rolehash)) {
                   16624:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16625:             my $cid = $cdom.'_'.$cnum;
                   16626:             if (exists($courses{$cid})) {
                   16627:                 if (ref($courses{$cid}) eq 'HASH') {
                   16628:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16629:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16630:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16631:                         }
                   16632:                     } else {
                   16633:                         $courses{$cid}{roles} = [$courserole];
                   16634:                     }
                   16635:                     $showcourses{$cid} = $courses{$cid};
                   16636:                 }
                   16637:             }
                   16638:         }
                   16639:         %courses = %showcourses;
                   16640:     }
                   16641:     return %courses;
                   16642: }
                   16643: 
                   16644: =pod
                   16645: 
                   16646: =back
                   16647: 
1.1075.2.88  raeburn  16648: =head1 Routines for version requirements for current course.
                   16649: 
                   16650: =over 4
                   16651: 
                   16652: =item * &check_release_required()
                   16653: 
                   16654: Compares required LON-CAPA version with version on server, and
                   16655: if required version is newer looks for a server with the required version.
                   16656: 
                   16657: Looks first at servers in user's owen domain; if none suitable, looks at
                   16658: servers in course's domain are permitted to host sessions for user's domain.
                   16659: 
                   16660: Inputs:
                   16661: 
                   16662: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16663: 
                   16664: $courseid - Course ID of current course
                   16665: 
                   16666: $rolecode - User's current role in course (for switchserver query string).
                   16667: 
                   16668: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16669: 
                   16670: 
                   16671: Returns:
                   16672: 
                   16673: $switchserver - query string tp append to /adm/switchserver call (if
                   16674:                 current server's LON-CAPA version is too old.
                   16675: 
                   16676: $warning - Message is displayed if no suitable server could be found.
                   16677: 
                   16678: =cut
                   16679: 
                   16680: sub check_release_required {
                   16681:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16682:     my ($switchserver,$warning);
                   16683:     if ($required ne '') {
                   16684:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16685:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16686:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16687:             my $otherserver;
                   16688:             if (($major eq '' && $minor eq '') ||
                   16689:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16690:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16691:                 my $switchlcrev =
                   16692:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16693:                                                            $userdomserver);
                   16694:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16695:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16696:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16697:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16698:                     if ($cdom ne $env{'user.domain'}) {
                   16699:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16700:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16701:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16702:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16703:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16704:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16705:                         my $canhost =
                   16706:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16707:                                                               $coursedomserver,
                   16708:                                                               $remoterev,
                   16709:                                                               $udomdefaults{'remotesessions'},
                   16710:                                                               $defdomdefaults{'hostedsessions'});
                   16711: 
                   16712:                         if ($canhost) {
                   16713:                             $otherserver = $coursedomserver;
                   16714:                         } else {
                   16715:                             $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.");
                   16716:                         }
                   16717:                     } else {
                   16718:                         $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).");
                   16719:                     }
                   16720:                 } else {
                   16721:                     $otherserver = $userdomserver;
                   16722:                 }
                   16723:             }
                   16724:             if ($otherserver ne '') {
                   16725:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16726:             }
                   16727:         }
                   16728:     }
                   16729:     return ($switchserver,$warning);
                   16730: }
                   16731: 
                   16732: =pod
                   16733: 
                   16734: =item * &check_release_result()
                   16735: 
                   16736: Inputs:
                   16737: 
                   16738: $switchwarning - Warning message if no suitable server found to host session.
                   16739: 
                   16740: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16741:                 and current role.
                   16742: 
                   16743: Returns: HTML to display with information about requirement to switch server.
                   16744:          Either displaying warning with link to Roles/Courses screen or
                   16745:          display link to switchserver.
                   16746: 
1.1075.2.69  raeburn  16747: =cut
                   16748: 
1.1075.2.88  raeburn  16749: sub check_release_result {
                   16750:     my ($switchwarning,$switchserver) = @_;
                   16751:     my $output = &start_page('Selected course unavailable on this server').
                   16752:                  '<p class="LC_warning">';
                   16753:     if ($switchwarning) {
                   16754:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16755:         if (&show_course()) {
                   16756:             $output .= &mt('Display courses');
                   16757:         } else {
                   16758:             $output .= &mt('Display roles');
                   16759:         }
                   16760:         $output .= '</a>';
                   16761:     } elsif ($switchserver) {
                   16762:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16763:                    '<br />'.
                   16764:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16765:                    &mt('Switch Server').
                   16766:                    '</a>';
                   16767:     }
                   16768:     $output .= '</p>'.&end_page();
                   16769:     return $output;
                   16770: }
                   16771: 
                   16772: =pod
                   16773: 
                   16774: =item * &needs_coursereinit()
                   16775: 
                   16776: Determine if course contents stored for user's session needs to be
                   16777: refreshed, because content has changed since "Big Hash" last tied.
                   16778: 
                   16779: Check for change is made if time last checked is more than 10 minutes ago
                   16780: (by default).
                   16781: 
                   16782: Inputs:
                   16783: 
                   16784: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16785: 
                   16786: $interval (optional) - Time which may elapse (in s) between last check for content
                   16787:                        change in current course. (default: 600 s).
                   16788: 
                   16789: Returns: an array; first element is:
                   16790: 
                   16791: =over 4
                   16792: 
                   16793: 'switch' - if content updates mean user's session
                   16794:            needs to be switched to a server running a newer LON-CAPA version
                   16795: 
                   16796: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16797:            on current server hosting user's session
                   16798: 
                   16799: ''       - if no action required.
                   16800: 
                   16801: =back
                   16802: 
                   16803: If first item element is 'switch':
                   16804: 
                   16805: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16806: 
                   16807: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16808:                               and current role.
                   16809: 
                   16810: otherwise: no other elements returned.
                   16811: 
                   16812: =back
                   16813: 
                   16814: =cut
                   16815: 
                   16816: sub needs_coursereinit {
                   16817:     my ($loncaparev,$interval) = @_;
                   16818:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16819:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16820:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16821:     my $now = time;
                   16822:     if ($interval eq '') {
                   16823:         $interval = 600;
                   16824:     }
                   16825:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16826:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16827:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16828:         if ($lastchange > $env{'request.course.tied'}) {
                   16829:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16830:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16831:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16832:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16833:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16834:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16835:                     my ($switchserver,$switchwarning) =
                   16836:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16837:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16838:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16839:                         return ('switch',$switchwarning,$switchserver);
                   16840:                     }
                   16841:                 }
                   16842:             }
                   16843:             return ('update');
                   16844:         }
                   16845:     }
                   16846:     return ();
                   16847: }
1.1075.2.69  raeburn  16848: 
1.1075.2.11  raeburn  16849: sub update_content_constraints {
                   16850:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16851:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16852:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16853:     my %checkresponsetypes;
                   16854:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16855:         my ($item,$name,$value) = split(/:/,$key);
                   16856:         if ($item eq 'resourcetag') {
                   16857:             if ($name eq 'responsetype') {
                   16858:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16859:             }
                   16860:         }
                   16861:     }
                   16862:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16863:     if (defined($navmap)) {
                   16864:         my %allresponses;
                   16865:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16866:             my %responses = $res->responseTypes();
                   16867:             foreach my $key (keys(%responses)) {
                   16868:                 next unless(exists($checkresponsetypes{$key}));
                   16869:                 $allresponses{$key} += $responses{$key};
                   16870:             }
                   16871:         }
                   16872:         foreach my $key (keys(%allresponses)) {
                   16873:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16874:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16875:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16876:             }
                   16877:         }
                   16878:         undef($navmap);
                   16879:     }
                   16880:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16881:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16882:     }
                   16883:     return;
                   16884: }
                   16885: 
1.1075.2.27  raeburn  16886: sub allmaps_incourse {
                   16887:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16888:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16889:         $cid = $env{'request.course.id'};
                   16890:         $cdom = $env{'course.'.$cid.'.domain'};
                   16891:         $cnum = $env{'course.'.$cid.'.num'};
                   16892:         $chome = $env{'course.'.$cid.'.home'};
                   16893:     }
                   16894:     my %allmaps = ();
                   16895:     my $lastchange =
                   16896:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16897:     if ($lastchange > $env{'request.course.tied'}) {
                   16898:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16899:         unless ($ferr) {
                   16900:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16901:         }
                   16902:     }
                   16903:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16904:     if (defined($navmap)) {
                   16905:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16906:             $allmaps{$res->src()} = 1;
                   16907:         }
                   16908:     }
                   16909:     return \%allmaps;
                   16910: }
                   16911: 
1.1075.2.11  raeburn  16912: sub parse_supplemental_title {
                   16913:     my ($title) = @_;
                   16914: 
                   16915:     my ($foldertitle,$renametitle);
                   16916:     if ($title =~ /&amp;&amp;&amp;/) {
                   16917:         $title = &HTML::Entites::decode($title);
                   16918:     }
                   16919:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16920:         $renametitle=$4;
                   16921:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16922:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16923:         my $name =  &plainname($uname,$udom);
                   16924:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16925:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16926:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16927:             $name.': <br />'.$foldertitle;
                   16928:     }
                   16929:     if (wantarray) {
                   16930:         return ($title,$foldertitle,$renametitle);
                   16931:     }
                   16932:     return $title;
                   16933: }
                   16934: 
1.1075.2.43  raeburn  16935: sub recurse_supplemental {
                   16936:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16937:     if ($suppmap) {
                   16938:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16939:         if ($fatal) {
                   16940:             $errors ++;
                   16941:         } else {
                   16942:             if ($#LONCAPA::map::resources > 0) {
                   16943:                 foreach my $res (@LONCAPA::map::resources) {
                   16944:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16945:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16946:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16947:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16948:                         } else {
                   16949:                             $numfiles ++;
                   16950:                         }
                   16951:                     }
                   16952:                 }
                   16953:             }
                   16954:         }
                   16955:     }
                   16956:     return ($numfiles,$errors);
                   16957: }
                   16958: 
1.1075.2.18  raeburn  16959: sub symb_to_docspath {
1.1075.2.119  raeburn  16960:     my ($symb,$navmapref) = @_;
                   16961:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16962:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16963:     if ($resurl=~/\.(sequence|page)$/) {
                   16964:         $mapurl=$resurl;
                   16965:     } elsif ($resurl eq 'adm/navmaps') {
                   16966:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16967:     }
                   16968:     my $mapresobj;
1.1075.2.119  raeburn  16969:     unless (ref($$navmapref)) {
                   16970:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16971:     }
                   16972:     if (ref($$navmapref)) {
                   16973:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16974:     }
                   16975:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16976:     my $type=$2;
                   16977:     my $path;
                   16978:     if (ref($mapresobj)) {
                   16979:         my $pcslist = $mapresobj->map_hierarchy();
                   16980:         if ($pcslist ne '') {
                   16981:             foreach my $pc (split(/,/,$pcslist)) {
                   16982:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16983:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16984:                 if (ref($res)) {
                   16985:                     my $thisurl = $res->src();
                   16986:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16987:                     my $thistitle = $res->title();
                   16988:                     $path .= '&'.
                   16989:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16990:                              &escape($thistitle).
1.1075.2.18  raeburn  16991:                              ':'.$res->randompick().
                   16992:                              ':'.$res->randomout().
                   16993:                              ':'.$res->encrypted().
                   16994:                              ':'.$res->randomorder().
                   16995:                              ':'.$res->is_page();
                   16996:                 }
                   16997:             }
                   16998:         }
                   16999:         $path =~ s/^\&//;
                   17000:         my $maptitle = $mapresobj->title();
                   17001:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17002:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17003:         }
                   17004:         $path .= (($path ne '')? '&' : '').
                   17005:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17006:                  &escape($maptitle).
1.1075.2.18  raeburn  17007:                  ':'.$mapresobj->randompick().
                   17008:                  ':'.$mapresobj->randomout().
                   17009:                  ':'.$mapresobj->encrypted().
                   17010:                  ':'.$mapresobj->randomorder().
                   17011:                  ':'.$mapresobj->is_page();
                   17012:     } else {
                   17013:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17014:         my $ispage = (($type eq 'page')? 1 : '');
                   17015:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17016:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17017:         }
                   17018:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17019:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  17020:     }
                   17021:     unless ($mapurl eq 'default') {
                   17022:         $path = 'default&'.
1.1075.2.46  raeburn  17023:                 &escape('Main Content').
1.1075.2.18  raeburn  17024:                 ':::::&'.$path;
                   17025:     }
                   17026:     return $path;
                   17027: }
                   17028: 
1.1075.2.14  raeburn  17029: sub captcha_display {
1.1075.2.137  raeburn  17030:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17031:     my ($output,$error);
1.1075.2.107  raeburn  17032:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17033:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17034:     if ($captcha eq 'original') {
                   17035:         $output = &create_captcha();
                   17036:         unless ($output) {
                   17037:             $error = 'captcha';
                   17038:         }
                   17039:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17040:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17041:         unless ($output) {
                   17042:             $error = 'recaptcha';
                   17043:         }
                   17044:     }
1.1075.2.107  raeburn  17045:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17046: }
                   17047: 
                   17048: sub captcha_response {
1.1075.2.137  raeburn  17049:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17050:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17051:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17052:     if ($captcha eq 'original') {
                   17053:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17054:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17055:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17056:     } else {
                   17057:         $captcha_chk = 1;
                   17058:     }
                   17059:     return ($captcha_chk,$captcha_error);
                   17060: }
                   17061: 
                   17062: sub get_captcha_config {
1.1075.2.137  raeburn  17063:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17064:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17065:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17066:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17067:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17068:     if ($context eq 'usercreation') {
                   17069:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17070:         if (ref($domconfig{$context}) eq 'HASH') {
                   17071:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17072:             if (ref($hashtocheck) eq 'HASH') {
                   17073:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17074:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17075:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17076:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17077:                     }
                   17078:                     if ($privkey && $pubkey) {
                   17079:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17080:                         $version = $hashtocheck->{'recaptchaversion'};
                   17081:                         if ($version ne '2') {
                   17082:                             $version = 1;
                   17083:                         }
1.1075.2.14  raeburn  17084:                     } else {
                   17085:                         $captcha = 'original';
                   17086:                     }
                   17087:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17088:                     $captcha = 'original';
                   17089:                 }
                   17090:             }
                   17091:         } else {
                   17092:             $captcha = 'captcha';
                   17093:         }
                   17094:     } elsif ($context eq 'login') {
                   17095:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17096:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17097:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17098:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17099:             if ($privkey && $pubkey) {
                   17100:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17101:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17102:                 if ($version ne '2') {
                   17103:                     $version = 1;
                   17104:                 }
1.1075.2.14  raeburn  17105:             } else {
                   17106:                 $captcha = 'original';
                   17107:             }
                   17108:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17109:             $captcha = 'original';
                   17110:         }
1.1075.2.137  raeburn  17111:     } elsif ($context eq 'passwords') {
                   17112:         if ($dom_in_effect) {
                   17113:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17114:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17115:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17116:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17117:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17118:                 }
                   17119:                 if ($privkey && $pubkey) {
                   17120:                     $captcha = 'recaptcha';
                   17121:                     $version = $passwdconf{'recaptchaversion'};
                   17122:                     if ($version ne '2') {
                   17123:                         $version = 1;
                   17124:                     }
                   17125:                 } else {
                   17126:                     $captcha = 'original';
                   17127:                 }
                   17128:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17129:                 $captcha = 'original';
                   17130:             }
                   17131:         }
1.1075.2.14  raeburn  17132:     }
1.1075.2.107  raeburn  17133:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17134: }
                   17135: 
                   17136: sub create_captcha {
                   17137:     my %captcha_params = &captcha_settings();
                   17138:     my ($output,$maxtries,$tries) = ('',10,0);
                   17139:     while ($tries < $maxtries) {
                   17140:         $tries ++;
                   17141:         my $captcha = Authen::Captcha->new (
                   17142:                                            output_folder => $captcha_params{'output_dir'},
                   17143:                                            data_folder   => $captcha_params{'db_dir'},
                   17144:                                           );
                   17145:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17146: 
                   17147:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17148:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17149:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17150:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17151:                       '<br />'.
                   17152:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17153:             last;
                   17154:         }
                   17155:     }
                   17156:     return $output;
                   17157: }
                   17158: 
                   17159: sub captcha_settings {
                   17160:     my %captcha_params = (
                   17161:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17162:                            www_output_dir => "/captchaspool",
                   17163:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17164:                            numchars       => '5',
                   17165:                          );
                   17166:     return %captcha_params;
                   17167: }
                   17168: 
                   17169: sub check_captcha {
                   17170:     my ($captcha_chk,$captcha_error);
                   17171:     my $code = $env{'form.code'};
                   17172:     my $md5sum = $env{'form.crypt'};
                   17173:     my %captcha_params = &captcha_settings();
                   17174:     my $captcha = Authen::Captcha->new(
                   17175:                       output_folder => $captcha_params{'output_dir'},
                   17176:                       data_folder   => $captcha_params{'db_dir'},
                   17177:                   );
1.1075.2.26  raeburn  17178:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17179:     my %captcha_hash = (
                   17180:                         0       => 'Code not checked (file error)',
                   17181:                        -1      => 'Failed: code expired',
                   17182:                        -2      => 'Failed: invalid code (not in database)',
                   17183:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17184:     );
                   17185:     if ($captcha_chk != 1) {
                   17186:         $captcha_error = $captcha_hash{$captcha_chk}
                   17187:     }
                   17188:     return ($captcha_chk,$captcha_error);
                   17189: }
                   17190: 
                   17191: sub create_recaptcha {
1.1075.2.107  raeburn  17192:     my ($pubkey,$version) = @_;
                   17193:     if ($version >= 2) {
                   17194:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17195:     } else {
                   17196:         my $use_ssl;
                   17197:         if ($ENV{'SERVER_PORT'} == 443) {
                   17198:             $use_ssl = 1;
                   17199:         }
                   17200:         my $captcha = Captcha::reCAPTCHA->new;
                   17201:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17202:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17203:                &mt('If the text is hard to read, [_1] will replace them.',
                   17204:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17205:                '<br /><br />';
                   17206:      }
1.1075.2.14  raeburn  17207: }
                   17208: 
                   17209: sub check_recaptcha {
1.1075.2.107  raeburn  17210:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17211:     my $captcha_chk;
1.1075.2.150  raeburn  17212:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  17213:     if ($version >= 2) {
                   17214:         my $ua = LWP::UserAgent->new;
                   17215:         $ua->timeout(10);
                   17216:         my %info = (
                   17217:                      secret   => $privkey,
                   17218:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  17219:                      remoteip => $ip,
1.1075.2.107  raeburn  17220:                    );
                   17221:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17222:         if ($response->is_success)  {
                   17223:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17224:             if (ref($data) eq 'HASH') {
                   17225:                 if ($data->{'success'}) {
                   17226:                     $captcha_chk = 1;
                   17227:                 }
                   17228:             }
                   17229:         }
                   17230:     } else {
                   17231:         my $captcha = Captcha::reCAPTCHA->new;
                   17232:         my $captcha_result =
                   17233:             $captcha->check_answer(
                   17234:                                     $privkey,
1.1075.2.150  raeburn  17235:                                     $ip,
1.1075.2.107  raeburn  17236:                                     $env{'form.recaptcha_challenge_field'},
                   17237:                                     $env{'form.recaptcha_response_field'},
                   17238:                                   );
                   17239:         if ($captcha_result->{is_valid}) {
                   17240:             $captcha_chk = 1;
                   17241:         }
1.1075.2.14  raeburn  17242:     }
                   17243:     return $captcha_chk;
                   17244: }
                   17245: 
1.1075.2.64  raeburn  17246: sub emailusername_info {
1.1075.2.103  raeburn  17247:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17248:     my %titles = &Apache::lonlocal::texthash (
                   17249:                      lastname      => 'Last Name',
                   17250:                      firstname     => 'First Name',
                   17251:                      institution   => 'School/college/university',
                   17252:                      location      => "School's city, state/province, country",
                   17253:                      web           => "School's web address",
                   17254:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17255:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17256:                  );
                   17257:     return (\@fields,\%titles);
                   17258: }
                   17259: 
1.1075.2.56  raeburn  17260: sub cleanup_html {
                   17261:     my ($incoming) = @_;
                   17262:     my $outgoing;
                   17263:     if ($incoming ne '') {
                   17264:         $outgoing = $incoming;
                   17265:         $outgoing =~ s/;/&#059;/g;
                   17266:         $outgoing =~ s/\#/&#035;/g;
                   17267:         $outgoing =~ s/\&/&#038;/g;
                   17268:         $outgoing =~ s/</&#060;/g;
                   17269:         $outgoing =~ s/>/&#062;/g;
                   17270:         $outgoing =~ s/\(/&#040/g;
                   17271:         $outgoing =~ s/\)/&#041;/g;
                   17272:         $outgoing =~ s/"/&#034;/g;
                   17273:         $outgoing =~ s/'/&#039;/g;
                   17274:         $outgoing =~ s/\$/&#036;/g;
                   17275:         $outgoing =~ s{/}{&#047;}g;
                   17276:         $outgoing =~ s/=/&#061;/g;
                   17277:         $outgoing =~ s/\\/&#092;/g
                   17278:     }
                   17279:     return $outgoing;
                   17280: }
                   17281: 
1.1075.2.74  raeburn  17282: # Checks for critical messages and returns a redirect url if one exists.
                   17283: # $interval indicates how often to check for messages.
                   17284: sub critical_redirect {
                   17285:     my ($interval) = @_;
                   17286:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17287:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17288:                                         $env{'user.name'});
                   17289:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17290:         my $redirecturl;
                   17291:         if ($what[0]) {
                   17292:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17293:                 $redirecturl='/adm/email?critical=display';
                   17294:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17295:                 return (1, $url);
                   17296:             }
                   17297:         }
                   17298:     }
                   17299:     return ();
                   17300: }
                   17301: 
1.1075.2.64  raeburn  17302: # Use:
                   17303: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17304: #
                   17305: ##################################################
                   17306: #          password associated functions         #
                   17307: ##################################################
                   17308: sub des_keys {
                   17309:     # Make a new key for DES encryption.
                   17310:     # Each key has two parts which are returned separately.
                   17311:     # Please note:  Each key must be passed through the &hex function
                   17312:     # before it is output to the web browser.  The hex versions cannot
                   17313:     # be used to decrypt.
                   17314:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17315:                 '8','9','a','b','c','d','e','f');
                   17316:     my $lkey='';
                   17317:     for (0..7) {
                   17318:         $lkey.=$hexstr[rand(15)];
                   17319:     }
                   17320:     my $ukey='';
                   17321:     for (0..7) {
                   17322:         $ukey.=$hexstr[rand(15)];
                   17323:     }
                   17324:     return ($lkey,$ukey);
                   17325: }
                   17326: 
                   17327: sub des_decrypt {
                   17328:     my ($key,$cyphertext) = @_;
                   17329:     my $keybin=pack("H16",$key);
                   17330:     my $cypher;
                   17331:     if ($Crypt::DES::VERSION>=2.03) {
                   17332:         $cypher=new Crypt::DES $keybin;
                   17333:     } else {
                   17334:         $cypher=new DES $keybin;
                   17335:     }
1.1075.2.106  raeburn  17336:     my $plaintext='';
                   17337:     my $cypherlength = length($cyphertext);
                   17338:     my $numchunks = int($cypherlength/32);
                   17339:     for (my $j=0; $j<$numchunks; $j++) {
                   17340:         my $start = $j*32;
                   17341:         my $cypherblock = substr($cyphertext,$start,32);
                   17342:         my $chunk =
                   17343:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17344:         $chunk .=
                   17345:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17346:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17347:         $plaintext .= $chunk;
                   17348:     }
1.1075.2.64  raeburn  17349:     return $plaintext;
                   17350: }
                   17351: 
1.1075.2.135  raeburn  17352: sub is_nonframeable {
                   17353:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17354:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17355:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17356: 
                   17357:     $remprotocol = lc($remprotocol);
                   17358:     $remhost = lc($remhost);
                   17359:     my $remport = 80;
                   17360:     if ($remprotocol eq 'https') {
                   17361:         $remport = 443;
                   17362:     }
                   17363:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17364:     if ($cached) {
                   17365:         unless ($nocache) {
                   17366:             if ($result) {
                   17367:                 return 1;
                   17368:             } else {
                   17369:                 return 0;
                   17370:             }
                   17371:         }
                   17372:     }
                   17373:     my $uselink;
                   17374:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  17375:     my $ua = LWP::UserAgent->new;
                   17376:     $ua->timeout(5);
                   17377:     my $response=$ua->request($request);
1.1075.2.135  raeburn  17378:     if ($response->is_success()) {
                   17379:         my $secpolicy = lc($response->header('content-security-policy'));
                   17380:         my $xframeop = lc($response->header('x-frame-options'));
                   17381:         $secpolicy =~ s/^\s+|\s+$//g;
                   17382:         $xframeop =~ s/^\s+|\s+$//g;
                   17383:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17384:             my $remotehost = $remprotocol.'://'.$remhost;
                   17385:             my ($origin,$protocol,$port);
                   17386:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17387:                 $port = $ENV{'SERVER_PORT'};
                   17388:             } else {
                   17389:                 $port = 80;
                   17390:             }
                   17391:             if ($absolute eq '') {
                   17392:                 $protocol = 'http:';
                   17393:                 if ($port == 443) {
                   17394:                     $protocol = 'https:';
                   17395:                 }
                   17396:                 $origin = $protocol.'//'.lc($hostname);
                   17397:             } else {
                   17398:                 $origin = lc($absolute);
                   17399:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17400:             }
                   17401:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17402:                 my $framepolicy = $1;
                   17403:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17404:                 my @policies = split(/\s+/,$framepolicy);
                   17405:                 if (@policies) {
                   17406:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17407:                         $uselink = 1;
                   17408:                     } else {
                   17409:                         $uselink = 1;
                   17410:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17411:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17412:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17413:                             undef($uselink);
                   17414:                         }
                   17415:                         if ($uselink) {
                   17416:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17417:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17418:                                     undef($uselink);
                   17419:                                 }
                   17420:                             }
                   17421:                         }
                   17422:                         if ($uselink) {
                   17423:                             my @possok;
                   17424:                             if ($ip ne '') {
                   17425:                                 push(@possok,$ip);
                   17426:                             }
                   17427:                             my $hoststr = '';
                   17428:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17429:                                 if ($hoststr eq '') {
                   17430:                                     $hoststr = $part;
                   17431:                                 } else {
                   17432:                                     $hoststr = "$part.$hoststr";
                   17433:                                 }
                   17434:                                 if ($hoststr eq $hostname) {
                   17435:                                     push(@possok,$hostname);
                   17436:                                 } else {
                   17437:                                     push(@possok,"*.$hoststr");
                   17438:                                 }
                   17439:                             }
                   17440:                             if (@possok) {
                   17441:                                 foreach my $poss (@possok) {
                   17442:                                     last if (!$uselink);
                   17443:                                     foreach my $policy (@policies) {
                   17444:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17445:                                             undef($uselink);
                   17446:                                             last;
                   17447:                                         }
                   17448:                                     }
                   17449:                                 }
                   17450:                             }
                   17451:                         }
                   17452:                     }
                   17453:                 }
                   17454:             } elsif ($xframeop ne '') {
                   17455:                 $uselink = 1;
                   17456:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17457:                 if (@policies) {
                   17458:                     unless (grep(/^deny$/,@policies)) {
                   17459:                         if ($origin ne '') {
                   17460:                             if (grep(/^sameorigin$/,@policies)) {
                   17461:                                 if ($remotehost eq $origin) {
                   17462:                                     undef($uselink);
                   17463:                                 }
                   17464:                             }
                   17465:                             if ($uselink) {
                   17466:                                 foreach my $policy (@policies) {
                   17467:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17468:                                         my $allowfrom = $1;
                   17469:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17470:                                             undef($uselink);
                   17471:                                             last;
                   17472:                                         }
                   17473:                                     }
                   17474:                                 }
                   17475:                             }
                   17476:                         }
                   17477:                     }
                   17478:                 }
                   17479:             }
                   17480:         }
                   17481:     }
                   17482:     if ($nocache) {
                   17483:         if ($cached) {
                   17484:             my $devalidate;
                   17485:             if ($uselink && !$result) {
                   17486:                 $devalidate = 1;
                   17487:             } elsif (!$uselink && $result) {
                   17488:                 $devalidate = 1;
                   17489:             }
                   17490:             if ($devalidate) {
                   17491:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17492:             }
                   17493:         }
                   17494:     } else {
                   17495:         if ($uselink) {
                   17496:             $result = 1;
                   17497:         } else {
                   17498:             $result = 0;
                   17499:         }
                   17500:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17501:     }
                   17502:     return $uselink;
                   17503: }
                   17504: 
1.112     bowersj2 17505: 1;
                   17506: __END__;
1.41      ng       17507: 

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