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

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.60! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.59 2013/12/27 15:50:34 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.479     albertel   72: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    73: use DateTime::TimeZone;
1.687     raeburn    74: use DateTime::Locale::Catalog;
1.1075.2.14  raeburn    75: use Authen::Captcha;
                     76: use Captcha::reCAPTCHA;
1.117     www        77: 
1.517     raeburn    78: # ---------------------------------------------- Designs
                     79: use vars qw(%defaultdesign);
                     80: 
1.22      www        81: my $readit;
                     82: 
1.517     raeburn    83: 
1.157     matthew    84: ##
                     85: ## Global Variables
                     86: ##
1.46      matthew    87: 
1.643     foxr       88: 
                     89: # ----------------------------------------------- SSI with retries:
                     90: #
                     91: 
                     92: =pod
                     93: 
1.648     raeburn    94: =head1 Server Side include with retries:
1.643     foxr       95: 
                     96: =over 4
                     97: 
1.648     raeburn    98: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       99: 
                    100: Performs an ssi with some number of retries.  Retries continue either
                    101: until the result is ok or until the retry count supplied by the
                    102: caller is exhausted.  
                    103: 
                    104: Inputs:
1.648     raeburn   105: 
                    106: =over 4
                    107: 
1.643     foxr      108: resource   - Identifies the resource to insert.
1.648     raeburn   109: 
1.643     foxr      110: retries    - Count of the number of retries allowed.
1.648     raeburn   111: 
1.643     foxr      112: form       - Hash that identifies the rendering options.
                    113: 
1.648     raeburn   114: =back
                    115: 
                    116: Returns:
                    117: 
                    118: =over 4
                    119: 
1.643     foxr      120: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   121: 
1.643     foxr      122: response   - The response from the last attempt (which may or may not have been successful.
                    123: 
1.648     raeburn   124: =back
                    125: 
                    126: =back
                    127: 
1.643     foxr      128: =cut
                    129: 
                    130: sub ssi_with_retries {
                    131:     my ($resource, $retries, %form) = @_;
                    132: 
                    133: 
                    134:     my $ok = 0;			# True if we got a good response.
                    135:     my $content;
                    136:     my $response;
                    137: 
                    138:     # Try to get the ssi done. within the retries count:
                    139: 
                    140:     do {
                    141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    142: 	$ok      = $response->is_success;
1.650     www       143:         if (!$ok) {
                    144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    145:         }
1.643     foxr      146: 	$retries--;
                    147:     } while (!$ok && ($retries > 0));
                    148: 
                    149:     if (!$ok) {
                    150: 	$content = '';		# On error return an empty content.
                    151:     }
                    152:     return ($content, $response);
                    153: 
                    154: }
                    155: 
                    156: 
                    157: 
1.20      www       158: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  159: my %language;
1.124     www       160: my %supported_language;
1.1048    foxr      161: my %latex_language;		# For choosing hyphenation in <transl..>
                    162: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  163: my %cprtag;
1.192     taceyjo1  164: my %scprtag;
1.351     www       165: my %fe; my %fd; my %fm;
1.41      ng        166: my %category_extensions;
1.12      harris41  167: 
1.46      matthew   168: # ---------------------------------------------- Thesaurus variables
1.144     matthew   169: #
                    170: # %Keywords:
                    171: #      A hash used by &keyword to determine if a word is considered a keyword.
                    172: # $thesaurus_db_file 
                    173: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   174: 
                    175: my %Keywords;
                    176: my $thesaurus_db_file;
                    177: 
1.144     matthew   178: #
                    179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    180: # thesaurus.tab, and filecategories.tab.
                    181: #
1.18      www       182: BEGIN {
1.46      matthew   183:     # Variable initialization
                    184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    185:     #
1.22      www       186:     unless ($readit) {
1.12      harris41  187: # ------------------------------------------------------------------- languages
                    188:     {
1.158     raeburn   189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    190:                                    '/language.tab';
                    191:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  192:             while (my $line = <$fh>) {
                    193:                 next if ($line=~/^\#/);
                    194:                 chomp($line);
1.1048    foxr      195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   196:                 $language{$key}=$val.' - '.$enc;
                    197:                 if ($sup) {
                    198:                     $supported_language{$key}=$sup;
                    199:                 }
1.1048    foxr      200: 		if ($latex) {
                    201: 		    $latex_language_bykey{$key} = $latex;
                    202: 		    $latex_language{$two} = $latex;
                    203: 		}
1.158     raeburn   204:             }
                    205:             close($fh);
                    206:         }
1.12      harris41  207:     }
                    208: # ------------------------------------------------------------------ copyrights
                    209:     {
1.158     raeburn   210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    211:                                   '/copyright.tab';
                    212:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  213:             while (my $line = <$fh>) {
                    214:                 next if ($line=~/^\#/);
                    215:                 chomp($line);
                    216:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   217:                 $cprtag{$key}=$val;
                    218:             }
                    219:             close($fh);
                    220:         }
1.12      harris41  221:     }
1.351     www       222: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  223:     {
                    224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    225:                                   '/source_copyright.tab';
                    226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  227:             while (my $line = <$fh>) {
                    228:                 next if ($line =~ /^\#/);
                    229:                 chomp($line);
                    230:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  231:                 $scprtag{$key}=$val;
                    232:             }
                    233:             close($fh);
                    234:         }
                    235:     }
1.63      www       236: 
1.517     raeburn   237: # -------------------------------------------------------------- default domain designs
1.63      www       238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   239:     my $designfile = $designdir.'/default.tab';
                    240:     if ( open (my $fh,"<$designfile") ) {
                    241:         while (my $line = <$fh>) {
                    242:             next if ($line =~ /^\#/);
                    243:             chomp($line);
                    244:             my ($key,$val)=(split(/\=/,$line));
                    245:             if ($val) { $defaultdesign{$key}=$val; }
                    246:         }
                    247:         close($fh);
1.63      www       248:     }
                    249: 
1.15      harris41  250: # ------------------------------------------------------------- file categories
                    251:     {
1.158     raeburn   252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    253:                                   '/filecategories.tab';
                    254:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  255: 	    while (my $line = <$fh>) {
                    256: 		next if ($line =~ /^\#/);
                    257: 		chomp($line);
                    258:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   259:                 push @{$category_extensions{lc($category)}},$extension;
                    260:             }
                    261:             close($fh);
                    262:         }
                    263: 
1.15      harris41  264:     }
1.12      harris41  265: # ------------------------------------------------------------------ file types
                    266:     {
1.158     raeburn   267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    268:                '/filetypes.tab';
                    269:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  270:             while (my $line = <$fh>) {
                    271: 		next if ($line =~ /^\#/);
                    272: 		chomp($line);
                    273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   274:                 if ($descr ne '') {
                    275:                     $fe{$ending}=lc($emb);
                    276:                     $fd{$ending}=$descr;
1.351     www       277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   278:                 }
                    279:             }
                    280:             close($fh);
                    281:         }
1.12      harris41  282:     }
1.22      www       283:     &Apache::lonnet::logthis(
1.705     tempelho  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       285:     $readit=1;
1.46      matthew   286:     }  # end of unless($readit) 
1.32      matthew   287:     
                    288: }
1.112     bowersj2  289: 
1.42      matthew   290: ###############################################################
                    291: ##           HTML and Javascript Helper Functions            ##
                    292: ###############################################################
                    293: 
                    294: =pod 
                    295: 
1.112     bowersj2  296: =head1 HTML and Javascript Functions
1.42      matthew   297: 
1.112     bowersj2  298: =over 4
                    299: 
1.648     raeburn   300: =item * &browser_and_searcher_javascript()
1.112     bowersj2  301: 
                    302: X<browsing, javascript>X<searching, javascript>Returns a string
                    303: containing javascript with two functions, C<openbrowser> and
                    304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    305: tags.
1.42      matthew   306: 
1.648     raeburn   307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   308: 
                    309: inputs: formname, elementname, only, omit
                    310: 
                    311: formname and elementname indicate the name of the html form and name of
                    312: the element that the results of the browsing selection are to be placed in. 
                    313: 
                    314: Specifying 'only' will restrict the browser to displaying only files
1.185     www       315: with the given extension.  Can be a comma separated list.
1.42      matthew   316: 
                    317: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       318: with the given extension.  Can be a comma separated list.
1.42      matthew   319: 
1.648     raeburn   320: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   321: 
                    322: Inputs: formname, elementname
                    323: 
                    324: formname and elementname specify the name of the html form and the name
                    325: of the element the selection from the search results will be placed in.
1.542     raeburn   326: 
1.42      matthew   327: =cut
                    328: 
                    329: sub browser_and_searcher_javascript {
1.199     albertel  330:     my ($mode)=@_;
                    331:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  332:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   333:     return <<END;
1.219     albertel  334: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   335:     var editbrowser = null;
1.135     albertel  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       337:         var url = '$resurl/?';
1.42      matthew   338:         if (editbrowser == null) {
                    339:             url += 'launch=1&';
                    340:         }
                    341:         url += 'catalogmode=interactive&';
1.199     albertel  342:         url += 'mode=$mode&';
1.611     albertel  343:         url += 'inhibitmenu=yes&';
1.42      matthew   344:         url += 'form=' + formname + '&';
                    345:         if (only != null) {
                    346:             url += 'only=' + only + '&';
1.217     albertel  347:         } else {
                    348:             url += 'only=&';
                    349: 	}
1.42      matthew   350:         if (omit != null) {
                    351:             url += 'omit=' + omit + '&';
1.217     albertel  352:         } else {
                    353:             url += 'omit=&';
                    354: 	}
1.135     albertel  355:         if (titleelement != null) {
                    356:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  357:         } else {
                    358: 	    url += 'titleelement=&';
                    359: 	}
1.42      matthew   360:         url += 'element=' + elementname + '';
                    361:         var title = 'Browser';
1.435     albertel  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   363:         options += ',width=700,height=600';
                    364:         editbrowser = open(url,title,options,'1');
                    365:         editbrowser.focus();
                    366:     }
                    367:     var editsearcher;
1.135     albertel  368:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   369:         var url = '/adm/searchcat?';
                    370:         if (editsearcher == null) {
                    371:             url += 'launch=1&';
                    372:         }
                    373:         url += 'catalogmode=interactive&';
1.199     albertel  374:         url += 'mode=$mode&';
1.42      matthew   375:         url += 'form=' + formname + '&';
1.135     albertel  376:         if (titleelement != null) {
                    377:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  378:         } else {
                    379: 	    url += 'titleelement=&';
                    380: 	}
1.42      matthew   381:         url += 'element=' + elementname + '';
                    382:         var title = 'Search';
1.435     albertel  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   384:         options += ',width=700,height=600';
                    385:         editsearcher = open(url,title,options,'1');
                    386:         editsearcher.focus();
                    387:     }
1.219     albertel  388: // END LON-CAPA Internal -->
1.42      matthew   389: END
1.170     www       390: }
                    391: 
                    392: sub lastresurl {
1.258     albertel  393:     if ($env{'environment.lastresurl'}) {
                    394: 	return $env{'environment.lastresurl'}
1.170     www       395:     } else {
                    396: 	return '/res';
                    397:     }
                    398: }
                    399: 
                    400: sub storeresurl {
                    401:     my $resurl=&Apache::lonnet::clutter(shift);
                    402:     unless ($resurl=~/^\/res/) { return 0; }
                    403:     $resurl=~s/\/$//;
                    404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       406:     return 1;
1.42      matthew   407: }
                    408: 
1.74      www       409: sub studentbrowser_javascript {
1.111     www       410:    unless (
1.258     albertel  411:             (($env{'request.course.id'}) && 
1.302     albertel  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    414: 					  '/'.$env{'request.course.sec'})
                    415: 	      ))
1.258     albertel  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       417:           ) { return ''; }  
1.74      www       418:    return (<<'ENDSTDBRW');
1.776     bisitz    419: <script type="text/javascript" language="Javascript">
1.824     bisitz    420: // <![CDATA[
1.74      www       421:     var stdeditbrowser;
1.999     www       422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       423:         var url = '/adm/pickstudent?';
                    424:         var filter;
1.558     albertel  425: 	if (!ignorefilter) {
                    426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    427: 	}
1.74      www       428:         if (filter != null) {
                    429:            if (filter != '') {
                    430:                url += 'filter='+filter+'&';
                    431: 	   }
                    432:         }
                    433:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       434:                                     '&udomelement='+udom+
                    435:                                     '&clicker='+clicker;
1.111     www       436: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   437:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       438:         var title = 'Student_Browser';
1.74      www       439:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    440:         options += ',width=700,height=600';
                    441:         stdeditbrowser = open(url,title,options,'1');
                    442:         stdeditbrowser.focus();
                    443:     }
1.824     bisitz    444: // ]]>
1.74      www       445: </script>
                    446: ENDSTDBRW
                    447: }
1.42      matthew   448: 
1.1003    www       449: sub resourcebrowser_javascript {
                    450:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       451:    return (<<'ENDRESBRW');
1.1003    www       452: <script type="text/javascript" language="Javascript">
                    453: // <![CDATA[
                    454:     var reseditbrowser;
1.1004    www       455:     function openresbrowser(formname,reslink) {
1.1005    www       456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       457:         var title = 'Resource_Browser';
                    458:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       459:         options += ',width=700,height=500';
1.1004    www       460:         reseditbrowser = open(url,title,options,'1');
                    461:         reseditbrowser.focus();
1.1003    www       462:     }
                    463: // ]]>
                    464: </script>
1.1004    www       465: ENDRESBRW
1.1003    www       466: }
                    467: 
1.74      www       468: sub selectstudent_link {
1.999     www       469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  473:    if ($env{'request.course.id'}) {  
1.302     albertel  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    476: 					'/'.$env{'request.course.sec'})) {
1.111     www       477: 	   return '';
                    478:        }
1.999     www       479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   480:        if ($courseadvonly)  {
                    481:            $callargs .= ",'',1,1";
                    482:        }
                    483:        return '<span class="LC_nobreak">'.
                    484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    485:               &mt('Select User').'</a></span>';
1.74      www       486:    }
1.258     albertel  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       488:        $callargs .= ",'',1"; 
1.793     raeburn   489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.111     www       492:    }
                    493:    return '';
1.91      www       494: }
                    495: 
1.1004    www       496: sub selectresource_link {
                    497:    my ($form,$reslink,$arg)=@_;
                    498:    
                    499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    501:    unless ($env{'request.course.id'}) { return $arg; }
                    502:    return '<span class="LC_nobreak">'.
                    503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    504:               $arg.'</a></span>';
                    505: }
                    506: 
                    507: 
                    508: 
1.653     raeburn   509: sub authorbrowser_javascript {
                    510:     return <<"ENDAUTHORBRW";
1.776     bisitz    511: <script type="text/javascript" language="JavaScript">
1.824     bisitz    512: // <![CDATA[
1.653     raeburn   513: var stdeditbrowser;
                    514: 
                    515: function openauthorbrowser(formname,udom) {
                    516:     var url = '/adm/pickauthor?';
                    517:     url += 'form='+formname+'&roledom='+udom;
                    518:     var title = 'Author_Browser';
                    519:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    520:     options += ',width=700,height=600';
                    521:     stdeditbrowser = open(url,title,options,'1');
                    522:     stdeditbrowser.focus();
                    523: }
                    524: 
1.824     bisitz    525: // ]]>
1.653     raeburn   526: </script>
                    527: ENDAUTHORBRW
                    528: }
                    529: 
1.91      www       530: sub coursebrowser_javascript {
1.1075.2.31  raeburn   531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    532:         $credits_element) = @_;
1.932     raeburn   533:     my $wintitle = 'Course_Browser';
1.931     raeburn   534:     if ($crstype eq 'Community') {
1.932     raeburn   535:         $wintitle = 'Community_Browser';
1.909     raeburn   536:     }
1.876     raeburn   537:     my $id_functions = &javascript_index_functions();
                    538:     my $output = '
1.776     bisitz    539: <script type="text/javascript" language="JavaScript">
1.824     bisitz    540: // <![CDATA[
1.468     raeburn   541:     var stdeditbrowser;'."\n";
1.876     raeburn   542: 
                    543:     $output .= <<"ENDSTDBRW";
1.909     raeburn   544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       545:         var url = '/adm/pickcourse?';
1.895     raeburn   546:         var formid = getFormIdByName(formname);
1.876     raeburn   547:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  548:         if (domainfilter != null) {
                    549:            if (domainfilter != '') {
                    550:                url += 'domainfilter='+domainfilter+'&';
                    551: 	   }
                    552:         }
1.91      www       553:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  554: 	                            '&cdomelement='+udom+
                    555:                                     '&cnameelement='+desc;
1.468     raeburn   556:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   557:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   558:                 url += '&roleelement='+extra_element;
                    559:                 if (domainfilter == null || domainfilter == '') {
                    560:                     url += '&domainfilter='+extra_element;
                    561:                 }
1.234     raeburn   562:             }
1.468     raeburn   563:             else {
                    564:                 if (formname == 'portform') {
                    565:                     url += '&setroles='+extra_element;
1.800     raeburn   566:                 } else {
                    567:                     if (formname == 'rules') {
                    568:                         url += '&fixeddom='+extra_element; 
                    569:                     }
1.468     raeburn   570:                 }
                    571:             }     
1.230     raeburn   572:         }
1.909     raeburn   573:         if (type != null && type != '') {
                    574:             url += '&type='+type;
                    575:         }
                    576:         if (type_elem != null && type_elem != '') {
                    577:             url += '&typeelement='+type_elem;
                    578:         }
1.872     raeburn   579:         if (formname == 'ccrs') {
                    580:             var ownername = document.forms[formid].ccuname.value;
                    581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    582:             url += '&cloner='+ownername+':'+ownerdom;
                    583:         }
1.293     raeburn   584:         if (multflag !=null && multflag != '') {
                    585:             url += '&multiple='+multflag;
                    586:         }
1.909     raeburn   587:         var title = '$wintitle';
1.91      www       588:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    589:         options += ',width=700,height=600';
                    590:         stdeditbrowser = open(url,title,options,'1');
                    591:         stdeditbrowser.focus();
                    592:     }
1.876     raeburn   593: $id_functions
                    594: ENDSTDBRW
1.1075.2.31  raeburn   595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    597:                                       $credits_element);
1.876     raeburn   598:     }
                    599:     $output .= '
                    600: // ]]>
                    601: </script>';
                    602:     return $output;
                    603: }
                    604: 
                    605: sub javascript_index_functions {
                    606:     return <<"ENDJS";
                    607: 
                    608: function getFormIdByName(formname) {
                    609:     for (var i=0;i<document.forms.length;i++) {
                    610:         if (document.forms[i].name == formname) {
                    611:             return i;
                    612:         }
                    613:     }
                    614:     return -1;
                    615: }
                    616: 
                    617: function getIndexByName(formid,item) {
                    618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    619:         if (document.forms[formid].elements[i].name == item) {
                    620:             return i;
                    621:         }
                    622:     }
                    623:     return -1;
                    624: }
1.468     raeburn   625: 
1.876     raeburn   626: function getDomainFromSelectbox(formname,udom) {
                    627:     var userdom;
                    628:     var formid = getFormIdByName(formname);
                    629:     if (formid > -1) {
                    630:         var domid = getIndexByName(formid,udom);
                    631:         if (domid > -1) {
                    632:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    634:             }
                    635:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    636:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   637:             }
                    638:         }
                    639:     }
1.876     raeburn   640:     return userdom;
                    641: }
                    642: 
                    643: ENDJS
1.468     raeburn   644: 
1.876     raeburn   645: }
                    646: 
1.1017    raeburn   647: sub javascript_array_indexof {
1.1018    raeburn   648:     return <<ENDJS;
1.1017    raeburn   649: <script type="text/javascript" language="JavaScript">
                    650: // <![CDATA[
                    651: 
                    652: if (!Array.prototype.indexOf) {
                    653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    654:         "use strict";
                    655:         if (this === void 0 || this === null) {
                    656:             throw new TypeError();
                    657:         }
                    658:         var t = Object(this);
                    659:         var len = t.length >>> 0;
                    660:         if (len === 0) {
                    661:             return -1;
                    662:         }
                    663:         var n = 0;
                    664:         if (arguments.length > 0) {
                    665:             n = Number(arguments[1]);
                    666:             if (n !== n) { // shortcut for verifying if it's NaN
                    667:                 n = 0;
                    668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    670:             }
                    671:         }
                    672:         if (n >= len) {
                    673:             return -1;
                    674:         }
                    675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    676:         for (; k < len; k++) {
                    677:             if (k in t && t[k] === searchElement) {
                    678:                 return k;
                    679:             }
                    680:         }
                    681:         return -1;
                    682:     }
                    683: }
                    684: 
                    685: // ]]>
                    686: </script>
                    687: 
                    688: ENDJS
                    689: 
                    690: }
                    691: 
1.876     raeburn   692: sub userbrowser_javascript {
                    693:     my $id_functions = &javascript_index_functions();
                    694:     return <<"ENDUSERBRW";
                    695: 
1.888     raeburn   696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   697:     var url = '/adm/pickuser?';
                    698:     var userdom = getDomainFromSelectbox(formname,udom);
                    699:     if (userdom != null) {
                    700:        if (userdom != '') {
                    701:            url += 'srchdom='+userdom+'&';
                    702:        }
                    703:     }
                    704:     url += 'form=' + formname + '&unameelement='+uname+
                    705:                                 '&udomelement='+udom+
                    706:                                 '&ulastelement='+ulast+
                    707:                                 '&ufirstelement='+ufirst+
                    708:                                 '&uemailelement='+uemail+
1.881     raeburn   709:                                 '&hideudomelement='+hideudom+
                    710:                                 '&coursedom='+crsdom;
1.888     raeburn   711:     if ((caller != null) && (caller != undefined)) {
                    712:         url += '&caller='+caller;
                    713:     }
1.876     raeburn   714:     var title = 'User_Browser';
                    715:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    716:     options += ',width=700,height=600';
                    717:     var stdeditbrowser = open(url,title,options,'1');
                    718:     stdeditbrowser.focus();
                    719: }
                    720: 
1.888     raeburn   721: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   722:     var formid = getFormIdByName(formname);
                    723:     if (formid > -1) {
1.888     raeburn   724:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   725:         var domid = getIndexByName(formid,udom);
                    726:         var hidedomid = getIndexByName(formid,origdom);
                    727:         if (hidedomid > -1) {
                    728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   729:             var unameval = document.forms[formid].elements[unameid].value;
                    730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    731:                 if (domid > -1) {
                    732:                     var slct = document.forms[formid].elements[domid];
                    733:                     if (slct.type == 'select-one') {
                    734:                         var i;
                    735:                         for (i=0;i<slct.length;i++) {
                    736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    737:                         }
                    738:                     }
                    739:                     if (slct.type == 'hidden') {
                    740:                         slct.value = fixeddom;
1.876     raeburn   741:                     }
                    742:                 }
1.468     raeburn   743:             }
                    744:         }
                    745:     }
1.876     raeburn   746:     return;
                    747: }
                    748: 
                    749: $id_functions
                    750: ENDUSERBRW
1.468     raeburn   751: }
                    752: 
                    753: sub setsec_javascript {
1.1075.2.31  raeburn   754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    756:         $communityrolestr);
                    757:     if ($role_element ne '') {
                    758:         my @allroles = ('st','ta','ep','in','ad');
                    759:         foreach my $crstype ('Course','Community') {
                    760:             if ($crstype eq 'Community') {
                    761:                 foreach my $role (@allroles) {
                    762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    763:                 }
                    764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    765:             } else {
                    766:                 foreach my $role (@allroles) {
                    767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    768:                 }
                    769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    770:             }
                    771:         }
                    772:         $rolestr = '"'.join('","',@allroles).'"';
                    773:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    775:     }
1.468     raeburn   776:     my $setsections = qq|
                    777: function setSect(sectionlist) {
1.629     raeburn   778:     var sectionsArray = new Array();
                    779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    780:         sectionsArray = sectionlist.split(",");
                    781:     }
1.468     raeburn   782:     var numSections = sectionsArray.length;
                    783:     document.$formname.$sec_element.length = 0;
                    784:     if (numSections == 0) {
                    785:         document.$formname.$sec_element.multiple=false;
                    786:         document.$formname.$sec_element.size=1;
                    787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    788:     } else {
                    789:         if (numSections == 1) {
                    790:             document.$formname.$sec_element.multiple=false;
                    791:             document.$formname.$sec_element.size=1;
                    792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    795:         } else {
                    796:             for (var i=0; i<numSections; i++) {
                    797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    798:             }
                    799:             document.$formname.$sec_element.multiple=true
                    800:             if (numSections < 3) {
                    801:                 document.$formname.$sec_element.size=numSections;
                    802:             } else {
                    803:                 document.$formname.$sec_element.size=3;
                    804:             }
                    805:             document.$formname.$sec_element.options[0].selected = false
                    806:         }
                    807:     }
1.91      www       808: }
1.905     raeburn   809: 
                    810: function setRole(crstype) {
1.468     raeburn   811: |;
1.905     raeburn   812:     if ($role_element eq '') {
                    813:         $setsections .= '    return;
                    814: }
                    815: ';
                    816:     } else {
                    817:         $setsections .= qq|
                    818:     var elementLength = document.$formname.$role_element.length;
                    819:     var allroles = Array($rolestr);
                    820:     var courserolenames = Array($courserolestr);
                    821:     var communityrolenames = Array($communityrolestr);
                    822:     if (elementLength != undefined) {
                    823:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    824:             if (crstype == 'Course') {
                    825:                 return;
                    826:             } else {
                    827:                 allroles[5] = 'co';
                    828:                 for (var i=0; i<6; i++) {
                    829:                     document.$formname.$role_element.options[i].value = allroles[i];
                    830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    831:                 }
                    832:             }
                    833:         } else {
                    834:             if (crstype == 'Community') {
                    835:                 return;
                    836:             } else {
                    837:                 allroles[5] = 'cc';
                    838:                 for (var i=0; i<6; i++) {
                    839:                     document.$formname.$role_element.options[i].value = allroles[i];
                    840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    841:                 }
                    842:             }
                    843:         }
                    844:     }
                    845:     return;
                    846: }
                    847: |;
                    848:     }
1.1075.2.31  raeburn   849:     if ($credits_element) {
                    850:         $setsections .= qq|
                    851: function setCredits(defaultcredits) {
                    852:     document.$formname.$credits_element.value = defaultcredits;
                    853:     return;
                    854: }
                    855: |;
                    856:     }
1.468     raeburn   857:     return $setsections;
                    858: }
                    859: 
1.91      www       860: sub selectcourse_link {
1.909     raeburn   861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    862:        $typeelement) = @_;
                    863:    my $type = $selecttype;
1.871     raeburn   864:    my $linktext = &mt('Select Course');
                    865:    if ($selecttype eq 'Community') {
1.909     raeburn   866:        $linktext = &mt('Select Community');
1.906     raeburn   867:    } elsif ($selecttype eq 'Course/Community') {
                    868:        $linktext = &mt('Select Course/Community');
1.909     raeburn   869:        $type = '';
1.1019    raeburn   870:    } elsif ($selecttype eq 'Select') {
                    871:        $linktext = &mt('Select');
                    872:        $type = '';
1.871     raeburn   873:    }
1.787     bisitz    874:    return '<span class="LC_nobreak">'
                    875:          ."<a href='"
                    876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   879:          ."'>".$linktext.'</a>'
1.787     bisitz    880:          .'</span>';
1.74      www       881: }
1.42      matthew   882: 
1.653     raeburn   883: sub selectauthor_link {
                    884:    my ($form,$udom)=@_;
                    885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    886:           &mt('Select Author').'</a>';
                    887: }
                    888: 
1.876     raeburn   889: sub selectuser_link {
1.881     raeburn   890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   891:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   894:            ');">'.$linktext.'</a>';
1.876     raeburn   895: }
                    896: 
1.273     raeburn   897: sub check_uncheck_jscript {
                    898:     my $jscript = <<"ENDSCRT";
                    899: function checkAll(field) {
                    900:     if (field.length > 0) {
                    901:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   902:             if (!field[i].disabled) {
                    903:                 field[i].checked = true;
                    904:             }
1.273     raeburn   905:         }
                    906:     } else {
1.1075.2.14  raeburn   907:         if (!field.disabled) {
                    908:             field.checked = true;
                    909:         }
1.273     raeburn   910:     }
                    911: }
                    912:  
                    913: function uncheckAll(field) {
                    914:     if (field.length > 0) {
                    915:         for (i = 0; i < field.length; i++) {
                    916:             field[i].checked = false ;
1.543     albertel  917:         }
                    918:     } else {
1.273     raeburn   919:         field.checked = false ;
                    920:     }
                    921: }
                    922: ENDSCRT
                    923:     return $jscript;
                    924: }
                    925: 
1.656     www       926: sub select_timezone {
1.659     raeburn   927:    my ($name,$selected,$onchange,$includeempty)=@_;
                    928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    929:    if ($includeempty) {
                    930:        $output .= '<option value=""';
                    931:        if (($selected eq '') || ($selected eq 'local')) {
                    932:            $output .= ' selected="selected" ';
                    933:        }
                    934:        $output .= '> </option>';
                    935:    }
1.657     raeburn   936:    my @timezones = DateTime::TimeZone->all_names;
                    937:    foreach my $tzone (@timezones) {
                    938:        $output.= '<option value="'.$tzone.'"';
                    939:        if ($tzone eq $selected) {
                    940:            $output.=' selected="selected"';
                    941:        }
                    942:        $output.=">$tzone</option>\n";
1.656     www       943:    }
                    944:    $output.="</select>";
                    945:    return $output;
                    946: }
1.273     raeburn   947: 
1.687     raeburn   948: sub select_datelocale {
                    949:     my ($name,$selected,$onchange,$includeempty)=@_;
                    950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    951:     if ($includeempty) {
                    952:         $output .= '<option value=""';
                    953:         if ($selected eq '') {
                    954:             $output .= ' selected="selected" ';
                    955:         }
                    956:         $output .= '> </option>';
                    957:     }
                    958:     my (@possibles,%locale_names);
                    959:     my @locales = DateTime::Locale::Catalog::Locales;
                    960:     foreach my $locale (@locales) {
                    961:         if (ref($locale) eq 'HASH') {
                    962:             my $id = $locale->{'id'};
                    963:             if ($id ne '') {
                    964:                 my $en_terr = $locale->{'en_territory'};
                    965:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   966:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   967:                 if (grep(/^en$/,@languages) || !@languages) {
                    968:                     if ($en_terr ne '') {
                    969:                         $locale_names{$id} = '('.$en_terr.')';
                    970:                     } elsif ($native_terr ne '') {
                    971:                         $locale_names{$id} = $native_terr;
                    972:                     }
                    973:                 } else {
                    974:                     if ($native_terr ne '') {
                    975:                         $locale_names{$id} = $native_terr.' ';
                    976:                     } elsif ($en_terr ne '') {
                    977:                         $locale_names{$id} = '('.$en_terr.')';
                    978:                     }
                    979:                 }
                    980:                 push (@possibles,$id);
                    981:             }
                    982:         }
                    983:     }
                    984:     foreach my $item (sort(@possibles)) {
                    985:         $output.= '<option value="'.$item.'"';
                    986:         if ($item eq $selected) {
                    987:             $output.=' selected="selected"';
                    988:         }
                    989:         $output.=">$item";
                    990:         if ($locale_names{$item} ne '') {
                    991:             $output.="  $locale_names{$item}</option>\n";
                    992:         }
                    993:         $output.="</option>\n";
                    994:     }
                    995:     $output.="</select>";
                    996:     return $output;
                    997: }
                    998: 
1.792     raeburn   999: sub select_language {
                   1000:     my ($name,$selected,$includeempty) = @_;
                   1001:     my %langchoices;
                   1002:     if ($includeempty) {
1.1075.2.32  raeburn  1003:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1004:     }
                   1005:     foreach my $id (&languageids()) {
                   1006:         my $code = &supportedlanguagecode($id);
                   1007:         if ($code) {
                   1008:             $langchoices{$code} = &plainlanguagedescription($id);
                   1009:         }
                   1010:     }
1.1075.2.32  raeburn  1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1012:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1013: }
                   1014: 
1.42      matthew  1015: =pod
1.36      matthew  1016: 
1.648     raeburn  1017: =item * &linked_select_forms(...)
1.36      matthew  1018: 
                   1019: linked_select_forms returns a string containing a <script></script> block
                   1020: and html for two <select> menus.  The select menus will be linked in that
                   1021: changing the value of the first menu will result in new values being placed
                   1022: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1023: order unless a defined order is provided.
1.36      matthew  1024: 
                   1025: linked_select_forms takes the following ordered inputs:
                   1026: 
                   1027: =over 4
                   1028: 
1.112     bowersj2 1029: =item * $formname, the name of the <form> tag
1.36      matthew  1030: 
1.112     bowersj2 1031: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1032: 
1.112     bowersj2 1033: =item * $firstdefault, the default value for the first menu
1.36      matthew  1034: 
1.112     bowersj2 1035: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1036: 
1.112     bowersj2 1037: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1038: 
1.112     bowersj2 1039: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1040: 
1.609     raeburn  1041: =item * $menuorder, the order of values in the first menu
                   1042: 
1.1075.2.31  raeburn  1043: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1044:         event for the first <select> tag
                   1045: 
                   1046: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1047:         event for the second <select> tag
                   1048: 
1.41      ng       1049: =back 
                   1050: 
1.36      matthew  1051: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1053: values for the first select menu.  The text that coincides with the 
1.41      ng       1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1055: and text for the second menu are given in the hash pointed to by 
                   1056: $menu{$choice1}->{'select2'}.  
                   1057: 
1.112     bowersj2 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1059:                        default => "B3",
                   1060:                        select2 => { 
                   1061:                            B1 => "Choice B1",
                   1062:                            B2 => "Choice B2",
                   1063:                            B3 => "Choice B3",
                   1064:                            B4 => "Choice B4"
1.609     raeburn  1065:                            },
                   1066:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1067:                    },
                   1068:                A2 => { text =>"Choice A2" ,
                   1069:                        default => "C2",
                   1070:                        select2 => { 
                   1071:                            C1 => "Choice C1",
                   1072:                            C2 => "Choice C2",
                   1073:                            C3 => "Choice C3"
1.609     raeburn  1074:                            },
                   1075:                        order => ['C2','C1','C3'],
1.112     bowersj2 1076:                    },
                   1077:                A3 => { text =>"Choice A3" ,
                   1078:                        default => "D6",
                   1079:                        select2 => { 
                   1080:                            D1 => "Choice D1",
                   1081:                            D2 => "Choice D2",
                   1082:                            D3 => "Choice D3",
                   1083:                            D4 => "Choice D4",
                   1084:                            D5 => "Choice D5",
                   1085:                            D6 => "Choice D6",
                   1086:                            D7 => "Choice D7"
1.609     raeburn  1087:                            },
                   1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1089:                    }
                   1090:                );
1.36      matthew  1091: 
                   1092: =cut
                   1093: 
                   1094: sub linked_select_forms {
                   1095:     my ($formname,
                   1096:         $middletext,
                   1097:         $firstdefault,
                   1098:         $firstselectname,
                   1099:         $secondselectname, 
1.609     raeburn  1100:         $hashref,
                   1101:         $menuorder,
1.1075.2.31  raeburn  1102:         $onchangefirst,
                   1103:         $onchangesecond
1.36      matthew  1104:         ) = @_;
                   1105:     my $second = "document.$formname.$secondselectname";
                   1106:     my $first = "document.$formname.$firstselectname";
                   1107:     # output the javascript to do the changing
                   1108:     my $result = '';
1.776     bisitz   1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1110:     $result.="// <![CDATA[\n";
1.36      matthew  1111:     $result.="var select2data = new Object();\n";
                   1112:     $" = '","';
                   1113:     my $debug = '';
                   1114:     foreach my $s1 (sort(keys(%$hashref))) {
                   1115:         $result.="select2data.d_$s1 = new Object();\n";        
                   1116:         $result.="select2data.d_$s1.def = new String('".
                   1117:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1118:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1121:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1122:         }
1.36      matthew  1123:         $result.="\"@s2values\");\n";
                   1124:         $result.="select2data.d_$s1.texts = new Array(";        
                   1125:         my @s2texts;
                   1126:         foreach my $value (@s2values) {
                   1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1128:         }
                   1129:         $result.="\"@s2texts\");\n";
                   1130:     }
                   1131:     $"=' ';
                   1132:     $result.= <<"END";
                   1133: 
                   1134: function select1_changed() {
                   1135:     // Determine new choice
                   1136:     var newvalue = "d_" + $first.value;
                   1137:     // update select2
                   1138:     var values     = select2data[newvalue].values;
                   1139:     var texts      = select2data[newvalue].texts;
                   1140:     var select2def = select2data[newvalue].def;
                   1141:     var i;
                   1142:     // out with the old
                   1143:     for (i = 0; i < $second.options.length; i++) {
                   1144:         $second.options[i] = null;
                   1145:     }
                   1146:     // in with the nuclear
                   1147:     for (i=0;i<values.length; i++) {
                   1148:         $second.options[i] = new Option(values[i]);
1.143     matthew  1149:         $second.options[i].value = values[i];
1.36      matthew  1150:         $second.options[i].text = texts[i];
                   1151:         if (values[i] == select2def) {
                   1152:             $second.options[i].selected = true;
                   1153:         }
                   1154:     }
                   1155: }
1.824     bisitz   1156: // ]]>
1.36      matthew  1157: </script>
                   1158: END
                   1159:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1161:     my @order = sort(keys(%{$hashref}));
                   1162:     if (ref($menuorder) eq 'ARRAY') {
                   1163:         @order = @{$menuorder};
                   1164:     }
                   1165:     foreach my $value (@order) {
1.36      matthew  1166:         $result.="    <option value=\"$value\" ";
1.253     albertel 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1169:     }
                   1170:     $result .= "</select>\n";
                   1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1172:     $result .= $middletext;
1.1075.2.31  raeburn  1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1174:     if ($onchangesecond) {
                   1175:         $result .= ' onchange="'.$onchangesecond.'"';
                   1176:     }
                   1177:     $result .= ">\n";
1.36      matthew  1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1179:     
                   1180:     my @secondorder = sort(keys(%select2));
                   1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1183:     }
                   1184:     foreach my $value (@secondorder) {
1.36      matthew  1185:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1187:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1188:     }
                   1189:     $result .= "</select>\n";
                   1190:     #    return $debug;
                   1191:     return $result;
                   1192: }   #  end of sub linked_select_forms {
                   1193: 
1.45      matthew  1194: =pod
1.44      bowersj2 1195: 
1.973     raeburn  1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1197: 
1.112     bowersj2 1198: Returns a string corresponding to an HTML link to the given help
                   1199: $topic, where $topic corresponds to the name of a .tex file in
                   1200: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1201: spaces. 
                   1202: 
                   1203: $text will optionally be linked to the same topic, allowing you to
                   1204: link text in addition to the graphic. If you do not want to link
                   1205: text, but wish to specify one of the later parameters, pass an
                   1206: empty string. 
                   1207: 
                   1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1209: the link will not open a new window. If false, the link will open
                   1210: a new window using Javascript. (Default is false.) 
                   1211: 
                   1212: $width and $height are optional numerical parameters that will
                   1213: override the width and height of the popped up window, which may
1.973     raeburn  1214: be useful for certain help topics with big pictures included.
                   1215: 
                   1216: $imgid is the id of the img tag used for the help icon. This may be
                   1217: used in a javascript call to switch the image src.  See 
                   1218: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1219: 
                   1220: =cut
                   1221: 
                   1222: sub help_open_topic {
1.973     raeburn  1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1224:     $text = "" if (not defined $text);
1.44      bowersj2 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1226:     $width = 500 if (not defined $width);
1.44      bowersj2 1227:     $height = 400 if (not defined $height);
                   1228:     my $filename = $topic;
                   1229:     $filename =~ s/ /_/g;
                   1230: 
1.48      bowersj2 1231:     my $template = "";
                   1232:     my $link;
1.572     banghart 1233:     
1.159     www      1234:     $topic=~s/\W/\_/g;
1.44      bowersj2 1235: 
1.572     banghart 1236:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1237:         if ($env{'browser.mobile'}) {
                   1238: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1239:         } else {
                   1240:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1241:         }
1.1037    www      1242:     } elsif ($stayOnPage eq 'popup') {
                   1243:         $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 1244:     } else {
1.48      bowersj2 1245: 	$link = "/adm/help/${filename}.hlp";
                   1246:     }
                   1247: 
                   1248:     # Add the text
1.755     neumanie 1249:     if ($text ne "") {	
1.763     bisitz   1250: 	$template.='<span class="LC_help_open_topic">'
                   1251:                   .'<a target="_top" href="'.$link.'">'
                   1252:                   .$text.'</a>';
1.48      bowersj2 1253:     }
                   1254: 
1.763     bisitz   1255:     # (Always) Add the graphic
1.179     matthew  1256:     my $title = &mt('Online Help');
1.667     raeburn  1257:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1258:     if ($imgid ne '') {
                   1259:         $imgid = ' id="'.$imgid.'"';
                   1260:     }
1.763     bisitz   1261:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1262:               .'<img src="'.$helpicon.'" border="0"'
                   1263:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1264:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1265:               .' /></a>';
                   1266:     if ($text ne "") {	
                   1267:         $template.='</span>';
                   1268:     }
1.44      bowersj2 1269:     return $template;
                   1270: 
1.106     bowersj2 1271: }
                   1272: 
                   1273: # This is a quicky function for Latex cheatsheet editing, since it 
                   1274: # appears in at least four places
                   1275: sub helpLatexCheatsheet {
1.1037    www      1276:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1277:     my $out;
1.106     bowersj2 1278:     my $addOther = '';
1.732     raeburn  1279:     if ($topic) {
1.1037    www      1280: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1281:     }
                   1282:     $out = '<span>' # Start cheatsheet
                   1283: 	  .$addOther
                   1284:           .'<span>'
1.1037    www      1285: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1286: 	  .'</span> <span>'
1.1037    www      1287: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1288: 	  .'</span>';
1.732     raeburn  1289:     unless ($not_author) {
1.763     bisitz   1290:         $out .= ' <span>'
1.1037    www      1291: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1292: 	       .'</span>';
1.732     raeburn  1293:     }
1.763     bisitz   1294:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1295:     return $out;
1.172     www      1296: }
                   1297: 
1.430     albertel 1298: sub general_help {
                   1299:     my $helptopic='Student_Intro';
                   1300:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1301: 	$helptopic='Authoring_Intro';
1.907     raeburn  1302:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1303: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1304:     } elsif ($env{'request.role'}=~/^dc/) {
                   1305:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1306:     }
                   1307:     return $helptopic;
                   1308: }
                   1309: 
                   1310: sub update_help_link {
                   1311:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1312:     my $origurl = $ENV{'REQUEST_URI'};
                   1313:     $origurl=~s|^/~|/priv/|;
                   1314:     my $timestamp = time;
                   1315:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1316:         $$datum = &escape($$datum);
                   1317:     }
                   1318: 
                   1319:     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";
                   1320:     my $output .= <<"ENDOUTPUT";
                   1321: <script type="text/javascript">
1.824     bisitz   1322: // <![CDATA[
1.430     albertel 1323: banner_link = '$banner_link';
1.824     bisitz   1324: // ]]>
1.430     albertel 1325: </script>
                   1326: ENDOUTPUT
                   1327:     return $output;
                   1328: }
                   1329: 
                   1330: # now just updates the help link and generates a blue icon
1.193     raeburn  1331: sub help_open_menu {
1.430     albertel 1332:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1333: 	= @_;    
1.949     droeschl 1334:     $stayOnPage = 1;
1.430     albertel 1335:     my $output;
                   1336:     if ($component_help) {
                   1337: 	if (!$text) {
                   1338: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1339: 				       $width,$height);
                   1340: 	} else {
                   1341: 	    my $help_text;
                   1342: 	    $help_text=&unescape($topic);
                   1343: 	    $output='<table><tr><td>'.
                   1344: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1345: 				 $width,$height).'</td></tr></table>';
                   1346: 	}
                   1347:     }
                   1348:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1349:     return $output.$banner_link;
                   1350: }
                   1351: 
                   1352: sub top_nav_help {
                   1353:     my ($text) = @_;
1.436     albertel 1354:     $text = &mt($text);
1.1075.2.60! raeburn  1355:     my $stay_on_page;
        !          1356:     unless ($env{'environment.remote'} eq 'on') {
        !          1357:         $stay_on_page = 1;
        !          1358:     }
1.572     banghart 1359:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1360: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1361:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1362: 
1.201     raeburn  1363:     my $title = &mt('Get help');
1.436     albertel 1364: 
                   1365:     return <<"END";
                   1366: $banner_link
1.1075.2.56  raeburn  1367: <a href="$link" title="$title">$text</a>
1.436     albertel 1368: END
                   1369: }
                   1370: 
                   1371: sub help_menu_js {
1.1075.2.52  raeburn  1372:     my ($httphost) = @_;
1.949     droeschl 1373:     my $stayOnPage = 1;
1.436     albertel 1374:     my $width = 620;
                   1375:     my $height = 600;
1.430     albertel 1376:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1377:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1378:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1379:     my $start_page =
                   1380:         &Apache::loncommon::start_page('Help Menu', undef,
                   1381: 				       {'frameset'    => 1,
                   1382: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1383:                                         'use_absolute' => $httphost, 
1.331     albertel 1384: 					'add_entries' => {
                   1385: 					    'border' => '0',
1.579     raeburn  1386: 					    'rows'   => "110,*",},});
1.331     albertel 1387:     my $end_page =
                   1388:         &Apache::loncommon::end_page({'frameset' => 1,
                   1389: 				      'js_ready' => 1,});
                   1390: 
1.436     albertel 1391:     my $template .= <<"ENDTEMPLATE";
                   1392: <script type="text/javascript">
1.877     bisitz   1393: // <![CDATA[
1.253     albertel 1394: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1395: var banner_link = '';
1.243     raeburn  1396: function helpMenu(target) {
                   1397:     var caller = this;
                   1398:     if (target == 'open') {
                   1399:         var newWindow = null;
                   1400:         try {
1.262     albertel 1401:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1402:         }
                   1403:         catch(error) {
                   1404:             writeHelp(caller);
                   1405:             return;
                   1406:         }
                   1407:         if (newWindow) {
                   1408:             caller = newWindow;
                   1409:         }
1.193     raeburn  1410:     }
1.243     raeburn  1411:     writeHelp(caller);
                   1412:     return;
                   1413: }
                   1414: function writeHelp(caller) {
1.1072    raeburn  1415:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1.243     raeburn  1416:     caller.document.close()
                   1417:     caller.focus()
1.193     raeburn  1418: }
1.877     bisitz   1419: // END LON-CAPA Internal -->
1.253     albertel 1420: // ]]>
1.436     albertel 1421: </script>
1.193     raeburn  1422: ENDTEMPLATE
                   1423:     return $template;
                   1424: }
                   1425: 
1.172     www      1426: sub help_open_bug {
                   1427:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1428:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1429:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1430:     $text = "" if (not defined $text);
                   1431: 	$stayOnPage=1;
1.184     albertel 1432:     $width = 600 if (not defined $width);
                   1433:     $height = 600 if (not defined $height);
1.172     www      1434: 
                   1435:     $topic=~s/\W+/\+/g;
                   1436:     my $link='';
                   1437:     my $template='';
1.379     albertel 1438:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1439: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1440:     if (!$stayOnPage)
                   1441:     {
                   1442: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1443:     }
                   1444:     else
                   1445:     {
                   1446: 	$link = $url;
                   1447:     }
                   1448:     # Add the text
                   1449:     if ($text ne "")
                   1450:     {
                   1451: 	$template .= 
                   1452:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1453:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1454:     }
                   1455: 
                   1456:     # Add the graphic
1.179     matthew  1457:     my $title = &mt('Report a Bug');
1.215     albertel 1458:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1459:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1460:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1461: ENDTEMPLATE
                   1462:     if ($text ne '') { $template.='</td></tr></table>' };
                   1463:     return $template;
                   1464: 
                   1465: }
                   1466: 
                   1467: sub help_open_faq {
                   1468:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1469:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1470:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1471:     $text = "" if (not defined $text);
                   1472: 	$stayOnPage=1;
                   1473:     $width = 350 if (not defined $width);
                   1474:     $height = 400 if (not defined $height);
                   1475: 
                   1476:     $topic=~s/\W+/\+/g;
                   1477:     my $link='';
                   1478:     my $template='';
                   1479:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1480:     if (!$stayOnPage)
                   1481:     {
                   1482: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1483:     }
                   1484:     else
                   1485:     {
                   1486: 	$link = $url;
                   1487:     }
                   1488: 
                   1489:     # Add the text
                   1490:     if ($text ne "")
                   1491:     {
                   1492: 	$template .= 
1.173     www      1493:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1494:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1495:     }
                   1496: 
                   1497:     # Add the graphic
1.179     matthew  1498:     my $title = &mt('View the FAQ');
1.215     albertel 1499:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1500:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1501:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1502: ENDTEMPLATE
                   1503:     if ($text ne '') { $template.='</td></tr></table>' };
                   1504:     return $template;
                   1505: 
1.44      bowersj2 1506: }
1.37      matthew  1507: 
1.180     matthew  1508: ###############################################################
                   1509: ###############################################################
                   1510: 
1.45      matthew  1511: =pod
                   1512: 
1.648     raeburn  1513: =item * &change_content_javascript():
1.256     matthew  1514: 
                   1515: This and the next function allow you to create small sections of an
                   1516: otherwise static HTML page that you can update on the fly with
                   1517: Javascript, even in Netscape 4.
                   1518: 
                   1519: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1520: must be written to the HTML page once. It will prove the Javascript
                   1521: function "change(name, content)". Calling the change function with the
                   1522: name of the section 
                   1523: you want to update, matching the name passed to C<changable_area>, and
                   1524: the new content you want to put in there, will put the content into
                   1525: that area.
                   1526: 
                   1527: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1528: to contain room for the original contents. You need to "make space"
                   1529: for whatever changes you wish to make, and be B<sure> to check your
                   1530: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1531: it's adequate for updating a one-line status display, but little more.
                   1532: This script will set the space to 100% width, so you only need to
                   1533: worry about height in Netscape 4.
                   1534: 
                   1535: Modern browsers are much less limiting, and if you can commit to the
                   1536: user not using Netscape 4, this feature may be used freely with
                   1537: pretty much any HTML.
                   1538: 
                   1539: =cut
                   1540: 
                   1541: sub change_content_javascript {
                   1542:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1543:     if ($env{'browser.type'} eq 'netscape' &&
                   1544: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1545: 	return (<<NETSCAPE4);
                   1546: 	function change(name, content) {
                   1547: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1548: 	    doc.open();
                   1549: 	    doc.write(content);
                   1550: 	    doc.close();
                   1551: 	}
                   1552: NETSCAPE4
                   1553:     } else {
                   1554: 	# Otherwise, we need to use semi-standards-compliant code
                   1555: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1556: 	# is really scary, and every useful browser supports it
                   1557: 	return (<<DOMBASED);
                   1558: 	function change(name, content) {
                   1559: 	    element = document.getElementById(name);
                   1560: 	    element.innerHTML = content;
                   1561: 	}
                   1562: DOMBASED
                   1563:     }
                   1564: }
                   1565: 
                   1566: =pod
                   1567: 
1.648     raeburn  1568: =item * &changable_area($name,$origContent):
1.256     matthew  1569: 
                   1570: This provides a "changable area" that can be modified on the fly via
                   1571: the Javascript code provided in C<change_content_javascript>. $name is
                   1572: the name you will use to reference the area later; do not repeat the
                   1573: same name on a given HTML page more then once. $origContent is what
                   1574: the area will originally contain, which can be left blank.
                   1575: 
                   1576: =cut
                   1577: 
                   1578: sub changable_area {
                   1579:     my ($name, $origContent) = @_;
                   1580: 
1.258     albertel 1581:     if ($env{'browser.type'} eq 'netscape' &&
                   1582: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1583: 	# If this is netscape 4, we need to use the Layer tag
                   1584: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1585:     } else {
                   1586: 	return "<span id='$name'>$origContent</span>";
                   1587:     }
                   1588: }
                   1589: 
                   1590: =pod
                   1591: 
1.648     raeburn  1592: =item * &viewport_geometry_js 
1.590     raeburn  1593: 
                   1594: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1595: 
                   1596: =cut
                   1597: 
                   1598: 
                   1599: sub viewport_geometry_js { 
                   1600:     return <<"GEOMETRY";
                   1601: var Geometry = {};
                   1602: function init_geometry() {
                   1603:     if (Geometry.init) { return };
                   1604:     Geometry.init=1;
                   1605:     if (window.innerHeight) {
                   1606:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1607:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1608:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1609:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1610:     }
                   1611:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1612:         Geometry.getViewportHeight =
                   1613:             function() { return document.documentElement.clientHeight; };
                   1614:         Geometry.getViewportWidth =
                   1615:             function() { return document.documentElement.clientWidth; };
                   1616: 
                   1617:         Geometry.getHorizontalScroll =
                   1618:             function() { return document.documentElement.scrollLeft; };
                   1619:         Geometry.getVerticalScroll =
                   1620:             function() { return document.documentElement.scrollTop; };
                   1621:     }
                   1622:     else if (document.body.clientHeight) {
                   1623:         Geometry.getViewportHeight =
                   1624:             function() { return document.body.clientHeight; };
                   1625:         Geometry.getViewportWidth =
                   1626:             function() { return document.body.clientWidth; };
                   1627:         Geometry.getHorizontalScroll =
                   1628:             function() { return document.body.scrollLeft; };
                   1629:         Geometry.getVerticalScroll =
                   1630:             function() { return document.body.scrollTop; };
                   1631:     }
                   1632: }
                   1633: 
                   1634: GEOMETRY
                   1635: }
                   1636: 
                   1637: =pod
                   1638: 
1.648     raeburn  1639: =item * &viewport_size_js()
1.590     raeburn  1640: 
                   1641: 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. 
                   1642: 
                   1643: =cut
                   1644: 
                   1645: sub viewport_size_js {
                   1646:     my $geometry = &viewport_geometry_js();
                   1647:     return <<"DIMS";
                   1648: 
                   1649: $geometry
                   1650: 
                   1651: function getViewportDims(width,height) {
                   1652:     init_geometry();
                   1653:     width.value = Geometry.getViewportWidth();
                   1654:     height.value = Geometry.getViewportHeight();
                   1655:     return;
                   1656: }
                   1657: 
                   1658: DIMS
                   1659: }
                   1660: 
                   1661: =pod
                   1662: 
1.648     raeburn  1663: =item * &resize_textarea_js()
1.565     albertel 1664: 
                   1665: emits the needed javascript to resize a textarea to be as big as possible
                   1666: 
                   1667: creates a function resize_textrea that takes two IDs first should be
                   1668: the id of the element to resize, second should be the id of a div that
                   1669: surrounds everything that comes after the textarea, this routine needs
                   1670: to be attached to the <body> for the onload and onresize events.
                   1671: 
1.648     raeburn  1672: =back
1.565     albertel 1673: 
                   1674: =cut
                   1675: 
                   1676: sub resize_textarea_js {
1.590     raeburn  1677:     my $geometry = &viewport_geometry_js();
1.565     albertel 1678:     return <<"RESIZE";
                   1679:     <script type="text/javascript">
1.824     bisitz   1680: // <![CDATA[
1.590     raeburn  1681: $geometry
1.565     albertel 1682: 
1.588     albertel 1683: function getX(element) {
                   1684:     var x = 0;
                   1685:     while (element) {
                   1686: 	x += element.offsetLeft;
                   1687: 	element = element.offsetParent;
                   1688:     }
                   1689:     return x;
                   1690: }
                   1691: function getY(element) {
                   1692:     var y = 0;
                   1693:     while (element) {
                   1694: 	y += element.offsetTop;
                   1695: 	element = element.offsetParent;
                   1696:     }
                   1697:     return y;
                   1698: }
                   1699: 
                   1700: 
1.565     albertel 1701: function resize_textarea(textarea_id,bottom_id) {
                   1702:     init_geometry();
                   1703:     var textarea        = document.getElementById(textarea_id);
                   1704:     //alert(textarea);
                   1705: 
1.588     albertel 1706:     var textarea_top    = getY(textarea);
1.565     albertel 1707:     var textarea_height = textarea.offsetHeight;
                   1708:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1709:     var bottom_top      = getY(bottom);
1.565     albertel 1710:     var bottom_height   = bottom.offsetHeight;
                   1711:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1712:     var fudge           = 23;
1.565     albertel 1713:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1714:     if (new_height < 300) {
                   1715: 	new_height = 300;
                   1716:     }
                   1717:     textarea.style.height=new_height+'px';
                   1718: }
1.824     bisitz   1719: // ]]>
1.565     albertel 1720: </script>
                   1721: RESIZE
                   1722: 
                   1723: }
                   1724: 
                   1725: =pod
                   1726: 
1.256     matthew  1727: =head1 Excel and CSV file utility routines
                   1728: 
                   1729: =cut
                   1730: 
                   1731: ###############################################################
                   1732: ###############################################################
                   1733: 
                   1734: =pod
                   1735: 
1.1075.2.56  raeburn  1736: =over 4
                   1737: 
1.648     raeburn  1738: =item * &csv_translate($text) 
1.37      matthew  1739: 
1.185     www      1740: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1741: format.
                   1742: 
                   1743: =cut
                   1744: 
1.180     matthew  1745: ###############################################################
                   1746: ###############################################################
1.37      matthew  1747: sub csv_translate {
                   1748:     my $text = shift;
                   1749:     $text =~ s/\"/\"\"/g;
1.209     albertel 1750:     $text =~ s/\n/ /g;
1.37      matthew  1751:     return $text;
                   1752: }
1.180     matthew  1753: 
                   1754: ###############################################################
                   1755: ###############################################################
                   1756: 
                   1757: =pod
                   1758: 
1.648     raeburn  1759: =item * &define_excel_formats()
1.180     matthew  1760: 
                   1761: Define some commonly used Excel cell formats.
                   1762: 
                   1763: Currently supported formats:
                   1764: 
                   1765: =over 4
                   1766: 
                   1767: =item header
                   1768: 
                   1769: =item bold
                   1770: 
                   1771: =item h1
                   1772: 
                   1773: =item h2
                   1774: 
                   1775: =item h3
                   1776: 
1.256     matthew  1777: =item h4
                   1778: 
                   1779: =item i
                   1780: 
1.180     matthew  1781: =item date
                   1782: 
                   1783: =back
                   1784: 
                   1785: Inputs: $workbook
                   1786: 
                   1787: Returns: $format, a hash reference.
                   1788: 
1.1057    foxr     1789: 
1.180     matthew  1790: =cut
                   1791: 
                   1792: ###############################################################
                   1793: ###############################################################
                   1794: sub define_excel_formats {
                   1795:     my ($workbook) = @_;
                   1796:     my $format;
                   1797:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1798:                                                 bottom    => 1,
                   1799:                                                 align     => 'center');
                   1800:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1801:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1802:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1803:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1804:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1805:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1806:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1807:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1808:     return $format;
                   1809: }
                   1810: 
                   1811: ###############################################################
                   1812: ###############################################################
1.113     bowersj2 1813: 
                   1814: =pod
                   1815: 
1.648     raeburn  1816: =item * &create_workbook()
1.255     matthew  1817: 
                   1818: Create an Excel worksheet.  If it fails, output message on the
                   1819: request object and return undefs.
                   1820: 
                   1821: Inputs: Apache request object
                   1822: 
                   1823: Returns (undef) on failure, 
                   1824:     Excel worksheet object, scalar with filename, and formats 
                   1825:     from &Apache::loncommon::define_excel_formats on success
                   1826: 
                   1827: =cut
                   1828: 
                   1829: ###############################################################
                   1830: ###############################################################
                   1831: sub create_workbook {
                   1832:     my ($r) = @_;
                   1833:         #
                   1834:     # Create the excel spreadsheet
                   1835:     my $filename = '/prtspool/'.
1.258     albertel 1836:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1837:         time.'_'.rand(1000000000).'.xls';
                   1838:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1839:     if (! defined($workbook)) {
                   1840:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1841:         $r->print(
                   1842:             '<p class="LC_error">'
                   1843:            .&mt('Problems occurred in creating the new Excel file.')
                   1844:            .' '.&mt('This error has been logged.')
                   1845:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1846:            .'</p>'
                   1847:         );
1.255     matthew  1848:         return (undef);
                   1849:     }
                   1850:     #
1.1014    foxr     1851:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1852:     #
                   1853:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1854:     return ($workbook,$filename,$format);
                   1855: }
                   1856: 
                   1857: ###############################################################
                   1858: ###############################################################
                   1859: 
                   1860: =pod
                   1861: 
1.648     raeburn  1862: =item * &create_text_file()
1.113     bowersj2 1863: 
1.542     raeburn  1864: Create a file to write to and eventually make available to the user.
1.256     matthew  1865: If file creation fails, outputs an error message on the request object and 
                   1866: return undefs.
1.113     bowersj2 1867: 
1.256     matthew  1868: Inputs: Apache request object, and file suffix
1.113     bowersj2 1869: 
1.256     matthew  1870: Returns (undef) on failure, 
                   1871:     Filehandle and filename on success.
1.113     bowersj2 1872: 
                   1873: =cut
                   1874: 
1.256     matthew  1875: ###############################################################
                   1876: ###############################################################
                   1877: sub create_text_file {
                   1878:     my ($r,$suffix) = @_;
                   1879:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1880:     my $fh;
                   1881:     my $filename = '/prtspool/'.
1.258     albertel 1882:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1883:         time.'_'.rand(1000000000).'.'.$suffix;
                   1884:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1885:     if (! defined($fh)) {
                   1886:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1887:         $r->print(
                   1888:             '<p class="LC_error">'
                   1889:            .&mt('Problems occurred in creating the output file.')
                   1890:            .' '.&mt('This error has been logged.')
                   1891:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1892:            .'</p>'
                   1893:         );
1.113     bowersj2 1894:     }
1.256     matthew  1895:     return ($fh,$filename)
1.113     bowersj2 1896: }
                   1897: 
                   1898: 
1.256     matthew  1899: =pod 
1.113     bowersj2 1900: 
                   1901: =back
                   1902: 
                   1903: =cut
1.37      matthew  1904: 
                   1905: ###############################################################
1.33      matthew  1906: ##        Home server <option> list generating code          ##
                   1907: ###############################################################
1.35      matthew  1908: 
1.169     www      1909: # ------------------------------------------
                   1910: 
                   1911: sub domain_select {
                   1912:     my ($name,$value,$multiple)=@_;
                   1913:     my %domains=map { 
1.514     albertel 1914: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1915:     } &Apache::lonnet::all_domains();
1.169     www      1916:     if ($multiple) {
                   1917: 	$domains{''}=&mt('Any domain');
1.550     albertel 1918: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1919: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1920:     } else {
1.550     albertel 1921: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1922: 	return &select_form($name,$value,\%domains);
1.169     www      1923:     }
                   1924: }
                   1925: 
1.282     albertel 1926: #-------------------------------------------
                   1927: 
                   1928: =pod
                   1929: 
1.519     raeburn  1930: =head1 Routines for form select boxes
                   1931: 
                   1932: =over 4
                   1933: 
1.648     raeburn  1934: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1935: 
                   1936: Returns a string containing a <select> element int multiple mode
                   1937: 
                   1938: 
                   1939: Args:
                   1940:   $name - name of the <select> element
1.506     raeburn  1941:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1942:   $size - number of rows long the select element is
1.283     albertel 1943:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1944:           (shown text should already have been &mt())
1.506     raeburn  1945:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1946: 
1.282     albertel 1947: =cut
                   1948: 
                   1949: #-------------------------------------------
1.169     www      1950: sub multiple_select_form {
1.284     albertel 1951:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1952:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1953:     my $output='';
1.191     matthew  1954:     if (! defined($size)) {
                   1955:         $size = 4;
1.283     albertel 1956:         if (scalar(keys(%$hash))<4) {
                   1957:             $size = scalar(keys(%$hash));
1.191     matthew  1958:         }
                   1959:     }
1.734     bisitz   1960:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1961:     my @order;
1.506     raeburn  1962:     if (ref($order) eq 'ARRAY')  {
                   1963:         @order = @{$order};
                   1964:     } else {
                   1965:         @order = sort(keys(%$hash));
1.501     banghart 1966:     }
                   1967:     if (exists($$hash{'select_form_order'})) {
                   1968:         @order = @{$$hash{'select_form_order'}};
                   1969:     }
                   1970:         
1.284     albertel 1971:     foreach my $key (@order) {
1.356     albertel 1972:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1973:         $output.='selected="selected" ' if ($selected{$key});
                   1974:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1975:     }
                   1976:     $output.="</select>\n";
                   1977:     return $output;
                   1978: }
                   1979: 
1.88      www      1980: #-------------------------------------------
                   1981: 
                   1982: =pod
                   1983: 
1.970     raeburn  1984: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1985: 
                   1986: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1987: allow a user to select options from a ref to a hash containing:
                   1988: option_name => displayed text. An optional $onchange can include
                   1989: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1990: 
1.88      www      1991: See lonrights.pm for an example invocation and use.
                   1992: 
                   1993: =cut
                   1994: 
                   1995: #-------------------------------------------
                   1996: sub select_form {
1.970     raeburn  1997:     my ($def,$name,$hashref,$onchange) = @_;
                   1998:     return unless (ref($hashref) eq 'HASH');
                   1999:     if ($onchange) {
                   2000:         $onchange = ' onchange="'.$onchange.'"';
                   2001:     }
                   2002:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2003:     my @keys;
1.970     raeburn  2004:     if (exists($hashref->{'select_form_order'})) {
                   2005: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2006:     } else {
1.970     raeburn  2007: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2008:     }
1.356     albertel 2009:     foreach my $key (@keys) {
                   2010:         $selectform.=
                   2011: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2012:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2013:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2014:     }
                   2015:     $selectform.="</select>";
                   2016:     return $selectform;
                   2017: }
                   2018: 
1.475     www      2019: # For display filters
                   2020: 
                   2021: sub display_filter {
1.1074    raeburn  2022:     my ($context) = @_;
1.475     www      2023:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2024:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2025:     my $phraseinput = 'hidden';
                   2026:     my $includeinput = 'hidden';
                   2027:     my ($checked,$includetypestext);
                   2028:     if ($env{'form.displayfilter'} eq 'containing') {
                   2029:         $phraseinput = 'text'; 
                   2030:         if ($context eq 'parmslog') {
                   2031:             $includeinput = 'checkbox';
                   2032:             if ($env{'form.includetypes'}) {
                   2033:                 $checked = ' checked="checked"';
                   2034:             }
                   2035:             $includetypestext = &mt('Include parameter types');
                   2036:         }
                   2037:     } else {
                   2038:         $includetypestext = '&nbsp;';
                   2039:     }
                   2040:     my ($additional,$secondid,$thirdid);
                   2041:     if ($context eq 'parmslog') {
                   2042:         $additional = 
                   2043:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2044:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2045:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2046:             '</label>';
                   2047:         $secondid = 'includetypes';
                   2048:         $thirdid = 'includetypestext';
                   2049:     }
                   2050:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2051:                                                     '$secondid','$thirdid')";
                   2052:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2053: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2054: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2055: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2056:            &mt('Filter: [_1]',
1.477     www      2057: 	   &select_form($env{'form.displayfilter'},
                   2058: 			'displayfilter',
1.970     raeburn  2059: 			{'currentfolder' => 'Current folder/page',
1.477     www      2060: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2061: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2062: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2063:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2064:                          '" />'.$additional;
                   2065: }
                   2066: 
                   2067: sub display_filter_js {
                   2068:     my $includetext = &mt('Include parameter types');
                   2069:     return <<"ENDJS";
                   2070:   
                   2071: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2072:     var firstType = 'hidden';
                   2073:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2074:         firstType = 'text';
                   2075:     }
                   2076:     firstObject = document.getElementById(firstid);
                   2077:     if (typeof(firstObject) == 'object') {
                   2078:         if (firstObject.type != firstType) {
                   2079:             changeInputType(firstObject,firstType);
                   2080:         }
                   2081:     }
                   2082:     if (context == 'parmslog') {
                   2083:         var secondType = 'hidden';
                   2084:         if (firstType == 'text') {
                   2085:             secondType = 'checkbox';
                   2086:         }
                   2087:         secondObject = document.getElementById(secondid);  
                   2088:         if (typeof(secondObject) == 'object') {
                   2089:             if (secondObject.type != secondType) {
                   2090:                 changeInputType(secondObject,secondType);
                   2091:             }
                   2092:         }
                   2093:         var textItem = document.getElementById(thirdid);
                   2094:         var currtext = textItem.innerHTML;
                   2095:         var newtext;
                   2096:         if (firstType == 'text') {
                   2097:             newtext = '$includetext';
                   2098:         } else {
                   2099:             newtext = '&nbsp;';
                   2100:         }
                   2101:         if (currtext != newtext) {
                   2102:             textItem.innerHTML = newtext;
                   2103:         }
                   2104:     }
                   2105:     return;
                   2106: }
                   2107: 
                   2108: function changeInputType(oldObject,newType) {
                   2109:     var newObject = document.createElement('input');
                   2110:     newObject.type = newType;
                   2111:     if (oldObject.size) {
                   2112:         newObject.size = oldObject.size;
                   2113:     }
                   2114:     if (oldObject.value) {
                   2115:         newObject.value = oldObject.value;
                   2116:     }
                   2117:     if (oldObject.name) {
                   2118:         newObject.name = oldObject.name;
                   2119:     }
                   2120:     if (oldObject.id) {
                   2121:         newObject.id = oldObject.id;
                   2122:     }
                   2123:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2124:     return;
                   2125: }
                   2126: 
                   2127: ENDJS
1.475     www      2128: }
                   2129: 
1.167     www      2130: sub gradeleveldescription {
                   2131:     my $gradelevel=shift;
                   2132:     my %gradelevels=(0 => 'Not specified',
                   2133: 		     1 => 'Grade 1',
                   2134: 		     2 => 'Grade 2',
                   2135: 		     3 => 'Grade 3',
                   2136: 		     4 => 'Grade 4',
                   2137: 		     5 => 'Grade 5',
                   2138: 		     6 => 'Grade 6',
                   2139: 		     7 => 'Grade 7',
                   2140: 		     8 => 'Grade 8',
                   2141: 		     9 => 'Grade 9',
                   2142: 		     10 => 'Grade 10',
                   2143: 		     11 => 'Grade 11',
                   2144: 		     12 => 'Grade 12',
                   2145: 		     13 => 'Grade 13',
                   2146: 		     14 => '100 Level',
                   2147: 		     15 => '200 Level',
                   2148: 		     16 => '300 Level',
                   2149: 		     17 => '400 Level',
                   2150: 		     18 => 'Graduate Level');
                   2151:     return &mt($gradelevels{$gradelevel});
                   2152: }
                   2153: 
1.163     www      2154: sub select_level_form {
                   2155:     my ($deflevel,$name)=@_;
                   2156:     unless ($deflevel) { $deflevel=0; }
1.167     www      2157:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2158:     for (my $i=0; $i<=18; $i++) {
                   2159:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2160:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2161:                 ">".&gradeleveldescription($i)."</option>\n";
                   2162:     }
                   2163:     $selectform.="</select>";
                   2164:     return $selectform;
1.163     www      2165: }
1.167     www      2166: 
1.35      matthew  2167: #-------------------------------------------
                   2168: 
1.45      matthew  2169: =pod
                   2170: 
1.1075.2.42  raeburn  2171: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2172: 
                   2173: Returns a string containing a <select name='$name' size='1'> form to 
                   2174: allow a user to select the domain to preform an operation in.  
                   2175: See loncreateuser.pm for an example invocation and use.
                   2176: 
1.90      www      2177: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2178: selected");
                   2179: 
1.743     raeburn  2180: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2181: 
1.910     raeburn  2182: 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.
                   2183: 
1.1075.2.36  raeburn  2184: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2185: 
                   2186: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2187: 
1.35      matthew  2188: =cut
                   2189: 
                   2190: #-------------------------------------------
1.34      matthew  2191: sub select_dom_form {
1.1075.2.36  raeburn  2192:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2193:     if ($onchange) {
1.874     raeburn  2194:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2195:     }
1.1075.2.36  raeburn  2196:     my (@domains,%exclude);
1.910     raeburn  2197:     if (ref($incdoms) eq 'ARRAY') {
                   2198:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2199:     } else {
                   2200:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2201:     }
1.90      www      2202:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2203:     if (ref($excdoms) eq 'ARRAY') {
                   2204:         map { $exclude{$_} = 1; } @{$excdoms};
                   2205:     }
1.743     raeburn  2206:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2207:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2208:         next if ($exclude{$dom});
1.356     albertel 2209:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2210:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2211:         if ($showdomdesc) {
                   2212:             if ($dom ne '') {
                   2213:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2214:                 if ($domdesc ne '') {
                   2215:                     $selectdomain .= ' ('.$domdesc.')';
                   2216:                 }
                   2217:             } 
                   2218:         }
                   2219:         $selectdomain .= "</option>\n";
1.34      matthew  2220:     }
                   2221:     $selectdomain.="</select>";
                   2222:     return $selectdomain;
                   2223: }
                   2224: 
1.35      matthew  2225: #-------------------------------------------
                   2226: 
1.45      matthew  2227: =pod
                   2228: 
1.648     raeburn  2229: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2230: 
1.586     raeburn  2231: input: 4 arguments (two required, two optional) - 
                   2232:     $domain - domain of new user
                   2233:     $name - name of form element
                   2234:     $default - Value of 'default' causes a default item to be first 
                   2235:                             option, and selected by default. 
                   2236:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2237:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2238: output: returns 2 items: 
1.586     raeburn  2239: (a) form element which contains either:
                   2240:    (i) <select name="$name">
                   2241:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2242:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2243:        </select>
                   2244:        form item if there are multiple library servers in $domain, or
                   2245:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2246:        if there is only one library server in $domain.
                   2247: 
                   2248: (b) number of library servers found.
                   2249: 
                   2250: See loncreateuser.pm for example of use.
1.35      matthew  2251: 
                   2252: =cut
                   2253: 
                   2254: #-------------------------------------------
1.586     raeburn  2255: sub home_server_form_item {
                   2256:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2257:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2258:     my $result;
                   2259:     my $numlib = keys(%servers);
                   2260:     if ($numlib > 1) {
                   2261:         $result .= '<select name="'.$name.'" />'."\n";
                   2262:         if ($default) {
1.804     bisitz   2263:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2264:                        '</option>'."\n";
                   2265:         }
                   2266:         foreach my $hostid (sort(keys(%servers))) {
                   2267:             $result.= '<option value="'.$hostid.'">'.
                   2268: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2269:         }
                   2270:         $result .= '</select>'."\n";
                   2271:     } elsif ($numlib == 1) {
                   2272:         my $hostid;
                   2273:         foreach my $item (keys(%servers)) {
                   2274:             $hostid = $item;
                   2275:         }
                   2276:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2277:                    $hostid.'" />';
                   2278:                    if (!$hide) {
                   2279:                        $result .= $hostid.' '.$servers{$hostid};
                   2280:                    }
                   2281:                    $result .= "\n";
                   2282:     } elsif ($default) {
                   2283:         $result .= '<input type="hidden" name="'.$name.
                   2284:                    '" value="default" />';
                   2285:                    if (!$hide) {
                   2286:                        $result .= &mt('default');
                   2287:                    }
                   2288:                    $result .= "\n";
1.33      matthew  2289:     }
1.586     raeburn  2290:     return ($result,$numlib);
1.33      matthew  2291: }
1.112     bowersj2 2292: 
                   2293: =pod
                   2294: 
1.534     albertel 2295: =back 
                   2296: 
1.112     bowersj2 2297: =cut
1.87      matthew  2298: 
                   2299: ###############################################################
1.112     bowersj2 2300: ##                  Decoding User Agent                      ##
1.87      matthew  2301: ###############################################################
                   2302: 
                   2303: =pod
                   2304: 
1.112     bowersj2 2305: =head1 Decoding the User Agent
                   2306: 
                   2307: =over 4
                   2308: 
                   2309: =item * &decode_user_agent()
1.87      matthew  2310: 
                   2311: Inputs: $r
                   2312: 
                   2313: Outputs:
                   2314: 
                   2315: =over 4
                   2316: 
1.112     bowersj2 2317: =item * $httpbrowser
1.87      matthew  2318: 
1.112     bowersj2 2319: =item * $clientbrowser
1.87      matthew  2320: 
1.112     bowersj2 2321: =item * $clientversion
1.87      matthew  2322: 
1.112     bowersj2 2323: =item * $clientmathml
1.87      matthew  2324: 
1.112     bowersj2 2325: =item * $clientunicode
1.87      matthew  2326: 
1.112     bowersj2 2327: =item * $clientos
1.87      matthew  2328: 
1.1075.2.42  raeburn  2329: =item * $clientmobile
                   2330: 
                   2331: =item * $clientinfo
                   2332: 
1.87      matthew  2333: =back
                   2334: 
1.157     matthew  2335: =back 
                   2336: 
1.87      matthew  2337: =cut
                   2338: 
                   2339: ###############################################################
                   2340: ###############################################################
                   2341: sub decode_user_agent {
1.247     albertel 2342:     my ($r)=@_;
1.87      matthew  2343:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2344:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2345:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2346:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2347:     my $clientbrowser='unknown';
                   2348:     my $clientversion='0';
                   2349:     my $clientmathml='';
                   2350:     my $clientunicode='0';
1.1075.2.42  raeburn  2351:     my $clientmobile=0;
1.87      matthew  2352:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2353:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2354: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2355: 	    $clientbrowser=$bname;
                   2356:             $httpbrowser=~/$vreg/i;
                   2357: 	    $clientversion=$1;
                   2358:             $clientmathml=($clientversion>=$minv);
                   2359:             $clientunicode=($clientversion>=$univ);
                   2360: 	}
                   2361:     }
                   2362:     my $clientos='unknown';
1.1075.2.42  raeburn  2363:     my $clientinfo;
1.87      matthew  2364:     if (($httpbrowser=~/linux/i) ||
                   2365:         ($httpbrowser=~/unix/i) ||
                   2366:         ($httpbrowser=~/ux/i) ||
                   2367:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2368:     if (($httpbrowser=~/vax/i) ||
                   2369:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2370:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2371:     if (($httpbrowser=~/mac/i) ||
                   2372:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2373:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2374:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2375:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2376:         $clientmobile=lc($1);
                   2377:     }
                   2378:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2379:         $clientinfo = 'firefox-'.$1;
                   2380:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2381:         $clientinfo = 'chromeframe-'.$1;
                   2382:     }
1.87      matthew  2383:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.42  raeburn  2384:             $clientunicode,$clientos,$clientmobile,$clientinfo);
1.87      matthew  2385: }
                   2386: 
1.32      matthew  2387: ###############################################################
                   2388: ##    Authentication changing form generation subroutines    ##
                   2389: ###############################################################
                   2390: ##
                   2391: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2392: ## hash, and have reasonable default values.
                   2393: ##
                   2394: ##    formname = the name given in the <form> tag.
1.35      matthew  2395: #-------------------------------------------
                   2396: 
1.45      matthew  2397: =pod
                   2398: 
1.112     bowersj2 2399: =head1 Authentication Routines
                   2400: 
                   2401: =over 4
                   2402: 
1.648     raeburn  2403: =item * &authform_xxxxxx()
1.35      matthew  2404: 
                   2405: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2406: handle some of the conveniences required for authentication forms.  
                   2407: This is not an optimal method, but it works.  
                   2408: 
                   2409: =over 4
                   2410: 
1.112     bowersj2 2411: =item * authform_header
1.35      matthew  2412: 
1.112     bowersj2 2413: =item * authform_authorwarning
1.35      matthew  2414: 
1.112     bowersj2 2415: =item * authform_nochange
1.35      matthew  2416: 
1.112     bowersj2 2417: =item * authform_kerberos
1.35      matthew  2418: 
1.112     bowersj2 2419: =item * authform_internal
1.35      matthew  2420: 
1.112     bowersj2 2421: =item * authform_filesystem
1.35      matthew  2422: 
                   2423: =back
                   2424: 
1.648     raeburn  2425: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2426: 
1.35      matthew  2427: =cut
                   2428: 
                   2429: #-------------------------------------------
1.32      matthew  2430: sub authform_header{  
                   2431:     my %in = (
                   2432:         formname => 'cu',
1.80      albertel 2433:         kerb_def_dom => '',
1.32      matthew  2434:         @_,
                   2435:     );
                   2436:     $in{'formname'} = 'document.' . $in{'formname'};
                   2437:     my $result='';
1.80      albertel 2438: 
                   2439: #---------------------------------------------- Code for upper case translation
                   2440:     my $Javascript_toUpperCase;
                   2441:     unless ($in{kerb_def_dom}) {
                   2442:         $Javascript_toUpperCase =<<"END";
                   2443:         switch (choice) {
                   2444:            case 'krb': currentform.elements[choicearg].value =
                   2445:                currentform.elements[choicearg].value.toUpperCase();
                   2446:                break;
                   2447:            default:
                   2448:         }
                   2449: END
                   2450:     } else {
                   2451:         $Javascript_toUpperCase = "";
                   2452:     }
                   2453: 
1.165     raeburn  2454:     my $radioval = "'nochange'";
1.591     raeburn  2455:     if (defined($in{'curr_authtype'})) {
                   2456:         if ($in{'curr_authtype'} ne '') {
                   2457:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2458:         }
1.174     matthew  2459:     }
1.165     raeburn  2460:     my $argfield = 'null';
1.591     raeburn  2461:     if (defined($in{'mode'})) {
1.165     raeburn  2462:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2463:             if (defined($in{'curr_autharg'})) {
                   2464:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2465:                     $argfield = "'$in{'curr_autharg'}'";
                   2466:                 }
                   2467:             }
                   2468:         }
                   2469:     }
                   2470: 
1.32      matthew  2471:     $result.=<<"END";
                   2472: var current = new Object();
1.165     raeburn  2473: current.radiovalue = $radioval;
                   2474: current.argfield = $argfield;
1.32      matthew  2475: 
                   2476: function changed_radio(choice,currentform) {
                   2477:     var choicearg = choice + 'arg';
                   2478:     // If a radio button in changed, we need to change the argfield
                   2479:     if (current.radiovalue != choice) {
                   2480:         current.radiovalue = choice;
                   2481:         if (current.argfield != null) {
                   2482:             currentform.elements[current.argfield].value = '';
                   2483:         }
                   2484:         if (choice == 'nochange') {
                   2485:             current.argfield = null;
                   2486:         } else {
                   2487:             current.argfield = choicearg;
                   2488:             switch(choice) {
                   2489:                 case 'krb': 
                   2490:                     currentform.elements[current.argfield].value = 
                   2491:                         "$in{'kerb_def_dom'}";
                   2492:                 break;
                   2493:               default:
                   2494:                 break;
                   2495:             }
                   2496:         }
                   2497:     }
                   2498:     return;
                   2499: }
1.22      www      2500: 
1.32      matthew  2501: function changed_text(choice,currentform) {
                   2502:     var choicearg = choice + 'arg';
                   2503:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2504:         $Javascript_toUpperCase
1.32      matthew  2505:         // clear old field
                   2506:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2507:             currentform.elements[current.argfield].value = '';
                   2508:         }
                   2509:         current.argfield = choicearg;
                   2510:     }
                   2511:     set_auth_radio_buttons(choice,currentform);
                   2512:     return;
1.20      www      2513: }
1.32      matthew  2514: 
                   2515: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2516:     var numauthchoices = currentform.login.length;
                   2517:     if (typeof numauthchoices  == "undefined") {
                   2518:         return;
                   2519:     } 
1.32      matthew  2520:     var i=0;
1.986     raeburn  2521:     while (i < numauthchoices) {
1.32      matthew  2522:         if (currentform.login[i].value == newvalue) { break; }
                   2523:         i++;
                   2524:     }
1.986     raeburn  2525:     if (i == numauthchoices) {
1.32      matthew  2526:         return;
                   2527:     }
                   2528:     current.radiovalue = newvalue;
                   2529:     currentform.login[i].checked = true;
                   2530:     return;
                   2531: }
                   2532: END
                   2533:     return $result;
                   2534: }
                   2535: 
1.1075.2.20  raeburn  2536: sub authform_authorwarning {
1.32      matthew  2537:     my $result='';
1.144     matthew  2538:     $result='<i>'.
                   2539:         &mt('As a general rule, only authors or co-authors should be '.
                   2540:             'filesystem authenticated '.
                   2541:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2542:     return $result;
                   2543: }
                   2544: 
1.1075.2.20  raeburn  2545: sub authform_nochange {
1.32      matthew  2546:     my %in = (
                   2547:               formname => 'document.cu',
                   2548:               kerb_def_dom => 'MSU.EDU',
                   2549:               @_,
                   2550:           );
1.1075.2.20  raeburn  2551:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2552:     my $result;
1.1075.2.20  raeburn  2553:     if (!$authnum) {
                   2554:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2555:     } else {
                   2556:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2557:                   '<input type="radio" name="login" value="nochange" '.
                   2558:                   'checked="checked" onclick="'.
1.281     albertel 2559:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2560: 	    '</label>';
1.586     raeburn  2561:     }
1.32      matthew  2562:     return $result;
                   2563: }
                   2564: 
1.591     raeburn  2565: sub authform_kerberos {
1.32      matthew  2566:     my %in = (
                   2567:               formname => 'document.cu',
                   2568:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2569:               kerb_def_auth => 'krb4',
1.32      matthew  2570:               @_,
                   2571:               );
1.586     raeburn  2572:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2573:         $autharg,$jscall);
1.1075.2.20  raeburn  2574:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2575:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2576:        $check5 = ' checked="checked"';
1.80      albertel 2577:     } else {
1.772     bisitz   2578:        $check4 = ' checked="checked"';
1.80      albertel 2579:     }
1.165     raeburn  2580:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2581:     if (defined($in{'curr_authtype'})) {
                   2582:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2583:             $krbcheck = ' checked="checked"';
1.623     raeburn  2584:             if (defined($in{'mode'})) {
                   2585:                 if ($in{'mode'} eq 'modifyuser') {
                   2586:                     $krbcheck = '';
                   2587:                 }
                   2588:             }
1.591     raeburn  2589:             if (defined($in{'curr_kerb_ver'})) {
                   2590:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2591:                     $check5 = ' checked="checked"';
1.591     raeburn  2592:                     $check4 = '';
                   2593:                 } else {
1.772     bisitz   2594:                     $check4 = ' checked="checked"';
1.591     raeburn  2595:                     $check5 = '';
                   2596:                 }
1.586     raeburn  2597:             }
1.591     raeburn  2598:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2599:                 $krbarg = $in{'curr_autharg'};
                   2600:             }
1.586     raeburn  2601:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2602:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2603:                     $result = 
                   2604:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2605:         $in{'curr_autharg'},$krbver);
                   2606:                 } else {
                   2607:                     $result =
                   2608:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2609:                 }
                   2610:                 return $result; 
                   2611:             }
                   2612:         }
                   2613:     } else {
                   2614:         if ($authnum == 1) {
1.784     bisitz   2615:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2616:         }
                   2617:     }
1.586     raeburn  2618:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2619:         return;
1.587     raeburn  2620:     } elsif ($authtype eq '') {
1.591     raeburn  2621:         if (defined($in{'mode'})) {
1.587     raeburn  2622:             if ($in{'mode'} eq 'modifycourse') {
                   2623:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2624:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2625:                 }
                   2626:             }
                   2627:         }
1.586     raeburn  2628:     }
                   2629:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2630:     if ($authtype eq '') {
                   2631:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2632:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2633:                     $krbcheck.' />';
                   2634:     }
                   2635:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2636:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2637:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2638:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2639:          $in{'curr_authtype'} eq 'krb4')) {
                   2640:         $result .= &mt
1.144     matthew  2641:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2642:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2643:          '<label>'.$authtype,
1.281     albertel 2644:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2645:              'value="'.$krbarg.'" '.
1.144     matthew  2646:              'onchange="'.$jscall.'" />',
1.281     albertel 2647:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2648:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2649: 	 '</label>');
1.586     raeburn  2650:     } elsif ($can_assign{'krb4'}) {
                   2651:         $result .= &mt
                   2652:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2653:          '[_3] Version 4 [_4]',
                   2654:          '<label>'.$authtype,
                   2655:          '</label><input type="text" size="10" name="krbarg" '.
                   2656:              'value="'.$krbarg.'" '.
                   2657:              'onchange="'.$jscall.'" />',
                   2658:          '<label><input type="hidden" name="krbver" value="4" />',
                   2659:          '</label>');
                   2660:     } elsif ($can_assign{'krb5'}) {
                   2661:         $result .= &mt
                   2662:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2663:          '[_3] Version 5 [_4]',
                   2664:          '<label>'.$authtype,
                   2665:          '</label><input type="text" size="10" name="krbarg" '.
                   2666:              'value="'.$krbarg.'" '.
                   2667:              'onchange="'.$jscall.'" />',
                   2668:          '<label><input type="hidden" name="krbver" value="5" />',
                   2669:          '</label>');
                   2670:     }
1.32      matthew  2671:     return $result;
                   2672: }
                   2673: 
1.1075.2.20  raeburn  2674: sub authform_internal {
1.586     raeburn  2675:     my %in = (
1.32      matthew  2676:                 formname => 'document.cu',
                   2677:                 kerb_def_dom => 'MSU.EDU',
                   2678:                 @_,
                   2679:                 );
1.586     raeburn  2680:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2681:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2682:     if (defined($in{'curr_authtype'})) {
                   2683:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2684:             if ($can_assign{'int'}) {
1.772     bisitz   2685:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2686:                 if (defined($in{'mode'})) {
                   2687:                     if ($in{'mode'} eq 'modifyuser') {
                   2688:                         $intcheck = '';
                   2689:                     }
                   2690:                 }
1.591     raeburn  2691:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2692:                     $intarg = $in{'curr_autharg'};
                   2693:                 }
                   2694:             } else {
                   2695:                 $result = &mt('Currently internally authenticated.');
                   2696:                 return $result;
1.165     raeburn  2697:             }
                   2698:         }
1.586     raeburn  2699:     } else {
                   2700:         if ($authnum == 1) {
1.784     bisitz   2701:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2702:         }
                   2703:     }
                   2704:     if (!$can_assign{'int'}) {
                   2705:         return;
1.587     raeburn  2706:     } elsif ($authtype eq '') {
1.591     raeburn  2707:         if (defined($in{'mode'})) {
1.587     raeburn  2708:             if ($in{'mode'} eq 'modifycourse') {
                   2709:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2710:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2711:                 }
                   2712:             }
                   2713:         }
1.165     raeburn  2714:     }
1.586     raeburn  2715:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2716:     if ($authtype eq '') {
                   2717:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2718:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2719:     }
1.605     bisitz   2720:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2721:                $intarg.'" onchange="'.$jscall.'" />';
                   2722:     $result = &mt
1.144     matthew  2723:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2724:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2725:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  2726:     return $result;
                   2727: }
                   2728: 
1.1075.2.20  raeburn  2729: sub authform_local {
1.32      matthew  2730:     my %in = (
                   2731:               formname => 'document.cu',
                   2732:               kerb_def_dom => 'MSU.EDU',
                   2733:               @_,
                   2734:               );
1.586     raeburn  2735:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2736:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2737:     if (defined($in{'curr_authtype'})) {
                   2738:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2739:             if ($can_assign{'loc'}) {
1.772     bisitz   2740:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2741:                 if (defined($in{'mode'})) {
                   2742:                     if ($in{'mode'} eq 'modifyuser') {
                   2743:                         $loccheck = '';
                   2744:                     }
                   2745:                 }
1.591     raeburn  2746:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2747:                     $locarg = $in{'curr_autharg'};
                   2748:                 }
                   2749:             } else {
                   2750:                 $result = &mt('Currently using local (institutional) authentication.');
                   2751:                 return $result;
1.165     raeburn  2752:             }
                   2753:         }
1.586     raeburn  2754:     } else {
                   2755:         if ($authnum == 1) {
1.784     bisitz   2756:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2757:         }
                   2758:     }
                   2759:     if (!$can_assign{'loc'}) {
                   2760:         return;
1.587     raeburn  2761:     } elsif ($authtype eq '') {
1.591     raeburn  2762:         if (defined($in{'mode'})) {
1.587     raeburn  2763:             if ($in{'mode'} eq 'modifycourse') {
                   2764:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2765:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2766:                 }
                   2767:             }
                   2768:         }
1.165     raeburn  2769:     }
1.586     raeburn  2770:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2771:     if ($authtype eq '') {
                   2772:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2773:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2774:                     $jscall.'" />';
                   2775:     }
                   2776:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2777:                $locarg.'" onchange="'.$jscall.'" />';
                   2778:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2779:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2780:     return $result;
                   2781: }
                   2782: 
1.1075.2.20  raeburn  2783: sub authform_filesystem {
1.32      matthew  2784:     my %in = (
                   2785:               formname => 'document.cu',
                   2786:               kerb_def_dom => 'MSU.EDU',
                   2787:               @_,
                   2788:               );
1.586     raeburn  2789:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2790:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2791:     if (defined($in{'curr_authtype'})) {
                   2792:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2793:             if ($can_assign{'fsys'}) {
1.772     bisitz   2794:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2795:                 if (defined($in{'mode'})) {
                   2796:                     if ($in{'mode'} eq 'modifyuser') {
                   2797:                         $fsyscheck = '';
                   2798:                     }
                   2799:                 }
1.586     raeburn  2800:             } else {
                   2801:                 $result = &mt('Currently Filesystem Authenticated.');
                   2802:                 return $result;
                   2803:             }           
                   2804:         }
                   2805:     } else {
                   2806:         if ($authnum == 1) {
1.784     bisitz   2807:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2808:         }
                   2809:     }
                   2810:     if (!$can_assign{'fsys'}) {
                   2811:         return;
1.587     raeburn  2812:     } elsif ($authtype eq '') {
1.591     raeburn  2813:         if (defined($in{'mode'})) {
1.587     raeburn  2814:             if ($in{'mode'} eq 'modifycourse') {
                   2815:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2816:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2817:                 }
                   2818:             }
                   2819:         }
1.586     raeburn  2820:     }
                   2821:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2822:     if ($authtype eq '') {
                   2823:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2824:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2825:                     $jscall.'" />';
                   2826:     }
                   2827:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2828:                ' onchange="'.$jscall.'" />';
                   2829:     $result = &mt
1.144     matthew  2830:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2831:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2832:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2833:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2834:                   'onchange="'.$jscall.'" />');
1.32      matthew  2835:     return $result;
                   2836: }
                   2837: 
1.586     raeburn  2838: sub get_assignable_auth {
                   2839:     my ($dom) = @_;
                   2840:     if ($dom eq '') {
                   2841:         $dom = $env{'request.role.domain'};
                   2842:     }
                   2843:     my %can_assign = (
                   2844:                           krb4 => 1,
                   2845:                           krb5 => 1,
                   2846:                           int  => 1,
                   2847:                           loc  => 1,
                   2848:                      );
                   2849:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2850:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2851:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2852:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2853:             my $context;
                   2854:             if ($env{'request.role'} =~ /^au/) {
                   2855:                 $context = 'author';
                   2856:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2857:                 $context = 'domain';
                   2858:             } elsif ($env{'request.course.id'}) {
                   2859:                 $context = 'course';
                   2860:             }
                   2861:             if ($context) {
                   2862:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2863:                    %can_assign = %{$authhash->{$context}}; 
                   2864:                 }
                   2865:             }
                   2866:         }
                   2867:     }
                   2868:     my $authnum = 0;
                   2869:     foreach my $key (keys(%can_assign)) {
                   2870:         if ($can_assign{$key}) {
                   2871:             $authnum ++;
                   2872:         }
                   2873:     }
                   2874:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2875:         $authnum --;
                   2876:     }
                   2877:     return ($authnum,%can_assign);
                   2878: }
                   2879: 
1.80      albertel 2880: ###############################################################
                   2881: ##    Get Kerberos Defaults for Domain                 ##
                   2882: ###############################################################
                   2883: ##
                   2884: ## Returns default kerberos version and an associated argument
                   2885: ## as listed in file domain.tab. If not listed, provides
                   2886: ## appropriate default domain and kerberos version.
                   2887: ##
                   2888: #-------------------------------------------
                   2889: 
                   2890: =pod
                   2891: 
1.648     raeburn  2892: =item * &get_kerberos_defaults()
1.80      albertel 2893: 
                   2894: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2895: version and domain. If not found, it defaults to version 4 and the 
                   2896: domain of the server.
1.80      albertel 2897: 
1.648     raeburn  2898: =over 4
                   2899: 
1.80      albertel 2900: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2901: 
1.648     raeburn  2902: =back
                   2903: 
                   2904: =back
                   2905: 
1.80      albertel 2906: =cut
                   2907: 
                   2908: #-------------------------------------------
                   2909: sub get_kerberos_defaults {
                   2910:     my $domain=shift;
1.641     raeburn  2911:     my ($krbdef,$krbdefdom);
                   2912:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2913:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2914:         $krbdef = $domdefaults{'auth_def'};
                   2915:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2916:     } else {
1.80      albertel 2917:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2918:         my $krbdefdom=$1;
                   2919:         $krbdefdom=~tr/a-z/A-Z/;
                   2920:         $krbdef = "krb4";
                   2921:     }
                   2922:     return ($krbdef,$krbdefdom);
                   2923: }
1.112     bowersj2 2924: 
1.32      matthew  2925: 
1.46      matthew  2926: ###############################################################
                   2927: ##                Thesaurus Functions                        ##
                   2928: ###############################################################
1.20      www      2929: 
1.46      matthew  2930: =pod
1.20      www      2931: 
1.112     bowersj2 2932: =head1 Thesaurus Functions
                   2933: 
                   2934: =over 4
                   2935: 
1.648     raeburn  2936: =item * &initialize_keywords()
1.46      matthew  2937: 
                   2938: Initializes the package variable %Keywords if it is empty.  Uses the
                   2939: package variable $thesaurus_db_file.
                   2940: 
                   2941: =cut
                   2942: 
                   2943: ###################################################
                   2944: 
                   2945: sub initialize_keywords {
                   2946:     return 1 if (scalar keys(%Keywords));
                   2947:     # If we are here, %Keywords is empty, so fill it up
                   2948:     #   Make sure the file we need exists...
                   2949:     if (! -e $thesaurus_db_file) {
                   2950:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2951:                                  " failed because it does not exist");
                   2952:         return 0;
                   2953:     }
                   2954:     #   Set up the hash as a database
                   2955:     my %thesaurus_db;
                   2956:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2957:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2958:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2959:                                  $thesaurus_db_file);
                   2960:         return 0;
                   2961:     } 
                   2962:     #  Get the average number of appearances of a word.
                   2963:     my $avecount = $thesaurus_db{'average.count'};
                   2964:     #  Put keywords (those that appear > average) into %Keywords
                   2965:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2966:         my ($count,undef) = split /:/,$data;
                   2967:         $Keywords{$word}++ if ($count > $avecount);
                   2968:     }
                   2969:     untie %thesaurus_db;
                   2970:     # Remove special values from %Keywords.
1.356     albertel 2971:     foreach my $value ('total.count','average.count') {
                   2972:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2973:   }
1.46      matthew  2974:     return 1;
                   2975: }
                   2976: 
                   2977: ###################################################
                   2978: 
                   2979: =pod
                   2980: 
1.648     raeburn  2981: =item * &keyword($word)
1.46      matthew  2982: 
                   2983: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2984: than the average number of times in the thesaurus database.  Calls 
                   2985: &initialize_keywords
                   2986: 
                   2987: =cut
                   2988: 
                   2989: ###################################################
1.20      www      2990: 
                   2991: sub keyword {
1.46      matthew  2992:     return if (!&initialize_keywords());
                   2993:     my $word=lc(shift());
                   2994:     $word=~s/\W//g;
                   2995:     return exists($Keywords{$word});
1.20      www      2996: }
1.46      matthew  2997: 
                   2998: ###############################################################
                   2999: 
                   3000: =pod 
1.20      www      3001: 
1.648     raeburn  3002: =item * &get_related_words()
1.46      matthew  3003: 
1.160     matthew  3004: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3005: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3006: will be returned.  The order of the words returned is determined by the
                   3007: database which holds them.
                   3008: 
                   3009: Uses global $thesaurus_db_file.
                   3010: 
1.1057    foxr     3011: 
1.46      matthew  3012: =cut
                   3013: 
                   3014: ###############################################################
                   3015: sub get_related_words {
                   3016:     my $keyword = shift;
                   3017:     my %thesaurus_db;
                   3018:     if (! -e $thesaurus_db_file) {
                   3019:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3020:                                  "failed because the file does not exist");
                   3021:         return ();
                   3022:     }
                   3023:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3024:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3025:         return ();
                   3026:     } 
                   3027:     my @Words=();
1.429     www      3028:     my $count=0;
1.46      matthew  3029:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3030: 	# The first element is the number of times
                   3031: 	# the word appears.  We do not need it now.
1.429     www      3032: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3033: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3034: 	my $threshold=$mostfrequentcount/10;
                   3035:         foreach my $possibleword (@RelatedWords) {
                   3036:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3037:             if ($wordcount>$threshold) {
                   3038: 		push(@Words,$word);
                   3039:                 $count++;
                   3040:                 if ($count>10) { last; }
                   3041: 	    }
1.20      www      3042:         }
                   3043:     }
1.46      matthew  3044:     untie %thesaurus_db;
                   3045:     return @Words;
1.14      harris41 3046: }
1.46      matthew  3047: 
1.112     bowersj2 3048: =pod
                   3049: 
                   3050: =back
                   3051: 
                   3052: =cut
1.61      www      3053: 
                   3054: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3055: =pod
                   3056: 
1.112     bowersj2 3057: =head1 User Name Functions
                   3058: 
                   3059: =over 4
                   3060: 
1.648     raeburn  3061: =item * &plainname($uname,$udom,$first)
1.81      albertel 3062: 
1.112     bowersj2 3063: Takes a users logon name and returns it as a string in
1.226     albertel 3064: "first middle last generation" form 
                   3065: if $first is set to 'lastname' then it returns it as
                   3066: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3067: 
                   3068: =cut
1.61      www      3069: 
1.295     www      3070: 
1.81      albertel 3071: ###############################################################
1.61      www      3072: sub plainname {
1.226     albertel 3073:     my ($uname,$udom,$first)=@_;
1.537     albertel 3074:     return if (!defined($uname) || !defined($udom));
1.295     www      3075:     my %names=&getnames($uname,$udom);
1.226     albertel 3076:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3077: 					  $names{'middlename'},
                   3078: 					  $names{'lastname'},
                   3079: 					  $names{'generation'},$first);
                   3080:     $name=~s/^\s+//;
1.62      www      3081:     $name=~s/\s+$//;
                   3082:     $name=~s/\s+/ /g;
1.353     albertel 3083:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3084:     return $name;
1.61      www      3085: }
1.66      www      3086: 
                   3087: # -------------------------------------------------------------------- Nickname
1.81      albertel 3088: =pod
                   3089: 
1.648     raeburn  3090: =item * &nickname($uname,$udom)
1.81      albertel 3091: 
                   3092: Gets a users name and returns it as a string as
                   3093: 
                   3094: "&quot;nickname&quot;"
1.66      www      3095: 
1.81      albertel 3096: if the user has a nickname or
                   3097: 
                   3098: "first middle last generation"
                   3099: 
                   3100: if the user does not
                   3101: 
                   3102: =cut
1.66      www      3103: 
                   3104: sub nickname {
                   3105:     my ($uname,$udom)=@_;
1.537     albertel 3106:     return if (!defined($uname) || !defined($udom));
1.295     www      3107:     my %names=&getnames($uname,$udom);
1.68      albertel 3108:     my $name=$names{'nickname'};
1.66      www      3109:     if ($name) {
                   3110:        $name='&quot;'.$name.'&quot;'; 
                   3111:     } else {
                   3112:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3113: 	     $names{'lastname'}.' '.$names{'generation'};
                   3114:        $name=~s/\s+$//;
                   3115:        $name=~s/\s+/ /g;
                   3116:     }
                   3117:     return $name;
                   3118: }
                   3119: 
1.295     www      3120: sub getnames {
                   3121:     my ($uname,$udom)=@_;
1.537     albertel 3122:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3123:     if ($udom eq 'public' && $uname eq 'public') {
                   3124: 	return ('lastname' => &mt('Public'));
                   3125:     }
1.295     www      3126:     my $id=$uname.':'.$udom;
                   3127:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3128:     if ($cached) {
                   3129: 	return %{$names};
                   3130:     } else {
                   3131: 	my %loadnames=&Apache::lonnet::get('environment',
                   3132:                     ['firstname','middlename','lastname','generation','nickname'],
                   3133: 					 $udom,$uname);
                   3134: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3135: 	return %loadnames;
                   3136:     }
                   3137: }
1.61      www      3138: 
1.542     raeburn  3139: # -------------------------------------------------------------------- getemails
1.648     raeburn  3140: 
1.542     raeburn  3141: =pod
                   3142: 
1.648     raeburn  3143: =item * &getemails($uname,$udom)
1.542     raeburn  3144: 
                   3145: Gets a user's email information and returns it as a hash with keys:
                   3146: notification, critnotification, permanentemail
                   3147: 
                   3148: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3149: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3150:  
1.648     raeburn  3151: 
1.542     raeburn  3152: =cut
                   3153: 
1.648     raeburn  3154: 
1.466     albertel 3155: sub getemails {
                   3156:     my ($uname,$udom)=@_;
                   3157:     if ($udom eq 'public' && $uname eq 'public') {
                   3158: 	return;
                   3159:     }
1.467     www      3160:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3161:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3162:     my $id=$uname.':'.$udom;
                   3163:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3164:     if ($cached) {
                   3165: 	return %{$names};
                   3166:     } else {
                   3167: 	my %loadnames=&Apache::lonnet::get('environment',
                   3168:                     			   ['notification','critnotification',
                   3169: 					    'permanentemail'],
                   3170: 					   $udom,$uname);
                   3171: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3172: 	return %loadnames;
                   3173:     }
                   3174: }
                   3175: 
1.551     albertel 3176: sub flush_email_cache {
                   3177:     my ($uname,$udom)=@_;
                   3178:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3179:     if (!$uname) { $uname=$env{'user.name'};   }
                   3180:     return if ($udom eq 'public' && $uname eq 'public');
                   3181:     my $id=$uname.':'.$udom;
                   3182:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3183: }
                   3184: 
1.728     raeburn  3185: # -------------------------------------------------------------------- getlangs
                   3186: 
                   3187: =pod
                   3188: 
                   3189: =item * &getlangs($uname,$udom)
                   3190: 
                   3191: Gets a user's language preference and returns it as a hash with key:
                   3192: language.
                   3193: 
                   3194: =cut
                   3195: 
                   3196: 
                   3197: sub getlangs {
                   3198:     my ($uname,$udom) = @_;
                   3199:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3200:     if (!$uname) { $uname=$env{'user.name'};   }
                   3201:     my $id=$uname.':'.$udom;
                   3202:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3203:     if ($cached) {
                   3204:         return %{$langs};
                   3205:     } else {
                   3206:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3207:                                            $udom,$uname);
                   3208:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3209:         return %loadlangs;
                   3210:     }
                   3211: }
                   3212: 
                   3213: sub flush_langs_cache {
                   3214:     my ($uname,$udom)=@_;
                   3215:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3216:     if (!$uname) { $uname=$env{'user.name'};   }
                   3217:     return if ($udom eq 'public' && $uname eq 'public');
                   3218:     my $id=$uname.':'.$udom;
                   3219:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3220: }
                   3221: 
1.61      www      3222: # ------------------------------------------------------------------ Screenname
1.81      albertel 3223: 
                   3224: =pod
                   3225: 
1.648     raeburn  3226: =item * &screenname($uname,$udom)
1.81      albertel 3227: 
                   3228: Gets a users screenname and returns it as a string
                   3229: 
                   3230: =cut
1.61      www      3231: 
                   3232: sub screenname {
                   3233:     my ($uname,$udom)=@_;
1.258     albertel 3234:     if ($uname eq $env{'user.name'} &&
                   3235: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3236:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3237:     return $names{'screenname'};
1.62      www      3238: }
                   3239: 
1.212     albertel 3240: 
1.802     bisitz   3241: # ------------------------------------------------------------- Confirm Wrapper
                   3242: =pod
                   3243: 
1.1075.2.42  raeburn  3244: =item * &confirmwrapper($message)
1.802     bisitz   3245: 
                   3246: Wrap messages about completion of operation in box
                   3247: 
                   3248: =cut
                   3249: 
                   3250: sub confirmwrapper {
                   3251:     my ($message)=@_;
                   3252:     if ($message) {
                   3253:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3254:                .$message."\n"
                   3255:                .'</div>'."\n";
                   3256:     } else {
                   3257:         return $message;
                   3258:     }
                   3259: }
                   3260: 
1.62      www      3261: # ------------------------------------------------------------- Message Wrapper
                   3262: 
                   3263: sub messagewrapper {
1.369     www      3264:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3265:     return 
1.441     albertel 3266:         '<a href="/adm/email?compose=individual&amp;'.
                   3267:         'recname='.$username.'&amp;recdom='.$domain.
                   3268: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3269:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3270: }
1.802     bisitz   3271: 
1.74      www      3272: # --------------------------------------------------------------- Notes Wrapper
                   3273: 
                   3274: sub noteswrapper {
                   3275:     my ($link,$un,$do)=@_;
                   3276:     return 
1.896     amueller 3277: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3278: }
1.802     bisitz   3279: 
1.62      www      3280: # ------------------------------------------------------------- Aboutme Wrapper
                   3281: 
                   3282: sub aboutmewrapper {
1.1070    raeburn  3283:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3284:     if (!defined($username)  && !defined($domain)) {
                   3285:         return;
                   3286:     }
1.1075.2.15  raeburn  3287:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3288: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3289: }
                   3290: 
                   3291: # ------------------------------------------------------------ Syllabus Wrapper
                   3292: 
                   3293: sub syllabuswrapper {
1.707     bisitz   3294:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3295:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3296: }
1.14      harris41 3297: 
1.802     bisitz   3298: # -----------------------------------------------------------------------------
                   3299: 
1.208     matthew  3300: sub track_student_link {
1.887     raeburn  3301:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3302:     my $link ="/adm/trackstudent?";
1.208     matthew  3303:     my $title = 'View recent activity';
                   3304:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3305:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3306:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3307:         $title .= ' of this student';
1.268     albertel 3308:     } 
1.208     matthew  3309:     if (defined($target) && $target !~ /^\s*$/) {
                   3310:         $target = qq{target="$target"};
                   3311:     } else {
                   3312:         $target = '';
                   3313:     }
1.268     albertel 3314:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3315:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3316:     $title = &mt($title);
                   3317:     $linktext = &mt($linktext);
1.448     albertel 3318:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3319: 	&help_open_topic('View_recent_activity');
1.208     matthew  3320: }
                   3321: 
1.781     raeburn  3322: sub slot_reservations_link {
                   3323:     my ($linktext,$sname,$sdom,$target) = @_;
                   3324:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3325:     my $title = 'View slot reservation history';
                   3326:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3327:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3328:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3329:         $title .= ' of this student';
                   3330:     }
                   3331:     if (defined($target) && $target !~ /^\s*$/) {
                   3332:         $target = qq{target="$target"};
                   3333:     } else {
                   3334:         $target = '';
                   3335:     }
                   3336:     $title = &mt($title);
                   3337:     $linktext = &mt($linktext);
                   3338:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3339: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3340: 
                   3341: }
                   3342: 
1.508     www      3343: # ===================================================== Display a student photo
                   3344: 
                   3345: 
1.509     albertel 3346: sub student_image_tag {
1.508     www      3347:     my ($domain,$user)=@_;
                   3348:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3349:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3350: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3351:     } else {
                   3352: 	return '';
                   3353:     }
                   3354: }
                   3355: 
1.112     bowersj2 3356: =pod
                   3357: 
                   3358: =back
                   3359: 
                   3360: =head1 Access .tab File Data
                   3361: 
                   3362: =over 4
                   3363: 
1.648     raeburn  3364: =item * &languageids() 
1.112     bowersj2 3365: 
                   3366: returns list of all language ids
                   3367: 
                   3368: =cut
                   3369: 
1.14      harris41 3370: sub languageids {
1.16      harris41 3371:     return sort(keys(%language));
1.14      harris41 3372: }
                   3373: 
1.112     bowersj2 3374: =pod
                   3375: 
1.648     raeburn  3376: =item * &languagedescription() 
1.112     bowersj2 3377: 
                   3378: returns description of a specified language id
                   3379: 
                   3380: =cut
                   3381: 
1.14      harris41 3382: sub languagedescription {
1.125     www      3383:     my $code=shift;
                   3384:     return  ($supported_language{$code}?'* ':'').
                   3385:             $language{$code}.
1.126     www      3386: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3387: }
                   3388: 
1.1048    foxr     3389: =pod
                   3390: 
                   3391: =item * &plainlanguagedescription
                   3392: 
                   3393: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3394: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3395: 
                   3396: =cut
                   3397: 
1.145     www      3398: sub plainlanguagedescription {
                   3399:     my $code=shift;
                   3400:     return $language{$code};
                   3401: }
                   3402: 
1.1048    foxr     3403: =pod
                   3404: 
                   3405: =item * &supportedlanguagecode
                   3406: 
                   3407: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3408: code.
                   3409: 
                   3410: =cut
                   3411: 
1.145     www      3412: sub supportedlanguagecode {
                   3413:     my $code=shift;
                   3414:     return $supported_language{$code};
1.97      www      3415: }
                   3416: 
1.112     bowersj2 3417: =pod
                   3418: 
1.1048    foxr     3419: =item * &latexlanguage()
                   3420: 
                   3421: Given a language key code returns the correspondnig language to use
                   3422: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3423: is no supported hyphenation for the language code.
                   3424: 
                   3425: =cut
                   3426: 
                   3427: sub latexlanguage {
                   3428:     my $code = shift;
                   3429:     return $latex_language{$code};
                   3430: }
                   3431: 
                   3432: =pod
                   3433: 
                   3434: =item * &latexhyphenation()
                   3435: 
                   3436: Same as above but what's supplied is the language as it might be stored
                   3437: in the metadata.
                   3438: 
                   3439: =cut
                   3440: 
                   3441: sub latexhyphenation {
                   3442:     my $key = shift;
                   3443:     return $latex_language_bykey{$key};
                   3444: }
                   3445: 
                   3446: =pod
                   3447: 
1.648     raeburn  3448: =item * &copyrightids() 
1.112     bowersj2 3449: 
                   3450: returns list of all copyrights
                   3451: 
                   3452: =cut
                   3453: 
                   3454: sub copyrightids {
                   3455:     return sort(keys(%cprtag));
                   3456: }
                   3457: 
                   3458: =pod
                   3459: 
1.648     raeburn  3460: =item * &copyrightdescription() 
1.112     bowersj2 3461: 
                   3462: returns description of a specified copyright id
                   3463: 
                   3464: =cut
                   3465: 
                   3466: sub copyrightdescription {
1.166     www      3467:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3468: }
1.197     matthew  3469: 
                   3470: =pod
                   3471: 
1.648     raeburn  3472: =item * &source_copyrightids() 
1.192     taceyjo1 3473: 
                   3474: returns list of all source copyrights
                   3475: 
                   3476: =cut
                   3477: 
                   3478: sub source_copyrightids {
                   3479:     return sort(keys(%scprtag));
                   3480: }
                   3481: 
                   3482: =pod
                   3483: 
1.648     raeburn  3484: =item * &source_copyrightdescription() 
1.192     taceyjo1 3485: 
                   3486: returns description of a specified source copyright id
                   3487: 
                   3488: =cut
                   3489: 
                   3490: sub source_copyrightdescription {
                   3491:     return &mt($scprtag{shift(@_)});
                   3492: }
1.112     bowersj2 3493: 
                   3494: =pod
                   3495: 
1.648     raeburn  3496: =item * &filecategories() 
1.112     bowersj2 3497: 
                   3498: returns list of all file categories
                   3499: 
                   3500: =cut
                   3501: 
                   3502: sub filecategories {
                   3503:     return sort(keys(%category_extensions));
                   3504: }
                   3505: 
                   3506: =pod
                   3507: 
1.648     raeburn  3508: =item * &filecategorytypes() 
1.112     bowersj2 3509: 
                   3510: returns list of file types belonging to a given file
                   3511: category
                   3512: 
                   3513: =cut
                   3514: 
                   3515: sub filecategorytypes {
1.356     albertel 3516:     my ($cat) = @_;
                   3517:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3518: }
                   3519: 
                   3520: =pod
                   3521: 
1.648     raeburn  3522: =item * &fileembstyle() 
1.112     bowersj2 3523: 
                   3524: returns embedding style for a specified file type
                   3525: 
                   3526: =cut
                   3527: 
                   3528: sub fileembstyle {
                   3529:     return $fe{lc(shift(@_))};
1.169     www      3530: }
                   3531: 
1.351     www      3532: sub filemimetype {
                   3533:     return $fm{lc(shift(@_))};
                   3534: }
                   3535: 
1.169     www      3536: 
                   3537: sub filecategoryselect {
                   3538:     my ($name,$value)=@_;
1.189     matthew  3539:     return &select_form($value,$name,
1.970     raeburn  3540:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3541: }
                   3542: 
                   3543: =pod
                   3544: 
1.648     raeburn  3545: =item * &filedescription() 
1.112     bowersj2 3546: 
                   3547: returns description for a specified file type
                   3548: 
                   3549: =cut
                   3550: 
                   3551: sub filedescription {
1.188     matthew  3552:     my $file_description = $fd{lc(shift())};
                   3553:     $file_description =~ s:([\[\]]):~$1:g;
                   3554:     return &mt($file_description);
1.112     bowersj2 3555: }
                   3556: 
                   3557: =pod
                   3558: 
1.648     raeburn  3559: =item * &filedescriptionex() 
1.112     bowersj2 3560: 
                   3561: returns description for a specified file type with
                   3562: extra formatting
                   3563: 
                   3564: =cut
                   3565: 
                   3566: sub filedescriptionex {
                   3567:     my $ex=shift;
1.188     matthew  3568:     my $file_description = $fd{lc($ex)};
                   3569:     $file_description =~ s:([\[\]]):~$1:g;
                   3570:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3571: }
                   3572: 
                   3573: # End of .tab access
                   3574: =pod
                   3575: 
                   3576: =back
                   3577: 
                   3578: =cut
                   3579: 
                   3580: # ------------------------------------------------------------------ File Types
                   3581: sub fileextensions {
                   3582:     return sort(keys(%fe));
                   3583: }
                   3584: 
1.97      www      3585: # ----------------------------------------------------------- Display Languages
                   3586: # returns a hash with all desired display languages
                   3587: #
                   3588: 
                   3589: sub display_languages {
                   3590:     my %languages=();
1.695     raeburn  3591:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3592: 	$languages{$lang}=1;
1.97      www      3593:     }
                   3594:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3595:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3596: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3597: 	    $languages{$lang}=1;
1.97      www      3598:         }
                   3599:     }
                   3600:     return %languages;
1.14      harris41 3601: }
                   3602: 
1.582     albertel 3603: sub languages {
                   3604:     my ($possible_langs) = @_;
1.695     raeburn  3605:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3606:     if (!ref($possible_langs)) {
                   3607: 	if( wantarray ) {
                   3608: 	    return @preferred_langs;
                   3609: 	} else {
                   3610: 	    return $preferred_langs[0];
                   3611: 	}
                   3612:     }
                   3613:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3614:     my @preferred_possibilities;
                   3615:     foreach my $preferred_lang (@preferred_langs) {
                   3616: 	if (exists($possibilities{$preferred_lang})) {
                   3617: 	    push(@preferred_possibilities, $preferred_lang);
                   3618: 	}
                   3619:     }
                   3620:     if( wantarray ) {
                   3621: 	return @preferred_possibilities;
                   3622:     }
                   3623:     return $preferred_possibilities[0];
                   3624: }
                   3625: 
1.742     raeburn  3626: sub user_lang {
                   3627:     my ($touname,$toudom,$fromcid) = @_;
                   3628:     my @userlangs;
                   3629:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3630:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3631:                     $env{'course.'.$fromcid.'.languages'}));
                   3632:     } else {
                   3633:         my %langhash = &getlangs($touname,$toudom);
                   3634:         if ($langhash{'languages'} ne '') {
                   3635:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3636:         } else {
                   3637:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3638:             if ($domdefs{'lang_def'} ne '') {
                   3639:                 @userlangs = ($domdefs{'lang_def'});
                   3640:             }
                   3641:         }
                   3642:     }
                   3643:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3644:     my $user_lh = Apache::localize->get_handle(@languages);
                   3645:     return $user_lh;
                   3646: }
                   3647: 
                   3648: 
1.112     bowersj2 3649: ###############################################################
                   3650: ##               Student Answer Attempts                     ##
                   3651: ###############################################################
                   3652: 
                   3653: =pod
                   3654: 
                   3655: =head1 Alternate Problem Views
                   3656: 
                   3657: =over 4
                   3658: 
1.648     raeburn  3659: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3660:     $getattempt, $regexp, $gradesub)
                   3661: 
                   3662: Return string with previous attempt on problem. Arguments:
                   3663: 
                   3664: =over 4
                   3665: 
                   3666: =item * $symb: Problem, including path
                   3667: 
                   3668: =item * $username: username of the desired student
                   3669: 
                   3670: =item * $domain: domain of the desired student
1.14      harris41 3671: 
1.112     bowersj2 3672: =item * $course: Course ID
1.14      harris41 3673: 
1.112     bowersj2 3674: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3675:     something
1.14      harris41 3676: 
1.112     bowersj2 3677: =item * $regexp: if string matches this regexp, the string will be
                   3678:     sent to $gradesub
1.14      harris41 3679: 
1.112     bowersj2 3680: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3681: 
1.112     bowersj2 3682: =back
1.14      harris41 3683: 
1.112     bowersj2 3684: The output string is a table containing all desired attempts, if any.
1.16      harris41 3685: 
1.112     bowersj2 3686: =cut
1.1       albertel 3687: 
                   3688: sub get_previous_attempt {
1.43      ng       3689:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3690:   my $prevattempts='';
1.43      ng       3691:   no strict 'refs';
1.1       albertel 3692:   if ($symb) {
1.3       albertel 3693:     my (%returnhash)=
                   3694:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3695:     if ($returnhash{'version'}) {
                   3696:       my %lasthash=();
                   3697:       my $version;
                   3698:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3699:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3700: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3701:         }
1.1       albertel 3702:       }
1.596     albertel 3703:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3704:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3705:       my (%typeparts,%lasthidden);
1.945     raeburn  3706:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3707:       foreach my $key (sort(keys(%lasthash))) {
                   3708: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3709: 	if ($#parts > 0) {
1.31      albertel 3710: 	  my $data=$parts[-1];
1.989     raeburn  3711:           next if ($data eq 'foilorder');
1.31      albertel 3712: 	  pop(@parts);
1.1010    www      3713:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3714:           if ($data eq 'type') {
                   3715:               unless ($showsurv) {
                   3716:                   my $id = join(',',@parts);
                   3717:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3718:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3719:                       $lasthidden{$ign.'.'.$id} = 1;
                   3720:                   }
1.945     raeburn  3721:               }
1.1010    www      3722:           } 
1.31      albertel 3723: 	} else {
1.41      ng       3724: 	  if ($#parts == 0) {
                   3725: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3726: 	  } else {
                   3727: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3728: 	  }
1.31      albertel 3729: 	}
1.16      harris41 3730:       }
1.596     albertel 3731:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3732:       if ($getattempt eq '') {
                   3733: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3734:             my @hidden;
                   3735:             if (%typeparts) {
                   3736:                 foreach my $id (keys(%typeparts)) {
                   3737:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3738:                         push(@hidden,$id);
                   3739:                     }
                   3740:                 }
                   3741:             }
                   3742:             $prevattempts.=&start_data_table_row().
                   3743:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3744:             if (@hidden) {
                   3745:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3746:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3747:                     my $hide;
                   3748:                     foreach my $id (@hidden) {
                   3749:                         if ($key =~ /^\Q$id\E/) {
                   3750:                             $hide = 1;
                   3751:                             last;
                   3752:                         }
                   3753:                     }
                   3754:                     if ($hide) {
                   3755:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3756:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3757:                             my $value = &format_previous_attempt_value($key,
                   3758:                                              $returnhash{$version.':'.$key});
                   3759:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3760:                         } else {
                   3761:                             $prevattempts.='<td>&nbsp;</td>';
                   3762:                         }
                   3763:                     } else {
                   3764:                         if ($key =~ /\./) {
                   3765:                             my $value = &format_previous_attempt_value($key,
                   3766:                                               $returnhash{$version.':'.$key});
                   3767:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3768:                         } else {
                   3769:                             $prevattempts.='<td>&nbsp;</td>';
                   3770:                         }
                   3771:                     }
                   3772:                 }
                   3773:             } else {
                   3774: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3775:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3776: 		    my $value = &format_previous_attempt_value($key,
                   3777: 			            $returnhash{$version.':'.$key});
                   3778: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3779: 	        }
                   3780:             }
                   3781: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3782: 	 }
1.1       albertel 3783:       }
1.945     raeburn  3784:       my @currhidden = keys(%lasthidden);
1.596     albertel 3785:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3786:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3787:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3788:           if (%typeparts) {
                   3789:               my $hidden;
                   3790:               foreach my $id (@currhidden) {
                   3791:                   if ($key =~ /^\Q$id\E/) {
                   3792:                       $hidden = 1;
                   3793:                       last;
                   3794:                   }
                   3795:               }
                   3796:               if ($hidden) {
                   3797:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3798:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3799:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3800:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3801:                           $value = &$gradesub($value);
                   3802:                       }
                   3803:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3804:                   } else {
                   3805:                       $prevattempts.='<td>&nbsp;</td>';
                   3806:                   }
                   3807:               } else {
                   3808:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3809:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3810:                       $value = &$gradesub($value);
                   3811:                   }
                   3812:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3813:               }
                   3814:           } else {
                   3815: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3816: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3817:                   $value = &$gradesub($value);
                   3818:               }
                   3819: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3820:           }
1.16      harris41 3821:       }
1.596     albertel 3822:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3823:     } else {
1.596     albertel 3824:       $prevattempts=
                   3825: 	  &start_data_table().&start_data_table_row().
                   3826: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3827: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3828:     }
                   3829:   } else {
1.596     albertel 3830:     $prevattempts=
                   3831: 	  &start_data_table().&start_data_table_row().
                   3832: 	  '<td>'.&mt('No data.').'</td>'.
                   3833: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3834:   }
1.10      albertel 3835: }
                   3836: 
1.581     albertel 3837: sub format_previous_attempt_value {
                   3838:     my ($key,$value) = @_;
1.1011    www      3839:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3840: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3841:     } elsif (ref($value) eq 'ARRAY') {
                   3842: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3843:     } elsif ($key =~ /answerstring$/) {
                   3844:         my %answers = &Apache::lonnet::str2hash($value);
                   3845:         my @anskeys = sort(keys(%answers));
                   3846:         if (@anskeys == 1) {
                   3847:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3848:             if ($answer =~ m{\0}) {
                   3849:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3850:             }
                   3851:             my $tag_internal_answer_name = 'INTERNAL';
                   3852:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3853:                 $value = $answer; 
                   3854:             } else {
                   3855:                 $value = $anskeys[0].'='.$answer;
                   3856:             }
                   3857:         } else {
                   3858:             foreach my $ans (@anskeys) {
                   3859:                 my $answer = $answers{$ans};
1.1001    raeburn  3860:                 if ($answer =~ m{\0}) {
                   3861:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3862:                 }
                   3863:                 $value .=  $ans.'='.$answer.'<br />';;
                   3864:             } 
                   3865:         }
1.581     albertel 3866:     } else {
                   3867: 	$value = &unescape($value);
                   3868:     }
                   3869:     return $value;
                   3870: }
                   3871: 
                   3872: 
1.107     albertel 3873: sub relative_to_absolute {
                   3874:     my ($url,$output)=@_;
                   3875:     my $parser=HTML::TokeParser->new(\$output);
                   3876:     my $token;
                   3877:     my $thisdir=$url;
                   3878:     my @rlinks=();
                   3879:     while ($token=$parser->get_token) {
                   3880: 	if ($token->[0] eq 'S') {
                   3881: 	    if ($token->[1] eq 'a') {
                   3882: 		if ($token->[2]->{'href'}) {
                   3883: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3884: 		}
                   3885: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3886: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3887: 	    } elsif ($token->[1] eq 'base') {
                   3888: 		$thisdir=$token->[2]->{'href'};
                   3889: 	    }
                   3890: 	}
                   3891:     }
                   3892:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3893:     foreach my $link (@rlinks) {
1.726     raeburn  3894: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3895: 		($link=~/^\//) ||
                   3896: 		($link=~/^javascript:/i) ||
                   3897: 		($link=~/^mailto:/i) ||
                   3898: 		($link=~/^\#/)) {
                   3899: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3900: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3901: 	}
                   3902:     }
                   3903: # -------------------------------------------------- Deal with Applet codebases
                   3904:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3905:     return $output;
                   3906: }
                   3907: 
1.112     bowersj2 3908: =pod
                   3909: 
1.648     raeburn  3910: =item * &get_student_view()
1.112     bowersj2 3911: 
                   3912: show a snapshot of what student was looking at
                   3913: 
                   3914: =cut
                   3915: 
1.10      albertel 3916: sub get_student_view {
1.186     albertel 3917:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3918:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3919:   my (%form);
1.10      albertel 3920:   my @elements=('symb','courseid','domain','username');
                   3921:   foreach my $element (@elements) {
1.186     albertel 3922:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3923:   }
1.186     albertel 3924:   if (defined($moreenv)) {
                   3925:       %form=(%form,%{$moreenv});
                   3926:   }
1.236     albertel 3927:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3928:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3929:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3930:   $userview=~s/\<body[^\>]*\>//gi;
                   3931:   $userview=~s/\<\/body\>//gi;
                   3932:   $userview=~s/\<html\>//gi;
                   3933:   $userview=~s/\<\/html\>//gi;
                   3934:   $userview=~s/\<head\>//gi;
                   3935:   $userview=~s/\<\/head\>//gi;
                   3936:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3937:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3938:   if (wantarray) {
                   3939:      return ($userview,$response);
                   3940:   } else {
                   3941:      return $userview;
                   3942:   }
                   3943: }
                   3944: 
                   3945: sub get_student_view_with_retries {
                   3946:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3947: 
                   3948:     my $ok = 0;                 # True if we got a good response.
                   3949:     my $content;
                   3950:     my $response;
                   3951: 
                   3952:     # Try to get the student_view done. within the retries count:
                   3953:     
                   3954:     do {
                   3955:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3956:          $ok      = $response->is_success;
                   3957:          if (!$ok) {
                   3958:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3959:          }
                   3960:          $retries--;
                   3961:     } while (!$ok && ($retries > 0));
                   3962:     
                   3963:     if (!$ok) {
                   3964:        $content = '';          # On error return an empty content.
                   3965:     }
1.651     www      3966:     if (wantarray) {
                   3967:        return ($content, $response);
                   3968:     } else {
                   3969:        return $content;
                   3970:     }
1.11      albertel 3971: }
                   3972: 
1.112     bowersj2 3973: =pod
                   3974: 
1.648     raeburn  3975: =item * &get_student_answers() 
1.112     bowersj2 3976: 
                   3977: show a snapshot of how student was answering problem
                   3978: 
                   3979: =cut
                   3980: 
1.11      albertel 3981: sub get_student_answers {
1.100     sakharuk 3982:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3983:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3984:   my (%moreenv);
1.11      albertel 3985:   my @elements=('symb','courseid','domain','username');
                   3986:   foreach my $element (@elements) {
1.186     albertel 3987:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3988:   }
1.186     albertel 3989:   $moreenv{'grade_target'}='answer';
                   3990:   %moreenv=(%form,%moreenv);
1.497     raeburn  3991:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3992:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3993:   return $userview;
1.1       albertel 3994: }
1.116     albertel 3995: 
                   3996: =pod
                   3997: 
                   3998: =item * &submlink()
                   3999: 
1.242     albertel 4000: Inputs: $text $uname $udom $symb $target
1.116     albertel 4001: 
                   4002: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4003: 
                   4004: =cut
                   4005: 
                   4006: ###############################################
                   4007: sub submlink {
1.242     albertel 4008:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4009:     if (!($uname && $udom)) {
                   4010: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4011: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4012: 	if (!$symb) { $symb=$cursymb; }
                   4013:     }
1.254     matthew  4014:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4015:     $symb=&escape($symb);
1.960     bisitz   4016:     if ($target) { $target=" target=\"$target\""; }
                   4017:     return
                   4018:         '<a href="/adm/grades?command=submission'.
                   4019:         '&amp;symb='.$symb.
                   4020:         '&amp;student='.$uname.
                   4021:         '&amp;userdom='.$udom.'"'.
                   4022:         $target.'>'.$text.'</a>';
1.242     albertel 4023: }
                   4024: ##############################################
                   4025: 
                   4026: =pod
                   4027: 
                   4028: =item * &pgrdlink()
                   4029: 
                   4030: Inputs: $text $uname $udom $symb $target
                   4031: 
                   4032: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4033: 
                   4034: =cut
                   4035: 
                   4036: ###############################################
                   4037: sub pgrdlink {
                   4038:     my $link=&submlink(@_);
                   4039:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4040:     return $link;
                   4041: }
                   4042: ##############################################
                   4043: 
                   4044: =pod
                   4045: 
                   4046: =item * &pprmlink()
                   4047: 
                   4048: Inputs: $text $uname $udom $symb $target
                   4049: 
                   4050: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4051: student and a specific resource
1.242     albertel 4052: 
                   4053: =cut
                   4054: 
                   4055: ###############################################
                   4056: sub pprmlink {
                   4057:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4058:     if (!($uname && $udom)) {
                   4059: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4060: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4061: 	if (!$symb) { $symb=$cursymb; }
                   4062:     }
1.254     matthew  4063:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4064:     $symb=&escape($symb);
1.242     albertel 4065:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4066:     return '<a href="/adm/parmset?command=set&amp;'.
                   4067: 	'symb='.$symb.'&amp;uname='.$uname.
                   4068: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4069: }
                   4070: ##############################################
1.37      matthew  4071: 
1.112     bowersj2 4072: =pod
                   4073: 
                   4074: =back
                   4075: 
                   4076: =cut
                   4077: 
1.37      matthew  4078: ###############################################
1.51      www      4079: 
                   4080: 
                   4081: sub timehash {
1.687     raeburn  4082:     my ($thistime) = @_;
                   4083:     my $timezone = &Apache::lonlocal::gettimezone();
                   4084:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4085:                      ->set_time_zone($timezone);
                   4086:     my $wday = $dt->day_of_week();
                   4087:     if ($wday == 7) { $wday = 0; }
                   4088:     return ( 'second' => $dt->second(),
                   4089:              'minute' => $dt->minute(),
                   4090:              'hour'   => $dt->hour(),
                   4091:              'day'     => $dt->day_of_month(),
                   4092:              'month'   => $dt->month(),
                   4093:              'year'    => $dt->year(),
                   4094:              'weekday' => $wday,
                   4095:              'dayyear' => $dt->day_of_year(),
                   4096:              'dlsav'   => $dt->is_dst() );
1.51      www      4097: }
                   4098: 
1.370     www      4099: sub utc_string {
                   4100:     my ($date)=@_;
1.371     www      4101:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4102: }
                   4103: 
1.51      www      4104: sub maketime {
                   4105:     my %th=@_;
1.687     raeburn  4106:     my ($epoch_time,$timezone,$dt);
                   4107:     $timezone = &Apache::lonlocal::gettimezone();
                   4108:     eval {
                   4109:         $dt = DateTime->new( year   => $th{'year'},
                   4110:                              month  => $th{'month'},
                   4111:                              day    => $th{'day'},
                   4112:                              hour   => $th{'hour'},
                   4113:                              minute => $th{'minute'},
                   4114:                              second => $th{'second'},
                   4115:                              time_zone => $timezone,
                   4116:                          );
                   4117:     };
                   4118:     if (!$@) {
                   4119:         $epoch_time = $dt->epoch;
                   4120:         if ($epoch_time) {
                   4121:             return $epoch_time;
                   4122:         }
                   4123:     }
1.51      www      4124:     return POSIX::mktime(
                   4125:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4126:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4127: }
                   4128: 
                   4129: #########################################
1.51      www      4130: 
                   4131: sub findallcourses {
1.482     raeburn  4132:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4133:     my %roles;
                   4134:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4135:     my %courses;
1.51      www      4136:     my $now=time;
1.482     raeburn  4137:     if (!defined($uname)) {
                   4138:         $uname = $env{'user.name'};
                   4139:     }
                   4140:     if (!defined($udom)) {
                   4141:         $udom = $env{'user.domain'};
                   4142:     }
                   4143:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4144:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4145:         if (!%roles) {
                   4146:             %roles = (
                   4147:                        cc => 1,
1.907     raeburn  4148:                        co => 1,
1.482     raeburn  4149:                        in => 1,
                   4150:                        ep => 1,
                   4151:                        ta => 1,
                   4152:                        cr => 1,
                   4153:                        st => 1,
                   4154:              );
                   4155:         }
                   4156:         foreach my $entry (keys(%roleshash)) {
                   4157:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4158:             if ($trole =~ /^cr/) { 
                   4159:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4160:             } else {
                   4161:                 next if (!exists($roles{$trole}));
                   4162:             }
                   4163:             if ($tend) {
                   4164:                 next if ($tend < $now);
                   4165:             }
                   4166:             if ($tstart) {
                   4167:                 next if ($tstart > $now);
                   4168:             }
1.1058    raeburn  4169:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4170:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4171:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4172:             if ($secpart eq '') {
                   4173:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4174:                 $sec = 'none';
1.1058    raeburn  4175:                 $value .= $cnum.'/';
1.482     raeburn  4176:             } else {
                   4177:                 $cnum = $cnumpart;
                   4178:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4179:                 $value .= $cnum.'/'.$sec;
                   4180:             }
                   4181:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4182:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4183:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4184:                 }
                   4185:             } else {
                   4186:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4187:             }
1.482     raeburn  4188:         }
                   4189:     } else {
                   4190:         foreach my $key (keys(%env)) {
1.483     albertel 4191: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4192:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4193: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4194: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4195: 	        next if (%roles && !exists($roles{$role}));
                   4196: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4197:                 my $active=1;
                   4198:                 if ($starttime) {
                   4199: 		    if ($now<$starttime) { $active=0; }
                   4200:                 }
                   4201:                 if ($endtime) {
                   4202:                     if ($now>$endtime) { $active=0; }
                   4203:                 }
                   4204:                 if ($active) {
1.1058    raeburn  4205:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4206:                     if ($sec eq '') {
                   4207:                         $sec = 'none';
1.1058    raeburn  4208:                     } else {
                   4209:                         $value .= $sec;
                   4210:                     }
                   4211:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4212:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4213:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4214:                         }
                   4215:                     } else {
                   4216:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4217:                     }
1.474     raeburn  4218:                 }
                   4219:             }
1.51      www      4220:         }
                   4221:     }
1.474     raeburn  4222:     return %courses;
1.51      www      4223: }
1.37      matthew  4224: 
1.54      www      4225: ###############################################
1.474     raeburn  4226: 
                   4227: sub blockcheck {
1.1062    raeburn  4228:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4229: 
                   4230:     if (!defined($udom)) {
                   4231:         $udom = $env{'user.domain'};
                   4232:     }
                   4233:     if (!defined($uname)) {
                   4234:         $uname = $env{'user.name'};
                   4235:     }
                   4236: 
                   4237:     # If uname and udom are for a course, check for blocks in the course.
                   4238: 
                   4239:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4240:         my ($startblock,$endblock,$triggerblock) = 
                   4241:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4242:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4243:     }
1.474     raeburn  4244: 
1.502     raeburn  4245:     my $startblock = 0;
                   4246:     my $endblock = 0;
1.1062    raeburn  4247:     my $triggerblock = '';
1.482     raeburn  4248:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4249: 
1.490     raeburn  4250:     # If uname is for a user, and activity is course-specific, i.e.,
                   4251:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4252: 
1.490     raeburn  4253:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4254:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4255:         foreach my $key (keys(%live_courses)) {
                   4256:             if ($key ne $env{'request.course.id'}) {
                   4257:                 delete($live_courses{$key});
                   4258:             }
                   4259:         }
                   4260:     }
                   4261: 
                   4262:     my $otheruser = 0;
                   4263:     my %own_courses;
                   4264:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4265:         # Resource belongs to user other than current user.
                   4266:         $otheruser = 1;
                   4267:         # Gather courses for current user
                   4268:         %own_courses = 
                   4269:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4270:     }
                   4271: 
                   4272:     # Gather active course roles - course coordinator, instructor, 
                   4273:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4274: 
                   4275:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4276:         my ($cdom,$cnum);
                   4277:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4278:             $cdom = $env{'course.'.$course.'.domain'};
                   4279:             $cnum = $env{'course.'.$course.'.num'};
                   4280:         } else {
1.490     raeburn  4281:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4282:         }
                   4283:         my $no_ownblock = 0;
                   4284:         my $no_userblock = 0;
1.533     raeburn  4285:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4286:             # Check if current user has 'evb' priv for this
                   4287:             if (defined($own_courses{$course})) {
                   4288:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4289:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4290:                     if ($sec ne 'none') {
                   4291:                         $checkrole .= '/'.$sec;
                   4292:                     }
                   4293:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4294:                         $no_ownblock = 1;
                   4295:                         last;
                   4296:                     }
                   4297:                 }
                   4298:             }
                   4299:             # if they have 'evb' priv and are currently not playing student
                   4300:             next if (($no_ownblock) &&
                   4301:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4302:         }
1.474     raeburn  4303:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4304:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4305:             if ($sec ne 'none') {
1.482     raeburn  4306:                 $checkrole .= '/'.$sec;
1.474     raeburn  4307:             }
1.490     raeburn  4308:             if ($otheruser) {
                   4309:                 # Resource belongs to user other than current user.
                   4310:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4311:                 my (%allroles,%userroles);
                   4312:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4313:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4314:                         my ($trole,$tdom,$tnum,$tsec);
                   4315:                         if ($entry =~ /^cr/) {
                   4316:                             ($trole,$tdom,$tnum,$tsec) = 
                   4317:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4318:                         } else {
                   4319:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4320:                         }
                   4321:                         my ($spec,$area,$trest);
                   4322:                         $area = '/'.$tdom.'/'.$tnum;
                   4323:                         $trest = $tnum;
                   4324:                         if ($tsec ne '') {
                   4325:                             $area .= '/'.$tsec;
                   4326:                             $trest .= '/'.$tsec;
                   4327:                         }
                   4328:                         $spec = $trole.'.'.$area;
                   4329:                         if ($trole =~ /^cr/) {
                   4330:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4331:                                                               $tdom,$spec,$trest,$area);
                   4332:                         } else {
                   4333:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4334:                                                                 $tdom,$spec,$trest,$area);
                   4335:                         }
                   4336:                     }
                   4337:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4338:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4339:                         if ($1) {
                   4340:                             $no_userblock = 1;
                   4341:                             last;
                   4342:                         }
1.486     raeburn  4343:                     }
                   4344:                 }
1.490     raeburn  4345:             } else {
                   4346:                 # Resource belongs to current user
                   4347:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4348:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4349:                     $no_ownblock = 1;
                   4350:                     last;
                   4351:                 }
1.474     raeburn  4352:             }
                   4353:         }
                   4354:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4355:         next if (($no_ownblock) &&
1.491     albertel 4356:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4357:         next if ($no_userblock);
1.474     raeburn  4358: 
1.866     kalberla 4359:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4360:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4361:         
1.1062    raeburn  4362:         my ($start,$end,$trigger) = 
                   4363:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4364:         if (($start != 0) && 
                   4365:             (($startblock == 0) || ($startblock > $start))) {
                   4366:             $startblock = $start;
1.1062    raeburn  4367:             if ($trigger ne '') {
                   4368:                 $triggerblock = $trigger;
                   4369:             }
1.502     raeburn  4370:         }
                   4371:         if (($end != 0)  &&
                   4372:             (($endblock == 0) || ($endblock < $end))) {
                   4373:             $endblock = $end;
1.1062    raeburn  4374:             if ($trigger ne '') {
                   4375:                 $triggerblock = $trigger;
                   4376:             }
1.502     raeburn  4377:         }
1.490     raeburn  4378:     }
1.1062    raeburn  4379:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4380: }
                   4381: 
                   4382: sub get_blocks {
1.1062    raeburn  4383:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4384:     my $startblock = 0;
                   4385:     my $endblock = 0;
1.1062    raeburn  4386:     my $triggerblock = '';
1.490     raeburn  4387:     my $course = $cdom.'_'.$cnum;
                   4388:     $setters->{$course} = {};
                   4389:     $setters->{$course}{'staff'} = [];
                   4390:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4391:     $setters->{$course}{'triggers'} = [];
                   4392:     my (@blockers,%triggered);
                   4393:     my $now = time;
                   4394:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4395:     if ($activity eq 'docs') {
                   4396:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4397:         foreach my $block (@blockers) {
                   4398:             if ($block =~ /^firstaccess____(.+)$/) {
                   4399:                 my $item = $1;
                   4400:                 my $type = 'map';
                   4401:                 my $timersymb = $item;
                   4402:                 if ($item eq 'course') {
                   4403:                     $type = 'course';
                   4404:                 } elsif ($item =~ /___\d+___/) {
                   4405:                     $type = 'resource';
                   4406:                 } else {
                   4407:                     $timersymb = &Apache::lonnet::symbread($item);
                   4408:                 }
                   4409:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4410:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4411:                 $triggered{$block} = {
                   4412:                                        start => $start,
                   4413:                                        end   => $end,
                   4414:                                        type  => $type,
                   4415:                                      };
                   4416:             }
                   4417:         }
                   4418:     } else {
                   4419:         foreach my $block (keys(%commblocks)) {
                   4420:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4421:                 my ($start,$end) = ($1,$2);
                   4422:                 if ($start <= time && $end >= time) {
                   4423:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4424:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4425:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4426:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4427:                                     push(@blockers,$block);
                   4428:                                 }
                   4429:                             }
                   4430:                         }
                   4431:                     }
                   4432:                 }
                   4433:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4434:                 my $item = $1;
                   4435:                 my $timersymb = $item; 
                   4436:                 my $type = 'map';
                   4437:                 if ($item eq 'course') {
                   4438:                     $type = 'course';
                   4439:                 } elsif ($item =~ /___\d+___/) {
                   4440:                     $type = 'resource';
                   4441:                 } else {
                   4442:                     $timersymb = &Apache::lonnet::symbread($item);
                   4443:                 }
                   4444:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4445:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4446:                 if ($start && $end) {
                   4447:                     if (($start <= time) && ($end >= time)) {
                   4448:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4449:                             push(@blockers,$block);
                   4450:                             $triggered{$block} = {
                   4451:                                                    start => $start,
                   4452:                                                    end   => $end,
                   4453:                                                    type  => $type,
                   4454:                                                  };
                   4455:                         }
                   4456:                     }
1.490     raeburn  4457:                 }
1.1062    raeburn  4458:             }
                   4459:         }
                   4460:     }
                   4461:     foreach my $blocker (@blockers) {
                   4462:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4463:             &parse_block_record($commblocks{$blocker});
                   4464:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4465:         my ($start,$end,$triggertype);
                   4466:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4467:             ($start,$end) = ($1,$2);
                   4468:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4469:             $start = $triggered{$blocker}{'start'};
                   4470:             $end = $triggered{$blocker}{'end'};
                   4471:             $triggertype = $triggered{$blocker}{'type'};
                   4472:         }
                   4473:         if ($start) {
                   4474:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4475:             if ($triggertype) {
                   4476:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4477:             } else {
                   4478:                 push(@{$$setters{$course}{'triggers'}},0);
                   4479:             }
                   4480:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4481:                 $startblock = $start;
                   4482:                 if ($triggertype) {
                   4483:                     $triggerblock = $blocker;
1.474     raeburn  4484:                 }
                   4485:             }
1.1062    raeburn  4486:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4487:                $endblock = $end;
                   4488:                if ($triggertype) {
                   4489:                    $triggerblock = $blocker;
                   4490:                }
                   4491:             }
1.474     raeburn  4492:         }
                   4493:     }
1.1062    raeburn  4494:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4495: }
                   4496: 
                   4497: sub parse_block_record {
                   4498:     my ($record) = @_;
                   4499:     my ($setuname,$setudom,$title,$blocks);
                   4500:     if (ref($record) eq 'HASH') {
                   4501:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4502:         $title = &unescape($record->{'event'});
                   4503:         $blocks = $record->{'blocks'};
                   4504:     } else {
                   4505:         my @data = split(/:/,$record,3);
                   4506:         if (scalar(@data) eq 2) {
                   4507:             $title = $data[1];
                   4508:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4509:         } else {
                   4510:             ($setuname,$setudom,$title) = @data;
                   4511:         }
                   4512:         $blocks = { 'com' => 'on' };
                   4513:     }
                   4514:     return ($setuname,$setudom,$title,$blocks);
                   4515: }
                   4516: 
1.854     kalberla 4517: sub blocking_status {
1.1062    raeburn  4518:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4519:     my %setters;
1.890     droeschl 4520: 
1.1061    raeburn  4521: # check for active blocking
1.1062    raeburn  4522:     my ($startblock,$endblock,$triggerblock) = 
                   4523:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4524:     my $blocked = 0;
                   4525:     if ($startblock && $endblock) {
                   4526:         $blocked = 1;
                   4527:     }
1.890     droeschl 4528: 
1.1061    raeburn  4529: # caller just wants to know whether a block is active
                   4530:     if (!wantarray) { return $blocked; }
                   4531: 
                   4532: # build a link to a popup window containing the details
                   4533:     my $querystring  = "?activity=$activity";
                   4534: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4535:     if ($activity eq 'port') {
                   4536:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4537:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4538:     } elsif ($activity eq 'docs') {
                   4539:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4540:     }
1.1061    raeburn  4541: 
                   4542:     my $output .= <<'END_MYBLOCK';
                   4543: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4544:     var options = "width=" + w + ",height=" + h + ",";
                   4545:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4546:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4547:     var newWin = window.open(url, wdwName, options);
                   4548:     newWin.focus();
                   4549: }
1.890     droeschl 4550: END_MYBLOCK
1.854     kalberla 4551: 
1.1061    raeburn  4552:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4553:   
1.1061    raeburn  4554:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4555:     my $text = &mt('Communication Blocked');
                   4556:     if ($activity eq 'docs') {
                   4557:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4558:     } elsif ($activity eq 'printout') {
                   4559:         $text = &mt('Printing Blocked');
1.1062    raeburn  4560:     }
1.1061    raeburn  4561:     $output .= <<"END_BLOCK";
1.867     kalberla 4562: <div class='LC_comblock'>
1.869     kalberla 4563:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4564:   title='$text'>
                   4565:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4566:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4567:   title='$text'>$text</a>
1.867     kalberla 4568: </div>
                   4569: 
                   4570: END_BLOCK
1.474     raeburn  4571: 
1.1061    raeburn  4572:     return ($blocked, $output);
1.854     kalberla 4573: }
1.490     raeburn  4574: 
1.60      matthew  4575: ###############################################
                   4576: 
1.682     raeburn  4577: sub check_ip_acc {
                   4578:     my ($acc)=@_;
                   4579:     &Apache::lonxml::debug("acc is $acc");
                   4580:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4581:         return 1;
                   4582:     }
                   4583:     my $allowed=0;
                   4584:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4585: 
                   4586:     my $name;
                   4587:     foreach my $pattern (split(',',$acc)) {
                   4588:         $pattern =~ s/^\s*//;
                   4589:         $pattern =~ s/\s*$//;
                   4590:         if ($pattern =~ /\*$/) {
                   4591:             #35.8.*
                   4592:             $pattern=~s/\*//;
                   4593:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4594:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4595:             #35.8.3.[34-56]
                   4596:             my $low=$2;
                   4597:             my $high=$3;
                   4598:             $pattern=$1;
                   4599:             if ($ip =~ /^\Q$pattern\E/) {
                   4600:                 my $last=(split(/\./,$ip))[3];
                   4601:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4602:             }
                   4603:         } elsif ($pattern =~ /^\*/) {
                   4604:             #*.msu.edu
                   4605:             $pattern=~s/\*//;
                   4606:             if (!defined($name)) {
                   4607:                 use Socket;
                   4608:                 my $netaddr=inet_aton($ip);
                   4609:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4610:             }
                   4611:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4612:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4613:             #127.0.0.1
                   4614:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4615:         } else {
                   4616:             #some.name.com
                   4617:             if (!defined($name)) {
                   4618:                 use Socket;
                   4619:                 my $netaddr=inet_aton($ip);
                   4620:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4621:             }
                   4622:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4623:         }
                   4624:         if ($allowed) { last; }
                   4625:     }
                   4626:     return $allowed;
                   4627: }
                   4628: 
                   4629: ###############################################
                   4630: 
1.60      matthew  4631: =pod
                   4632: 
1.112     bowersj2 4633: =head1 Domain Template Functions
                   4634: 
                   4635: =over 4
                   4636: 
                   4637: =item * &determinedomain()
1.60      matthew  4638: 
                   4639: Inputs: $domain (usually will be undef)
                   4640: 
1.63      www      4641: Returns: Determines which domain should be used for designs
1.60      matthew  4642: 
                   4643: =cut
1.54      www      4644: 
1.60      matthew  4645: ###############################################
1.63      www      4646: sub determinedomain {
                   4647:     my $domain=shift;
1.531     albertel 4648:     if (! $domain) {
1.60      matthew  4649:         # Determine domain if we have not been given one
1.893     raeburn  4650:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4651:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4652:         if ($env{'request.role.domain'}) { 
                   4653:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4654:         }
                   4655:     }
1.63      www      4656:     return $domain;
                   4657: }
                   4658: ###############################################
1.517     raeburn  4659: 
1.518     albertel 4660: sub devalidate_domconfig_cache {
                   4661:     my ($udom)=@_;
                   4662:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4663: }
                   4664: 
                   4665: # ---------------------- Get domain configuration for a domain
                   4666: sub get_domainconf {
                   4667:     my ($udom) = @_;
                   4668:     my $cachetime=1800;
                   4669:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4670:     if (defined($cached)) { return %{$result}; }
                   4671: 
                   4672:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4673: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4674:     my (%designhash,%legacy);
1.518     albertel 4675:     if (keys(%domconfig) > 0) {
                   4676:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4677:             if (keys(%{$domconfig{'login'}})) {
                   4678:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4679:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4680:                         if ($key eq 'loginvia') {
                   4681:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4682:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4683:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4684:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4685:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4686:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4687:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4688: 
                   4689:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4690:                                             } else {
1.1013    raeburn  4691:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4692:                                             }
                   4693:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4694:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4695:                                             }
1.946     raeburn  4696:                                         }
                   4697:                                     }
                   4698:                                 }
                   4699:                             }
                   4700:                         } else {
                   4701:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4702:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4703:                                     $domconfig{'login'}{$key}{$img};
                   4704:                             }
1.699     raeburn  4705:                         }
                   4706:                     } else {
                   4707:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4708:                     }
1.632     raeburn  4709:                 }
                   4710:             } else {
                   4711:                 $legacy{'login'} = 1;
1.518     albertel 4712:             }
1.632     raeburn  4713:         } else {
                   4714:             $legacy{'login'} = 1;
1.518     albertel 4715:         }
                   4716:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4717:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4718:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4719:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4720:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4721:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4722:                         }
1.518     albertel 4723:                     }
                   4724:                 }
1.632     raeburn  4725:             } else {
                   4726:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4727:             }
1.632     raeburn  4728:         } else {
                   4729:             $legacy{'rolecolors'} = 1;
1.518     albertel 4730:         }
1.948     raeburn  4731:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4732:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4733:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4734:             }
                   4735:         }
1.632     raeburn  4736:         if (keys(%legacy) > 0) {
                   4737:             my %legacyhash = &get_legacy_domconf($udom);
                   4738:             foreach my $item (keys(%legacyhash)) {
                   4739:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4740:                     if ($legacy{'login'}) { 
                   4741:                         $designhash{$item} = $legacyhash{$item};
                   4742:                     }
                   4743:                 } else {
                   4744:                     if ($legacy{'rolecolors'}) {
                   4745:                         $designhash{$item} = $legacyhash{$item};
                   4746:                     }
1.518     albertel 4747:                 }
                   4748:             }
                   4749:         }
1.632     raeburn  4750:     } else {
                   4751:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4752:     }
                   4753:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4754: 				  $cachetime);
                   4755:     return %designhash;
                   4756: }
                   4757: 
1.632     raeburn  4758: sub get_legacy_domconf {
                   4759:     my ($udom) = @_;
                   4760:     my %legacyhash;
                   4761:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4762:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4763:     if (-e $designfile) {
                   4764:         if ( open (my $fh,"<$designfile") ) {
                   4765:             while (my $line = <$fh>) {
                   4766:                 next if ($line =~ /^\#/);
                   4767:                 chomp($line);
                   4768:                 my ($key,$val)=(split(/\=/,$line));
                   4769:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4770:             }
                   4771:             close($fh);
                   4772:         }
                   4773:     }
1.1026    raeburn  4774:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4775:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4776:     }
                   4777:     return %legacyhash;
                   4778: }
                   4779: 
1.63      www      4780: =pod
                   4781: 
1.112     bowersj2 4782: =item * &domainlogo()
1.63      www      4783: 
                   4784: Inputs: $domain (usually will be undef)
                   4785: 
                   4786: Returns: A link to a domain logo, if the domain logo exists.
                   4787: If the domain logo does not exist, a description of the domain.
                   4788: 
                   4789: =cut
1.112     bowersj2 4790: 
1.63      www      4791: ###############################################
                   4792: sub domainlogo {
1.517     raeburn  4793:     my $domain = &determinedomain(shift);
1.518     albertel 4794:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4795:     # See if there is a logo
                   4796:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4797:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4798:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4799: 	    if ($imgsrc =~ m{^/res/}) {
                   4800: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4801: 		&Apache::lonnet::repcopy($local_name);
                   4802: 	    }
                   4803: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4804:         } 
                   4805:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4806:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4807:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4808:     } else {
1.60      matthew  4809:         return '';
1.59      www      4810:     }
                   4811: }
1.63      www      4812: ##############################################
                   4813: 
                   4814: =pod
                   4815: 
1.112     bowersj2 4816: =item * &designparm()
1.63      www      4817: 
                   4818: Inputs: $which parameter; $domain (usually will be undef)
                   4819: 
                   4820: Returns: value of designparamter $which
                   4821: 
                   4822: =cut
1.112     bowersj2 4823: 
1.397     albertel 4824: 
1.400     albertel 4825: ##############################################
1.397     albertel 4826: sub designparm {
                   4827:     my ($which,$domain)=@_;
                   4828:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4829:         return $env{'environment.color.'.$which};
1.96      www      4830:     }
1.63      www      4831:     $domain=&determinedomain($domain);
1.1016    raeburn  4832:     my %domdesign;
                   4833:     unless ($domain eq 'public') {
                   4834:         %domdesign = &get_domainconf($domain);
                   4835:     }
1.520     raeburn  4836:     my $output;
1.517     raeburn  4837:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4838:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4839:     } else {
1.520     raeburn  4840:         $output = $defaultdesign{$which};
                   4841:     }
                   4842:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4843:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4844:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4845:             if ($output =~ m{^/res/}) {
                   4846:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4847:                 &Apache::lonnet::repcopy($local_name);
                   4848:             }
1.520     raeburn  4849:             $output = &lonhttpdurl($output);
                   4850:         }
1.63      www      4851:     }
1.520     raeburn  4852:     return $output;
1.63      www      4853: }
1.59      www      4854: 
1.822     bisitz   4855: ##############################################
                   4856: =pod
                   4857: 
1.832     bisitz   4858: =item * &authorspace()
                   4859: 
1.1028    raeburn  4860: Inputs: $url (usually will be undef).
1.832     bisitz   4861: 
1.1075.2.40  raeburn  4862: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4863:          directory being viewed (or for which action is being taken). 
                   4864:          If $url is provided, and begins /priv/<domain>/<uname>
                   4865:          the path will be that portion of the $context argument.
                   4866:          Otherwise the path will be for the author space of the current
                   4867:          user when the current role is author, or for that of the 
                   4868:          co-author/assistant co-author space when the current role 
                   4869:          is co-author or assistant co-author.
1.832     bisitz   4870: 
                   4871: =cut
                   4872: 
                   4873: sub authorspace {
1.1028    raeburn  4874:     my ($url) = @_;
                   4875:     if ($url ne '') {
                   4876:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4877:            return $1;
                   4878:         }
                   4879:     }
1.832     bisitz   4880:     my $caname = '';
1.1024    www      4881:     my $cadom = '';
1.1028    raeburn  4882:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4883:         ($cadom,$caname) =
1.832     bisitz   4884:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4885:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4886:         $caname = $env{'user.name'};
1.1024    www      4887:         $cadom = $env{'user.domain'};
1.832     bisitz   4888:     }
1.1028    raeburn  4889:     if (($caname ne '') && ($cadom ne '')) {
                   4890:         return "/priv/$cadom/$caname/";
                   4891:     }
                   4892:     return;
1.832     bisitz   4893: }
                   4894: 
                   4895: ##############################################
                   4896: =pod
                   4897: 
1.822     bisitz   4898: =item * &head_subbox()
                   4899: 
                   4900: Inputs: $content (contains HTML code with page functions, etc.)
                   4901: 
                   4902: Returns: HTML div with $content
                   4903:          To be included in page header
                   4904: 
                   4905: =cut
                   4906: 
                   4907: sub head_subbox {
                   4908:     my ($content)=@_;
                   4909:     my $output =
1.993     raeburn  4910:         '<div class="LC_head_subbox">'
1.822     bisitz   4911:        .$content
                   4912:        .'</div>'
                   4913: }
                   4914: 
                   4915: ##############################################
                   4916: =pod
                   4917: 
                   4918: =item * &CSTR_pageheader()
                   4919: 
1.1026    raeburn  4920: Input: (optional) filename from which breadcrumb trail is built.
                   4921:        In most cases no input as needed, as $env{'request.filename'}
                   4922:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4923: 
                   4924: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  4925:          To be included on Authoring Space pages
1.822     bisitz   4926: 
                   4927: =cut
                   4928: 
                   4929: sub CSTR_pageheader {
1.1026    raeburn  4930:     my ($trailfile) = @_;
                   4931:     if ($trailfile eq '') {
                   4932:         $trailfile = $env{'request.filename'};
                   4933:     }
                   4934: 
                   4935: # this is for resources; directories have customtitle, and crumbs
                   4936: # and select recent are created in lonpubdir.pm
                   4937: 
                   4938:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4939:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  4940:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  4941:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4942:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4943: 
                   4944:     my $parentpath = '';
                   4945:     my $lastitem = '';
                   4946:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4947:         $parentpath = $1;
                   4948:         $lastitem = $2;
                   4949:     } else {
                   4950:         $lastitem = $thisdisfn;
                   4951:     }
1.921     bisitz   4952: 
                   4953:     my $output =
1.822     bisitz   4954:          '<div>'
                   4955:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  4956:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   4957:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   4958:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      4959:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   4960: 
                   4961:     if ($lastitem) {
                   4962:         $output .=
                   4963:              '<span class="LC_filename">'
                   4964:             .$lastitem
                   4965:             .'</span>';
                   4966:     }
                   4967:     $output .=
                   4968:          '<br />'
1.822     bisitz   4969:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   4970:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4971:         .'</form>'
                   4972:         .&Apache::lonmenu::constspaceform()
                   4973:         .'</div>';
1.921     bisitz   4974: 
                   4975:     return $output;
1.822     bisitz   4976: }
                   4977: 
1.60      matthew  4978: ###############################################
                   4979: ###############################################
                   4980: 
                   4981: =pod
                   4982: 
1.112     bowersj2 4983: =back
                   4984: 
1.549     albertel 4985: =head1 HTML Helpers
1.112     bowersj2 4986: 
                   4987: =over 4
                   4988: 
                   4989: =item * &bodytag()
1.60      matthew  4990: 
                   4991: Returns a uniform header for LON-CAPA web pages.
                   4992: 
                   4993: Inputs: 
                   4994: 
1.112     bowersj2 4995: =over 4
                   4996: 
                   4997: =item * $title, A title to be displayed on the page.
                   4998: 
                   4999: =item * $function, the current role (can be undef).
                   5000: 
                   5001: =item * $addentries, extra parameters for the <body> tag.
                   5002: 
                   5003: =item * $bodyonly, if defined, only return the <body> tag.
                   5004: 
                   5005: =item * $domain, if defined, force a given domain.
                   5006: 
                   5007: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5008:             text interface only)
1.60      matthew  5009: 
1.814     bisitz   5010: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5011:                      navigational links
1.317     albertel 5012: 
1.338     albertel 5013: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5014: 
1.1075.2.12  raeburn  5015: =item * $no_inline_link, if true and in remote mode, don't show the
                   5016:          'Switch To Inline Menu' link
                   5017: 
1.460     albertel 5018: =item * $args, optional argument valid values are
                   5019:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5020:             inherit_jsmath -> when creating popup window in a page,
                   5021:                               should it have jsmath forced on by the
                   5022:                               current page
1.460     albertel 5023: 
1.1075.2.15  raeburn  5024: =item * $advtoolsref, optional argument, ref to an array containing
                   5025:             inlineremote items to be added in "Functions" menu below
                   5026:             breadcrumbs.
                   5027: 
1.112     bowersj2 5028: =back
                   5029: 
1.60      matthew  5030: Returns: A uniform header for LON-CAPA web pages.  
                   5031: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5032: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5033: other decorations will be returned.
                   5034: 
                   5035: =cut
                   5036: 
1.54      www      5037: sub bodytag {
1.831     bisitz   5038:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5039:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5040: 
1.954     raeburn  5041:     my $public;
                   5042:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5043:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5044:         $public = 1;
                   5045:     }
1.460     albertel 5046:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5047:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5048: 
1.183     matthew  5049:     $function = &get_users_function() if (!$function);
1.339     albertel 5050:     my $img =    &designparm($function.'.img',$domain);
                   5051:     my $font =   &designparm($function.'.font',$domain);
                   5052:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5053: 
1.803     bisitz   5054:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5055: 		   'bgcolor' => $pgbg,
1.339     albertel 5056: 		   'text'    => $font,
                   5057:                    'alink'   => &designparm($function.'.alink',$domain),
                   5058: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5059: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5060:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5061: 
1.63      www      5062:  # role and realm
1.378     raeburn  5063:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5064:     if ($role  eq 'ca') {
1.479     albertel 5065:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5066:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5067:     } 
1.55      www      5068: # realm
1.258     albertel 5069:     if ($env{'request.course.id'}) {
1.378     raeburn  5070:         if ($env{'request.role'} !~ /^cr/) {
                   5071:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5072:         }
1.898     raeburn  5073:         if ($env{'request.course.sec'}) {
                   5074:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5075:         }   
1.359     albertel 5076: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5077:     } else {
                   5078:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5079:     }
1.433     albertel 5080: 
1.359     albertel 5081:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5082: 
1.438     albertel 5083:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5084: 
1.101     www      5085: # construct main body tag
1.359     albertel 5086:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5087: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5088: 
1.1075.2.38  raeburn  5089:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5090: 
                   5091:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5092:         return $bodytag;
1.1075.2.38  raeburn  5093:     }
1.359     albertel 5094: 
1.954     raeburn  5095:     if ($public) {
1.433     albertel 5096: 	undef($role);
                   5097:     }
1.359     albertel 5098:     
1.762     bisitz   5099:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5100:     #
                   5101:     # Extra info if you are the DC
                   5102:     my $dc_info = '';
                   5103:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5104:                         $env{'course.'.$env{'request.course.id'}.
                   5105:                                  '.domain'}.'/'})) {
                   5106:         my $cid = $env{'request.course.id'};
1.917     raeburn  5107:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5108:         $dc_info =~ s/\s+$//;
1.359     albertel 5109:     }
                   5110: 
1.898     raeburn  5111:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5112: 
1.1075.2.13  raeburn  5113:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5114: 
1.1075.2.38  raeburn  5115: 
                   5116: 
1.1075.2.21  raeburn  5117:     my $funclist;
                   5118:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5119:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5120:                     Apache::lonmenu::serverform();
                   5121:         my $forbodytag;
                   5122:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5123:                                             $forcereg,$args->{'group'},
                   5124:                                             $args->{'bread_crumbs'},
                   5125:                                             $advtoolsref,'',\$forbodytag);
                   5126:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5127:             $funclist = $forbodytag;
                   5128:         }
                   5129:     } else {
1.903     droeschl 5130: 
                   5131:         #    if ($env{'request.state'} eq 'construct') {
                   5132:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5133:         #    }
                   5134: 
1.1075.2.38  raeburn  5135:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5136:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5137: 
1.1075.2.38  raeburn  5138:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5139: 
1.916     droeschl 5140:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5141:             if ($dc_info) {
                   5142:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5143:             }
1.1075.2.38  raeburn  5144:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5145:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5146:             return $bodytag;
                   5147:         }
1.894     droeschl 5148: 
1.927     raeburn  5149:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5150:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5151:         }
1.916     droeschl 5152: 
1.1075.2.38  raeburn  5153:         $bodytag .= $right;
1.852     droeschl 5154: 
1.917     raeburn  5155:         if ($dc_info) {
                   5156:             $dc_info = &dc_courseid_toggle($dc_info);
                   5157:         }
                   5158:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5159: 
1.903     droeschl 5160:         #don't show menus for public users
1.954     raeburn  5161:         if (!$public){
1.1075.2.52  raeburn  5162:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5163:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5164:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5165:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5166:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5167:                                 $args->{'bread_crumbs'});
                   5168:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5169:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5170:                                                             $args->{'group'});
1.1075.2.15  raeburn  5171:             } else {
1.1075.2.21  raeburn  5172:                 my $forbodytag;
                   5173:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5174:                                                     $forcereg,$args->{'group'},
                   5175:                                                     $args->{'bread_crumbs'},
                   5176:                                                     $advtoolsref,'',\$forbodytag);
                   5177:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5178:                     $bodytag .= $forbodytag;
                   5179:                 }
1.920     raeburn  5180:             }
1.903     droeschl 5181:         }else{
                   5182:             # this is to seperate menu from content when there's no secondary
                   5183:             # menu. Especially needed for public accessible ressources.
                   5184:             $bodytag .= '<hr style="clear:both" />';
                   5185:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5186:         }
1.903     droeschl 5187: 
1.235     raeburn  5188:         return $bodytag;
1.1075.2.12  raeburn  5189:     }
                   5190: 
                   5191: #
                   5192: # Top frame rendering, Remote is up
                   5193: #
                   5194: 
                   5195:     my $imgsrc = $img;
                   5196:     if ($img =~ /^\/adm/) {
                   5197:         $imgsrc = &lonhttpdurl($img);
                   5198:     }
                   5199:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5200: 
1.1075.2.60! raeburn  5201:     my $help=($no_inline_link?''
        !          5202:               :&Apache::loncommon::top_nav_help('Help'));
        !          5203: 
1.1075.2.12  raeburn  5204:     # Explicit link to get inline menu
                   5205:     my $menu= ($no_inline_link?''
                   5206:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5207: 
                   5208:     if ($dc_info) {
                   5209:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5210:     }
                   5211: 
1.1075.2.38  raeburn  5212:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5213:     unless ($public) {
                   5214:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5215:                                 undef,'LC_menubuttons_link');
                   5216:     }
                   5217: 
1.1075.2.12  raeburn  5218:     unless ($env{'form.inhibitmenu'}) {
                   5219:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5220:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60! raeburn  5221:                        <li>$help</li>
1.1075.2.12  raeburn  5222:                        <li>$menu</li>
                   5223:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5224:     }
1.1075.2.13  raeburn  5225:     if ($env{'request.state'} eq 'construct') {
                   5226:         if (!$public){
                   5227:             if ($env{'request.state'} eq 'construct') {
                   5228:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5229:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5230:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5231:                             &Apache::lonmenu::innerregister($forcereg,
                   5232:                                                             $args->{'bread_crumbs'});
                   5233:             }
                   5234:         }
                   5235:     }
1.1075.2.21  raeburn  5236:     return $bodytag."\n".$funclist;
1.182     matthew  5237: }
                   5238: 
1.917     raeburn  5239: sub dc_courseid_toggle {
                   5240:     my ($dc_info) = @_;
1.980     raeburn  5241:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5242:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5243:            &mt('(More ...)').'</a></span>'.
                   5244:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5245: }
                   5246: 
1.330     albertel 5247: sub make_attr_string {
                   5248:     my ($register,$attr_ref) = @_;
                   5249: 
                   5250:     if ($attr_ref && !ref($attr_ref)) {
                   5251: 	die("addentries Must be a hash ref ".
                   5252: 	    join(':',caller(1))." ".
                   5253: 	    join(':',caller(0))." ");
                   5254:     }
                   5255: 
                   5256:     if ($register) {
1.339     albertel 5257: 	my ($on_load,$on_unload);
                   5258: 	foreach my $key (keys(%{$attr_ref})) {
                   5259: 	    if      (lc($key) eq 'onload') {
                   5260: 		$on_load.=$attr_ref->{$key}.';';
                   5261: 		delete($attr_ref->{$key});
                   5262: 
                   5263: 	    } elsif (lc($key) eq 'onunload') {
                   5264: 		$on_unload.=$attr_ref->{$key}.';';
                   5265: 		delete($attr_ref->{$key});
                   5266: 	    }
                   5267: 	}
1.1075.2.12  raeburn  5268:         if ($env{'environment.remote'} eq 'on') {
                   5269:             $attr_ref->{'onload'}  =
                   5270:                 &Apache::lonmenu::loadevents().  $on_load;
                   5271:             $attr_ref->{'onunload'}=
                   5272:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5273:         } else {  
                   5274: 	    $attr_ref->{'onload'}  = $on_load;
                   5275: 	    $attr_ref->{'onunload'}= $on_unload;
                   5276:         }
1.330     albertel 5277:     }
1.339     albertel 5278: 
1.330     albertel 5279:     my $attr_string;
1.1075.2.56  raeburn  5280:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5281: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5282:     }
                   5283:     return $attr_string;
                   5284: }
                   5285: 
                   5286: 
1.182     matthew  5287: ###############################################
1.251     albertel 5288: ###############################################
                   5289: 
                   5290: =pod
                   5291: 
                   5292: =item * &endbodytag()
                   5293: 
                   5294: Returns a uniform footer for LON-CAPA web pages.
                   5295: 
1.635     raeburn  5296: Inputs: 1 - optional reference to an args hash
                   5297: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5298: a 'Continue' link is not displayed if the page contains an
                   5299: internal redirect in the <head></head> section,
                   5300: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5301: 
                   5302: =cut
                   5303: 
                   5304: sub endbodytag {
1.635     raeburn  5305:     my ($args) = @_;
1.1075.2.6  raeburn  5306:     my $endbodytag;
                   5307:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5308:         $endbodytag='</body>';
                   5309:     }
1.269     albertel 5310:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5311:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5312:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5313: 	    $endbodytag=
                   5314: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5315: 	        &mt('Continue').'</a>'.
                   5316: 	        $endbodytag;
                   5317:         }
1.315     albertel 5318:     }
1.251     albertel 5319:     return $endbodytag;
                   5320: }
                   5321: 
1.352     albertel 5322: =pod
                   5323: 
                   5324: =item * &standard_css()
                   5325: 
                   5326: Returns a style sheet
                   5327: 
                   5328: Inputs: (all optional)
                   5329:             domain         -> force to color decorate a page for a specific
                   5330:                                domain
                   5331:             function       -> force usage of a specific rolish color scheme
                   5332:             bgcolor        -> override the default page bgcolor
                   5333: 
                   5334: =cut
                   5335: 
1.343     albertel 5336: sub standard_css {
1.345     albertel 5337:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5338:     $function  = &get_users_function() if (!$function);
                   5339:     my $img    = &designparm($function.'.img',   $domain);
                   5340:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5341:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5342:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5343: #second colour for later usage
1.345     albertel 5344:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5345:     my $pgbg_or_bgcolor =
                   5346: 	         $bgcolor ||
1.352     albertel 5347: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5348:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5349:     my $alink  = &designparm($function.'.alink', $domain);
                   5350:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5351:     my $link   = &designparm($function.'.link',  $domain);
                   5352: 
1.602     albertel 5353:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5354:     my $mono                 = 'monospace';
1.850     bisitz   5355:     my $data_table_head      = $sidebg;
                   5356:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5357:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5358:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5359:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5360:     my $mail_new             = '#FFBB77';
                   5361:     my $mail_new_hover       = '#DD9955';
                   5362:     my $mail_read            = '#BBBB77';
                   5363:     my $mail_read_hover      = '#999944';
                   5364:     my $mail_replied         = '#AAAA88';
                   5365:     my $mail_replied_hover   = '#888855';
                   5366:     my $mail_other           = '#99BBBB';
                   5367:     my $mail_other_hover     = '#669999';
1.391     albertel 5368:     my $table_header         = '#DDDDDD';
1.489     raeburn  5369:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5370:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5371:     my $button_hover         = '#BF2317';
1.392     albertel 5372: 
1.608     albertel 5373:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5374:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5375:                                              : '0 3px 0 4px';
1.448     albertel 5376: 
1.523     albertel 5377: 
1.343     albertel 5378:     return <<END;
1.947     droeschl 5379: 
                   5380: /* needed for iframe to allow 100% height in FF */
                   5381: body, html { 
                   5382:     margin: 0;
                   5383:     padding: 0 0.5%;
                   5384:     height: 99%; /* to avoid scrollbars */
                   5385: }
                   5386: 
1.795     www      5387: body {
1.911     bisitz   5388:   font-family: $sans;
                   5389:   line-height:130%;
                   5390:   font-size:0.83em;
                   5391:   color:$font;
1.795     www      5392: }
                   5393: 
1.959     onken    5394: a:focus,
                   5395: a:focus img {
1.795     www      5396:   color: red;
                   5397: }
1.698     harmsja  5398: 
1.911     bisitz   5399: form, .inline {
                   5400:   display: inline;
1.795     www      5401: }
1.721     harmsja  5402: 
1.795     www      5403: .LC_right {
1.911     bisitz   5404:   text-align:right;
1.795     www      5405: }
                   5406: 
                   5407: .LC_middle {
1.911     bisitz   5408:   vertical-align:middle;
1.795     www      5409: }
1.721     harmsja  5410: 
1.1075.2.38  raeburn  5411: .LC_floatleft {
                   5412:   float: left;
                   5413: }
                   5414: 
                   5415: .LC_floatright {
                   5416:   float: right;
                   5417: }
                   5418: 
1.911     bisitz   5419: .LC_400Box {
                   5420:   width:400px;
                   5421: }
1.721     harmsja  5422: 
1.947     droeschl 5423: .LC_iframecontainer {
                   5424:     width: 98%;
                   5425:     margin: 0;
                   5426:     position: fixed;
                   5427:     top: 8.5em;
                   5428:     bottom: 0;
                   5429: }
                   5430: 
                   5431: .LC_iframecontainer iframe{
                   5432:     border: none;
                   5433:     width: 100%;
                   5434:     height: 100%;
                   5435: }
                   5436: 
1.778     bisitz   5437: .LC_filename {
                   5438:   font-family: $mono;
                   5439:   white-space:pre;
1.921     bisitz   5440:   font-size: 120%;
1.778     bisitz   5441: }
                   5442: 
                   5443: .LC_fileicon {
                   5444:   border: none;
                   5445:   height: 1.3em;
                   5446:   vertical-align: text-bottom;
                   5447:   margin-right: 0.3em;
                   5448:   text-decoration:none;
                   5449: }
                   5450: 
1.1008    www      5451: .LC_setting {
                   5452:   text-decoration:underline;
                   5453: }
                   5454: 
1.350     albertel 5455: .LC_error {
                   5456:   color: red;
                   5457: }
1.795     www      5458: 
1.1075.2.15  raeburn  5459: .LC_warning {
                   5460:   color: darkorange;
                   5461: }
                   5462: 
1.457     albertel 5463: .LC_diff_removed {
1.733     bisitz   5464:   color: red;
1.394     albertel 5465: }
1.532     albertel 5466: 
                   5467: .LC_info,
1.457     albertel 5468: .LC_success,
                   5469: .LC_diff_added {
1.350     albertel 5470:   color: green;
                   5471: }
1.795     www      5472: 
1.802     bisitz   5473: div.LC_confirm_box {
                   5474:   background-color: #FAFAFA;
                   5475:   border: 1px solid $lg_border_color;
                   5476:   margin-right: 0;
                   5477:   padding: 5px;
                   5478: }
                   5479: 
                   5480: div.LC_confirm_box .LC_error img,
                   5481: div.LC_confirm_box .LC_success img {
                   5482:   vertical-align: middle;
                   5483: }
                   5484: 
1.440     albertel 5485: .LC_icon {
1.771     droeschl 5486:   border: none;
1.790     droeschl 5487:   vertical-align: middle;
1.771     droeschl 5488: }
                   5489: 
1.543     albertel 5490: .LC_docs_spacer {
                   5491:   width: 25px;
                   5492:   height: 1px;
1.771     droeschl 5493:   border: none;
1.543     albertel 5494: }
1.346     albertel 5495: 
1.532     albertel 5496: .LC_internal_info {
1.735     bisitz   5497:   color: #999999;
1.532     albertel 5498: }
                   5499: 
1.794     www      5500: .LC_discussion {
1.1050    www      5501:   background: $data_table_dark;
1.911     bisitz   5502:   border: 1px solid black;
                   5503:   margin: 2px;
1.794     www      5504: }
                   5505: 
                   5506: .LC_disc_action_left {
1.1050    www      5507:   background: $sidebg;
1.911     bisitz   5508:   text-align: left;
1.1050    www      5509:   padding: 4px;
                   5510:   margin: 2px;
1.794     www      5511: }
                   5512: 
                   5513: .LC_disc_action_right {
1.1050    www      5514:   background: $sidebg;
1.911     bisitz   5515:   text-align: right;
1.1050    www      5516:   padding: 4px;
                   5517:   margin: 2px;
1.794     www      5518: }
                   5519: 
                   5520: .LC_disc_new_item {
1.911     bisitz   5521:   background: white;
                   5522:   border: 2px solid red;
1.1050    www      5523:   margin: 4px;
                   5524:   padding: 4px;
1.794     www      5525: }
                   5526: 
                   5527: .LC_disc_old_item {
1.911     bisitz   5528:   background: white;
1.1050    www      5529:   margin: 4px;
                   5530:   padding: 4px;
1.794     www      5531: }
                   5532: 
1.458     albertel 5533: table.LC_pastsubmission {
                   5534:   border: 1px solid black;
                   5535:   margin: 2px;
                   5536: }
                   5537: 
1.924     bisitz   5538: table#LC_menubuttons {
1.345     albertel 5539:   width: 100%;
                   5540:   background: $pgbg;
1.392     albertel 5541:   border: 2px;
1.402     albertel 5542:   border-collapse: separate;
1.803     bisitz   5543:   padding: 0;
1.345     albertel 5544: }
1.392     albertel 5545: 
1.801     tempelho 5546: table#LC_title_bar a {
                   5547:   color: $fontmenu;
                   5548: }
1.836     bisitz   5549: 
1.807     droeschl 5550: table#LC_title_bar {
1.819     tempelho 5551:   clear: both;
1.836     bisitz   5552:   display: none;
1.807     droeschl 5553: }
                   5554: 
1.795     www      5555: table#LC_title_bar,
1.933     droeschl 5556: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5557: table#LC_title_bar.LC_with_remote {
1.359     albertel 5558:   width: 100%;
1.392     albertel 5559:   border-color: $pgbg;
                   5560:   border-style: solid;
                   5561:   border-width: $border;
1.379     albertel 5562:   background: $pgbg;
1.801     tempelho 5563:   color: $fontmenu;
1.392     albertel 5564:   border-collapse: collapse;
1.803     bisitz   5565:   padding: 0;
1.819     tempelho 5566:   margin: 0;
1.359     albertel 5567: }
1.795     www      5568: 
1.933     droeschl 5569: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5570:     margin: 0;
                   5571:     padding: 0;
1.933     droeschl 5572:     position: relative;
                   5573:     list-style: none;
1.913     droeschl 5574: }
1.933     droeschl 5575: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5576:     display: inline;
                   5577: }
1.933     droeschl 5578: 
                   5579: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5580:     padding: 0;
1.933     droeschl 5581:     margin: 0;
                   5582:     float: left;
1.913     droeschl 5583: }
1.933     droeschl 5584: .LC_breadcrumb_tools_tools {
                   5585:     padding: 0;
                   5586:     margin: 0;
1.913     droeschl 5587:     float: right;
                   5588: }
                   5589: 
1.359     albertel 5590: table#LC_title_bar td {
                   5591:   background: $tabbg;
                   5592: }
1.795     www      5593: 
1.911     bisitz   5594: table#LC_menubuttons img {
1.803     bisitz   5595:   border: none;
1.346     albertel 5596: }
1.795     www      5597: 
1.842     droeschl 5598: .LC_breadcrumbs_component {
1.911     bisitz   5599:   float: right;
                   5600:   margin: 0 1em;
1.357     albertel 5601: }
1.842     droeschl 5602: .LC_breadcrumbs_component img {
1.911     bisitz   5603:   vertical-align: middle;
1.777     tempelho 5604: }
1.795     www      5605: 
1.383     albertel 5606: td.LC_table_cell_checkbox {
                   5607:   text-align: center;
                   5608: }
1.795     www      5609: 
                   5610: .LC_fontsize_small {
1.911     bisitz   5611:   font-size: 70%;
1.705     tempelho 5612: }
                   5613: 
1.844     bisitz   5614: #LC_breadcrumbs {
1.911     bisitz   5615:   clear:both;
                   5616:   background: $sidebg;
                   5617:   border-bottom: 1px solid $lg_border_color;
                   5618:   line-height: 2.5em;
1.933     droeschl 5619:   overflow: hidden;
1.911     bisitz   5620:   margin: 0;
                   5621:   padding: 0;
1.995     raeburn  5622:   text-align: left;
1.819     tempelho 5623: }
1.862     bisitz   5624: 
1.1075.2.16  raeburn  5625: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5626:   clear:both;
                   5627:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5628:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5629:   margin: 0 0 10px 0;
1.966     bisitz   5630:   padding: 3px;
1.995     raeburn  5631:   text-align: left;
1.822     bisitz   5632: }
                   5633: 
1.795     www      5634: .LC_fontsize_medium {
1.911     bisitz   5635:   font-size: 85%;
1.705     tempelho 5636: }
                   5637: 
1.795     www      5638: .LC_fontsize_large {
1.911     bisitz   5639:   font-size: 120%;
1.705     tempelho 5640: }
                   5641: 
1.346     albertel 5642: .LC_menubuttons_inline_text {
                   5643:   color: $font;
1.698     harmsja  5644:   font-size: 90%;
1.701     harmsja  5645:   padding-left:3px;
1.346     albertel 5646: }
                   5647: 
1.934     droeschl 5648: .LC_menubuttons_inline_text img{
                   5649:   vertical-align: middle;
                   5650: }
                   5651: 
1.1051    www      5652: li.LC_menubuttons_inline_text img {
1.951     onken    5653:   cursor:pointer;
1.1002    droeschl 5654:   text-decoration: none;
1.951     onken    5655: }
                   5656: 
1.526     www      5657: .LC_menubuttons_link {
                   5658:   text-decoration: none;
                   5659: }
1.795     www      5660: 
1.522     albertel 5661: .LC_menubuttons_category {
1.521     www      5662:   color: $font;
1.526     www      5663:   background: $pgbg;
1.521     www      5664:   font-size: larger;
                   5665:   font-weight: bold;
                   5666: }
                   5667: 
1.346     albertel 5668: td.LC_menubuttons_text {
1.911     bisitz   5669:   color: $font;
1.346     albertel 5670: }
1.706     harmsja  5671: 
1.346     albertel 5672: .LC_current_location {
                   5673:   background: $tabbg;
                   5674: }
1.795     www      5675: 
1.938     bisitz   5676: table.LC_data_table {
1.347     albertel 5677:   border: 1px solid #000000;
1.402     albertel 5678:   border-collapse: separate;
1.426     albertel 5679:   border-spacing: 1px;
1.610     albertel 5680:   background: $pgbg;
1.347     albertel 5681: }
1.795     www      5682: 
1.422     albertel 5683: .LC_data_table_dense {
                   5684:   font-size: small;
                   5685: }
1.795     www      5686: 
1.507     raeburn  5687: table.LC_nested_outer {
                   5688:   border: 1px solid #000000;
1.589     raeburn  5689:   border-collapse: collapse;
1.803     bisitz   5690:   border-spacing: 0;
1.507     raeburn  5691:   width: 100%;
                   5692: }
1.795     www      5693: 
1.879     raeburn  5694: table.LC_innerpickbox,
1.507     raeburn  5695: table.LC_nested {
1.803     bisitz   5696:   border: none;
1.589     raeburn  5697:   border-collapse: collapse;
1.803     bisitz   5698:   border-spacing: 0;
1.507     raeburn  5699:   width: 100%;
                   5700: }
1.795     www      5701: 
1.911     bisitz   5702: table.LC_data_table tr th,
                   5703: table.LC_calendar tr th,
1.879     raeburn  5704: table.LC_prior_tries tr th,
                   5705: table.LC_innerpickbox tr th {
1.349     albertel 5706:   font-weight: bold;
                   5707:   background-color: $data_table_head;
1.801     tempelho 5708:   color:$fontmenu;
1.701     harmsja  5709:   font-size:90%;
1.347     albertel 5710: }
1.795     www      5711: 
1.879     raeburn  5712: table.LC_innerpickbox tr th,
                   5713: table.LC_innerpickbox tr td {
                   5714:   vertical-align: top;
                   5715: }
                   5716: 
1.711     raeburn  5717: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5718:   background-color: #CCCCCC;
1.711     raeburn  5719:   font-weight: bold;
                   5720:   text-align: left;
                   5721: }
1.795     www      5722: 
1.912     bisitz   5723: table.LC_data_table tr.LC_odd_row > td {
                   5724:   background-color: $data_table_light;
                   5725:   padding: 2px;
                   5726:   vertical-align: top;
                   5727: }
                   5728: 
1.809     bisitz   5729: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5730:   background-color: $data_table_light;
1.912     bisitz   5731:   vertical-align: top;
                   5732: }
                   5733: 
                   5734: table.LC_data_table tr.LC_even_row > td {
                   5735:   background-color: $data_table_dark;
1.425     albertel 5736:   padding: 2px;
1.900     bisitz   5737:   vertical-align: top;
1.347     albertel 5738: }
1.795     www      5739: 
1.809     bisitz   5740: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5741:   background-color: $data_table_dark;
1.900     bisitz   5742:   vertical-align: top;
1.347     albertel 5743: }
1.795     www      5744: 
1.425     albertel 5745: table.LC_data_table tr.LC_data_table_highlight td {
                   5746:   background-color: $data_table_darker;
                   5747: }
1.795     www      5748: 
1.639     raeburn  5749: table.LC_data_table tr td.LC_leftcol_header {
                   5750:   background-color: $data_table_head;
                   5751:   font-weight: bold;
                   5752: }
1.795     www      5753: 
1.451     albertel 5754: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5755: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5756:   font-weight: bold;
                   5757:   font-style: italic;
                   5758:   text-align: center;
                   5759:   padding: 8px;
1.347     albertel 5760: }
1.795     www      5761: 
1.1075.2.30  raeburn  5762: table.LC_data_table tr.LC_empty_row td,
                   5763: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5764:   background-color: $sidebg;
                   5765: }
                   5766: 
                   5767: table.LC_nested tr.LC_empty_row td {
                   5768:   background-color: #FFFFFF;
                   5769: }
                   5770: 
1.890     droeschl 5771: table.LC_caption {
                   5772: }
                   5773: 
1.507     raeburn  5774: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5775:   padding: 4ex
                   5776: }
1.795     www      5777: 
1.507     raeburn  5778: table.LC_nested_outer tr th {
                   5779:   font-weight: bold;
1.801     tempelho 5780:   color:$fontmenu;
1.507     raeburn  5781:   background-color: $data_table_head;
1.701     harmsja  5782:   font-size: small;
1.507     raeburn  5783:   border-bottom: 1px solid #000000;
                   5784: }
1.795     www      5785: 
1.507     raeburn  5786: table.LC_nested_outer tr td.LC_subheader {
                   5787:   background-color: $data_table_head;
                   5788:   font-weight: bold;
                   5789:   font-size: small;
                   5790:   border-bottom: 1px solid #000000;
                   5791:   text-align: right;
1.451     albertel 5792: }
1.795     www      5793: 
1.507     raeburn  5794: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5795:   background-color: #CCCCCC;
1.451     albertel 5796:   font-weight: bold;
                   5797:   font-size: small;
1.507     raeburn  5798:   text-align: center;
                   5799: }
1.795     www      5800: 
1.589     raeburn  5801: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5802: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5803:   text-align: left;
1.451     albertel 5804: }
1.795     www      5805: 
1.507     raeburn  5806: table.LC_nested td {
1.735     bisitz   5807:   background-color: #FFFFFF;
1.451     albertel 5808:   font-size: small;
1.507     raeburn  5809: }
1.795     www      5810: 
1.507     raeburn  5811: table.LC_nested_outer tr th.LC_right_item,
                   5812: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5813: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5814: table.LC_nested tr td.LC_right_item {
1.451     albertel 5815:   text-align: right;
                   5816: }
                   5817: 
1.507     raeburn  5818: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5819:   background-color: #EEEEEE;
1.451     albertel 5820: }
                   5821: 
1.473     raeburn  5822: table.LC_createuser {
                   5823: }
                   5824: 
                   5825: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5826:   font-size: small;
1.473     raeburn  5827: }
                   5828: 
                   5829: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5830:   background-color: #CCCCCC;
1.473     raeburn  5831:   font-weight: bold;
                   5832:   text-align: center;
                   5833: }
                   5834: 
1.349     albertel 5835: table.LC_calendar {
                   5836:   border: 1px solid #000000;
                   5837:   border-collapse: collapse;
1.917     raeburn  5838:   width: 98%;
1.349     albertel 5839: }
1.795     www      5840: 
1.349     albertel 5841: table.LC_calendar_pickdate {
                   5842:   font-size: xx-small;
                   5843: }
1.795     www      5844: 
1.349     albertel 5845: table.LC_calendar tr td {
                   5846:   border: 1px solid #000000;
                   5847:   vertical-align: top;
1.917     raeburn  5848:   width: 14%;
1.349     albertel 5849: }
1.795     www      5850: 
1.349     albertel 5851: table.LC_calendar tr td.LC_calendar_day_empty {
                   5852:   background-color: $data_table_dark;
                   5853: }
1.795     www      5854: 
1.779     bisitz   5855: table.LC_calendar tr td.LC_calendar_day_current {
                   5856:   background-color: $data_table_highlight;
1.777     tempelho 5857: }
1.795     www      5858: 
1.938     bisitz   5859: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5860:   background-color: $mail_new;
                   5861: }
1.795     www      5862: 
1.938     bisitz   5863: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5864:   background-color: $mail_new_hover;
                   5865: }
1.795     www      5866: 
1.938     bisitz   5867: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5868:   background-color: $mail_read;
                   5869: }
1.795     www      5870: 
1.938     bisitz   5871: /*
                   5872: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5873:   background-color: $mail_read_hover;
                   5874: }
1.938     bisitz   5875: */
1.795     www      5876: 
1.938     bisitz   5877: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5878:   background-color: $mail_replied;
                   5879: }
1.795     www      5880: 
1.938     bisitz   5881: /*
                   5882: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5883:   background-color: $mail_replied_hover;
                   5884: }
1.938     bisitz   5885: */
1.795     www      5886: 
1.938     bisitz   5887: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5888:   background-color: $mail_other;
                   5889: }
1.795     www      5890: 
1.938     bisitz   5891: /*
                   5892: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5893:   background-color: $mail_other_hover;
                   5894: }
1.938     bisitz   5895: */
1.494     raeburn  5896: 
1.777     tempelho 5897: table.LC_data_table tr > td.LC_browser_file,
                   5898: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5899:   background: #AAEE77;
1.389     albertel 5900: }
1.795     www      5901: 
1.777     tempelho 5902: table.LC_data_table tr > td.LC_browser_file_locked,
                   5903: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5904:   background: #FFAA99;
1.387     albertel 5905: }
1.795     www      5906: 
1.777     tempelho 5907: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5908:   background: #888888;
1.779     bisitz   5909: }
1.795     www      5910: 
1.777     tempelho 5911: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5912: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5913:   background: #F8F866;
1.777     tempelho 5914: }
1.795     www      5915: 
1.696     bisitz   5916: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5917:   background: #E0E8FF;
1.387     albertel 5918: }
1.696     bisitz   5919: 
1.707     bisitz   5920: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5921:   /* background: #77FF77; */
1.707     bisitz   5922: }
1.795     www      5923: 
1.707     bisitz   5924: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5925:   border-right: 8px solid #FFFF77;
1.707     bisitz   5926: }
1.795     www      5927: 
1.707     bisitz   5928: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5929:   border-right: 8px solid #FFAA77;
1.707     bisitz   5930: }
1.795     www      5931: 
1.707     bisitz   5932: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5933:   border-right: 8px solid #FF7777;
1.707     bisitz   5934: }
1.795     www      5935: 
1.707     bisitz   5936: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5937:   border-right: 8px solid #AAFF77;
1.707     bisitz   5938: }
1.795     www      5939: 
1.707     bisitz   5940: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5941:   border-right: 8px solid #11CC55;
1.707     bisitz   5942: }
                   5943: 
1.388     albertel 5944: span.LC_current_location {
1.701     harmsja  5945:   font-size:larger;
1.388     albertel 5946:   background: $pgbg;
                   5947: }
1.387     albertel 5948: 
1.1029    www      5949: span.LC_current_nav_location {
                   5950:   font-weight:bold;
                   5951:   background: $sidebg;
                   5952: }
                   5953: 
1.395     albertel 5954: span.LC_parm_menu_item {
                   5955:   font-size: larger;
                   5956: }
1.795     www      5957: 
1.395     albertel 5958: span.LC_parm_scope_all {
                   5959:   color: red;
                   5960: }
1.795     www      5961: 
1.395     albertel 5962: span.LC_parm_scope_folder {
                   5963:   color: green;
                   5964: }
1.795     www      5965: 
1.395     albertel 5966: span.LC_parm_scope_resource {
                   5967:   color: orange;
                   5968: }
1.795     www      5969: 
1.395     albertel 5970: span.LC_parm_part {
                   5971:   color: blue;
                   5972: }
1.795     www      5973: 
1.911     bisitz   5974: span.LC_parm_folder,
                   5975: span.LC_parm_symb {
1.395     albertel 5976:   font-size: x-small;
                   5977:   font-family: $mono;
                   5978:   color: #AAAAAA;
                   5979: }
                   5980: 
1.977     bisitz   5981: ul.LC_parm_parmlist li {
                   5982:   display: inline-block;
                   5983:   padding: 0.3em 0.8em;
                   5984:   vertical-align: top;
                   5985:   width: 150px;
                   5986:   border-top:1px solid $lg_border_color;
                   5987: }
                   5988: 
1.795     www      5989: td.LC_parm_overview_level_menu,
                   5990: td.LC_parm_overview_map_menu,
                   5991: td.LC_parm_overview_parm_selectors,
                   5992: td.LC_parm_overview_restrictions  {
1.396     albertel 5993:   border: 1px solid black;
                   5994:   border-collapse: collapse;
                   5995: }
1.795     www      5996: 
1.396     albertel 5997: table.LC_parm_overview_restrictions td {
                   5998:   border-width: 1px 4px 1px 4px;
                   5999:   border-style: solid;
                   6000:   border-color: $pgbg;
                   6001:   text-align: center;
                   6002: }
1.795     www      6003: 
1.396     albertel 6004: table.LC_parm_overview_restrictions th {
                   6005:   background: $tabbg;
                   6006:   border-width: 1px 4px 1px 4px;
                   6007:   border-style: solid;
                   6008:   border-color: $pgbg;
                   6009: }
1.795     www      6010: 
1.398     albertel 6011: table#LC_helpmenu {
1.803     bisitz   6012:   border: none;
1.398     albertel 6013:   height: 55px;
1.803     bisitz   6014:   border-spacing: 0;
1.398     albertel 6015: }
                   6016: 
                   6017: table#LC_helpmenu fieldset legend {
                   6018:   font-size: larger;
                   6019: }
1.795     www      6020: 
1.397     albertel 6021: table#LC_helpmenu_links {
                   6022:   width: 100%;
                   6023:   border: 1px solid black;
                   6024:   background: $pgbg;
1.803     bisitz   6025:   padding: 0;
1.397     albertel 6026:   border-spacing: 1px;
                   6027: }
1.795     www      6028: 
1.397     albertel 6029: table#LC_helpmenu_links tr td {
                   6030:   padding: 1px;
                   6031:   background: $tabbg;
1.399     albertel 6032:   text-align: center;
                   6033:   font-weight: bold;
1.397     albertel 6034: }
1.396     albertel 6035: 
1.795     www      6036: table#LC_helpmenu_links a:link,
                   6037: table#LC_helpmenu_links a:visited,
1.397     albertel 6038: table#LC_helpmenu_links a:active {
                   6039:   text-decoration: none;
                   6040:   color: $font;
                   6041: }
1.795     www      6042: 
1.397     albertel 6043: table#LC_helpmenu_links a:hover {
                   6044:   text-decoration: underline;
                   6045:   color: $vlink;
                   6046: }
1.396     albertel 6047: 
1.417     albertel 6048: .LC_chrt_popup_exists {
                   6049:   border: 1px solid #339933;
                   6050:   margin: -1px;
                   6051: }
1.795     www      6052: 
1.417     albertel 6053: .LC_chrt_popup_up {
                   6054:   border: 1px solid yellow;
                   6055:   margin: -1px;
                   6056: }
1.795     www      6057: 
1.417     albertel 6058: .LC_chrt_popup {
                   6059:   border: 1px solid #8888FF;
                   6060:   background: #CCCCFF;
                   6061: }
1.795     www      6062: 
1.421     albertel 6063: table.LC_pick_box {
                   6064:   border-collapse: separate;
                   6065:   background: white;
                   6066:   border: 1px solid black;
                   6067:   border-spacing: 1px;
                   6068: }
1.795     www      6069: 
1.421     albertel 6070: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6071:   background: $sidebg;
1.421     albertel 6072:   font-weight: bold;
1.900     bisitz   6073:   text-align: left;
1.740     bisitz   6074:   vertical-align: top;
1.421     albertel 6075:   width: 184px;
                   6076:   padding: 8px;
                   6077: }
1.795     www      6078: 
1.579     raeburn  6079: table.LC_pick_box td.LC_pick_box_value {
                   6080:   text-align: left;
                   6081:   padding: 8px;
                   6082: }
1.795     www      6083: 
1.579     raeburn  6084: table.LC_pick_box td.LC_pick_box_select {
                   6085:   text-align: left;
                   6086:   padding: 8px;
                   6087: }
1.795     www      6088: 
1.424     albertel 6089: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6090:   padding: 0;
1.421     albertel 6091:   height: 1px;
                   6092:   background: black;
                   6093: }
1.795     www      6094: 
1.421     albertel 6095: table.LC_pick_box td.LC_pick_box_submit {
                   6096:   text-align: right;
                   6097: }
1.795     www      6098: 
1.579     raeburn  6099: table.LC_pick_box td.LC_evenrow_value {
                   6100:   text-align: left;
                   6101:   padding: 8px;
                   6102:   background-color: $data_table_light;
                   6103: }
1.795     www      6104: 
1.579     raeburn  6105: table.LC_pick_box td.LC_oddrow_value {
                   6106:   text-align: left;
                   6107:   padding: 8px;
                   6108:   background-color: $data_table_light;
                   6109: }
1.795     www      6110: 
1.579     raeburn  6111: span.LC_helpform_receipt_cat {
                   6112:   font-weight: bold;
                   6113: }
1.795     www      6114: 
1.424     albertel 6115: table.LC_group_priv_box {
                   6116:   background: white;
                   6117:   border: 1px solid black;
                   6118:   border-spacing: 1px;
                   6119: }
1.795     www      6120: 
1.424     albertel 6121: table.LC_group_priv_box td.LC_pick_box_title {
                   6122:   background: $tabbg;
                   6123:   font-weight: bold;
                   6124:   text-align: right;
                   6125:   width: 184px;
                   6126: }
1.795     www      6127: 
1.424     albertel 6128: table.LC_group_priv_box td.LC_groups_fixed {
                   6129:   background: $data_table_light;
                   6130:   text-align: center;
                   6131: }
1.795     www      6132: 
1.424     albertel 6133: table.LC_group_priv_box td.LC_groups_optional {
                   6134:   background: $data_table_dark;
                   6135:   text-align: center;
                   6136: }
1.795     www      6137: 
1.424     albertel 6138: table.LC_group_priv_box td.LC_groups_functionality {
                   6139:   background: $data_table_darker;
                   6140:   text-align: center;
                   6141:   font-weight: bold;
                   6142: }
1.795     www      6143: 
1.424     albertel 6144: table.LC_group_priv td {
                   6145:   text-align: left;
1.803     bisitz   6146:   padding: 0;
1.424     albertel 6147: }
                   6148: 
                   6149: .LC_navbuttons {
                   6150:   margin: 2ex 0ex 2ex 0ex;
                   6151: }
1.795     www      6152: 
1.423     albertel 6153: .LC_topic_bar {
                   6154:   font-weight: bold;
                   6155:   background: $tabbg;
1.918     wenzelju 6156:   margin: 1em 0em 1em 2em;
1.805     bisitz   6157:   padding: 3px;
1.918     wenzelju 6158:   font-size: 1.2em;
1.423     albertel 6159: }
1.795     www      6160: 
1.423     albertel 6161: .LC_topic_bar span {
1.918     wenzelju 6162:   left: 0.5em;
                   6163:   position: absolute;
1.423     albertel 6164:   vertical-align: middle;
1.918     wenzelju 6165:   font-size: 1.2em;
1.423     albertel 6166: }
1.795     www      6167: 
1.423     albertel 6168: table.LC_course_group_status {
                   6169:   margin: 20px;
                   6170: }
1.795     www      6171: 
1.423     albertel 6172: table.LC_status_selector td {
                   6173:   vertical-align: top;
                   6174:   text-align: center;
1.424     albertel 6175:   padding: 4px;
                   6176: }
1.795     www      6177: 
1.599     albertel 6178: div.LC_feedback_link {
1.616     albertel 6179:   clear: both;
1.829     kalberla 6180:   background: $sidebg;
1.779     bisitz   6181:   width: 100%;
1.829     kalberla 6182:   padding-bottom: 10px;
                   6183:   border: 1px $tabbg solid;
1.833     kalberla 6184:   height: 22px;
                   6185:   line-height: 22px;
                   6186:   padding-top: 5px;
                   6187: }
                   6188: 
                   6189: div.LC_feedback_link img {
                   6190:   height: 22px;
1.867     kalberla 6191:   vertical-align:middle;
1.829     kalberla 6192: }
                   6193: 
1.911     bisitz   6194: div.LC_feedback_link a {
1.829     kalberla 6195:   text-decoration: none;
1.489     raeburn  6196: }
1.795     www      6197: 
1.867     kalberla 6198: div.LC_comblock {
1.911     bisitz   6199:   display:inline;
1.867     kalberla 6200:   color:$font;
                   6201:   font-size:90%;
                   6202: }
                   6203: 
                   6204: div.LC_feedback_link div.LC_comblock {
                   6205:   padding-left:5px;
                   6206: }
                   6207: 
                   6208: div.LC_feedback_link div.LC_comblock a {
                   6209:   color:$font;
                   6210: }
                   6211: 
1.489     raeburn  6212: span.LC_feedback_link {
1.858     bisitz   6213:   /* background: $feedback_link_bg; */
1.599     albertel 6214:   font-size: larger;
                   6215: }
1.795     www      6216: 
1.599     albertel 6217: span.LC_message_link {
1.858     bisitz   6218:   /* background: $feedback_link_bg; */
1.599     albertel 6219:   font-size: larger;
                   6220:   position: absolute;
                   6221:   right: 1em;
1.489     raeburn  6222: }
1.421     albertel 6223: 
1.515     albertel 6224: table.LC_prior_tries {
1.524     albertel 6225:   border: 1px solid #000000;
                   6226:   border-collapse: separate;
                   6227:   border-spacing: 1px;
1.515     albertel 6228: }
1.523     albertel 6229: 
1.515     albertel 6230: table.LC_prior_tries td {
1.524     albertel 6231:   padding: 2px;
1.515     albertel 6232: }
1.523     albertel 6233: 
                   6234: .LC_answer_correct {
1.795     www      6235:   background: lightgreen;
                   6236:   color: darkgreen;
                   6237:   padding: 6px;
1.523     albertel 6238: }
1.795     www      6239: 
1.523     albertel 6240: .LC_answer_charged_try {
1.797     www      6241:   background: #FFAAAA;
1.795     www      6242:   color: darkred;
                   6243:   padding: 6px;
1.523     albertel 6244: }
1.795     www      6245: 
1.779     bisitz   6246: .LC_answer_not_charged_try,
1.523     albertel 6247: .LC_answer_no_grade,
                   6248: .LC_answer_late {
1.795     www      6249:   background: lightyellow;
1.523     albertel 6250:   color: black;
1.795     www      6251:   padding: 6px;
1.523     albertel 6252: }
1.795     www      6253: 
1.523     albertel 6254: .LC_answer_previous {
1.795     www      6255:   background: lightblue;
                   6256:   color: darkblue;
                   6257:   padding: 6px;
1.523     albertel 6258: }
1.795     www      6259: 
1.779     bisitz   6260: .LC_answer_no_message {
1.777     tempelho 6261:   background: #FFFFFF;
                   6262:   color: black;
1.795     www      6263:   padding: 6px;
1.779     bisitz   6264: }
1.795     www      6265: 
1.779     bisitz   6266: .LC_answer_unknown {
                   6267:   background: orange;
                   6268:   color: black;
1.795     www      6269:   padding: 6px;
1.777     tempelho 6270: }
1.795     www      6271: 
1.529     albertel 6272: span.LC_prior_numerical,
                   6273: span.LC_prior_string,
                   6274: span.LC_prior_custom,
                   6275: span.LC_prior_reaction,
                   6276: span.LC_prior_math {
1.925     bisitz   6277:   font-family: $mono;
1.523     albertel 6278:   white-space: pre;
                   6279: }
                   6280: 
1.525     albertel 6281: span.LC_prior_string {
1.925     bisitz   6282:   font-family: $mono;
1.525     albertel 6283:   white-space: pre;
                   6284: }
                   6285: 
1.523     albertel 6286: table.LC_prior_option {
                   6287:   width: 100%;
                   6288:   border-collapse: collapse;
                   6289: }
1.795     www      6290: 
1.911     bisitz   6291: table.LC_prior_rank,
1.795     www      6292: table.LC_prior_match {
1.528     albertel 6293:   border-collapse: collapse;
                   6294: }
1.795     www      6295: 
1.528     albertel 6296: table.LC_prior_option tr td,
                   6297: table.LC_prior_rank tr td,
                   6298: table.LC_prior_match tr td {
1.524     albertel 6299:   border: 1px solid #000000;
1.515     albertel 6300: }
                   6301: 
1.855     bisitz   6302: .LC_nobreak {
1.544     albertel 6303:   white-space: nowrap;
1.519     raeburn  6304: }
                   6305: 
1.576     raeburn  6306: span.LC_cusr_emph {
                   6307:   font-style: italic;
                   6308: }
                   6309: 
1.633     raeburn  6310: span.LC_cusr_subheading {
                   6311:   font-weight: normal;
                   6312:   font-size: 85%;
                   6313: }
                   6314: 
1.861     bisitz   6315: div.LC_docs_entry_move {
1.859     bisitz   6316:   border: 1px solid #BBBBBB;
1.545     albertel 6317:   background: #DDDDDD;
1.861     bisitz   6318:   width: 22px;
1.859     bisitz   6319:   padding: 1px;
                   6320:   margin: 0;
1.545     albertel 6321: }
                   6322: 
1.861     bisitz   6323: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6324: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6325:   font-size: x-small;
                   6326: }
1.795     www      6327: 
1.861     bisitz   6328: .LC_docs_entry_parameter {
                   6329:   white-space: nowrap;
                   6330: }
                   6331: 
1.544     albertel 6332: .LC_docs_copy {
1.545     albertel 6333:   color: #000099;
1.544     albertel 6334: }
1.795     www      6335: 
1.544     albertel 6336: .LC_docs_cut {
1.545     albertel 6337:   color: #550044;
1.544     albertel 6338: }
1.795     www      6339: 
1.544     albertel 6340: .LC_docs_rename {
1.545     albertel 6341:   color: #009900;
1.544     albertel 6342: }
1.795     www      6343: 
1.544     albertel 6344: .LC_docs_remove {
1.545     albertel 6345:   color: #990000;
                   6346: }
                   6347: 
1.547     albertel 6348: .LC_docs_reinit_warn,
                   6349: .LC_docs_ext_edit {
                   6350:   font-size: x-small;
                   6351: }
                   6352: 
1.545     albertel 6353: table.LC_docs_adddocs td,
                   6354: table.LC_docs_adddocs th {
                   6355:   border: 1px solid #BBBBBB;
                   6356:   padding: 4px;
                   6357:   background: #DDDDDD;
1.543     albertel 6358: }
                   6359: 
1.584     albertel 6360: table.LC_sty_begin {
                   6361:   background: #BBFFBB;
                   6362: }
1.795     www      6363: 
1.584     albertel 6364: table.LC_sty_end {
                   6365:   background: #FFBBBB;
                   6366: }
                   6367: 
1.589     raeburn  6368: table.LC_double_column {
1.803     bisitz   6369:   border-width: 0;
1.589     raeburn  6370:   border-collapse: collapse;
                   6371:   width: 100%;
                   6372:   padding: 2px;
                   6373: }
                   6374: 
                   6375: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6376:   top: 2px;
1.589     raeburn  6377:   left: 2px;
                   6378:   width: 47%;
                   6379:   vertical-align: top;
                   6380: }
                   6381: 
                   6382: table.LC_double_column tr td.LC_right_col {
                   6383:   top: 2px;
1.779     bisitz   6384:   right: 2px;
1.589     raeburn  6385:   width: 47%;
                   6386:   vertical-align: top;
                   6387: }
                   6388: 
1.591     raeburn  6389: div.LC_left_float {
                   6390:   float: left;
                   6391:   padding-right: 5%;
1.597     albertel 6392:   padding-bottom: 4px;
1.591     raeburn  6393: }
                   6394: 
                   6395: div.LC_clear_float_header {
1.597     albertel 6396:   padding-bottom: 2px;
1.591     raeburn  6397: }
                   6398: 
                   6399: div.LC_clear_float_footer {
1.597     albertel 6400:   padding-top: 10px;
1.591     raeburn  6401:   clear: both;
                   6402: }
                   6403: 
1.597     albertel 6404: div.LC_grade_show_user {
1.941     bisitz   6405: /*  border-left: 5px solid $sidebg; */
                   6406:   border-top: 5px solid #000000;
                   6407:   margin: 50px 0 0 0;
1.936     bisitz   6408:   padding: 15px 0 5px 10px;
1.597     albertel 6409: }
1.795     www      6410: 
1.936     bisitz   6411: div.LC_grade_show_user_odd_row {
1.941     bisitz   6412: /*  border-left: 5px solid #000000; */
                   6413: }
                   6414: 
                   6415: div.LC_grade_show_user div.LC_Box {
                   6416:   margin-right: 50px;
1.597     albertel 6417: }
                   6418: 
                   6419: div.LC_grade_submissions,
                   6420: div.LC_grade_message_center,
1.936     bisitz   6421: div.LC_grade_info_links {
1.597     albertel 6422:   margin: 5px;
                   6423:   width: 99%;
                   6424:   background: #FFFFFF;
                   6425: }
1.795     www      6426: 
1.597     albertel 6427: div.LC_grade_submissions_header,
1.936     bisitz   6428: div.LC_grade_message_center_header {
1.705     tempelho 6429:   font-weight: bold;
                   6430:   font-size: large;
1.597     albertel 6431: }
1.795     www      6432: 
1.597     albertel 6433: div.LC_grade_submissions_body,
1.936     bisitz   6434: div.LC_grade_message_center_body {
1.597     albertel 6435:   border: 1px solid black;
                   6436:   width: 99%;
                   6437:   background: #FFFFFF;
                   6438: }
1.795     www      6439: 
1.613     albertel 6440: table.LC_scantron_action {
                   6441:   width: 100%;
                   6442: }
1.795     www      6443: 
1.613     albertel 6444: table.LC_scantron_action tr th {
1.698     harmsja  6445:   font-weight:bold;
                   6446:   font-style:normal;
1.613     albertel 6447: }
1.795     www      6448: 
1.779     bisitz   6449: .LC_edit_problem_header,
1.614     albertel 6450: div.LC_edit_problem_footer {
1.705     tempelho 6451:   font-weight: normal;
                   6452:   font-size:  medium;
1.602     albertel 6453:   margin: 2px;
1.1060    bisitz   6454:   background-color: $sidebg;
1.600     albertel 6455: }
1.795     www      6456: 
1.600     albertel 6457: div.LC_edit_problem_header,
1.602     albertel 6458: div.LC_edit_problem_header div,
1.614     albertel 6459: div.LC_edit_problem_footer,
                   6460: div.LC_edit_problem_footer div,
1.602     albertel 6461: div.LC_edit_problem_editxml_header,
                   6462: div.LC_edit_problem_editxml_header div {
1.600     albertel 6463:   margin-top: 5px;
                   6464: }
1.795     www      6465: 
1.600     albertel 6466: div.LC_edit_problem_header_title {
1.705     tempelho 6467:   font-weight: bold;
                   6468:   font-size: larger;
1.602     albertel 6469:   background: $tabbg;
                   6470:   padding: 3px;
1.1060    bisitz   6471:   margin: 0 0 5px 0;
1.602     albertel 6472: }
1.795     www      6473: 
1.602     albertel 6474: table.LC_edit_problem_header_title {
                   6475:   width: 100%;
1.600     albertel 6476:   background: $tabbg;
1.602     albertel 6477: }
                   6478: 
                   6479: div.LC_edit_problem_discards {
                   6480:   float: left;
                   6481:   padding-bottom: 5px;
                   6482: }
1.795     www      6483: 
1.602     albertel 6484: div.LC_edit_problem_saves {
                   6485:   float: right;
                   6486:   padding-bottom: 5px;
1.600     albertel 6487: }
1.795     www      6488: 
1.1075.2.34  raeburn  6489: .LC_edit_opt {
                   6490:   padding-left: 1em;
                   6491:   white-space: nowrap;
                   6492: }
                   6493: 
1.1075.2.57  raeburn  6494: .LC_edit_problem_latexhelper{
                   6495:     text-align: right;
                   6496: }
                   6497: 
                   6498: #LC_edit_problem_colorful div{
                   6499:     margin-left: 40px;
                   6500: }
                   6501: 
1.911     bisitz   6502: img.stift {
1.803     bisitz   6503:   border-width: 0;
                   6504:   vertical-align: middle;
1.677     riegler  6505: }
1.680     riegler  6506: 
1.923     bisitz   6507: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6508:   vertical-align: top;
1.777     tempelho 6509: }
1.795     www      6510: 
1.716     raeburn  6511: div.LC_createcourse {
1.911     bisitz   6512:   margin: 10px 10px 10px 10px;
1.716     raeburn  6513: }
                   6514: 
1.917     raeburn  6515: .LC_dccid {
1.1075.2.38  raeburn  6516:   float: right;
1.917     raeburn  6517:   margin: 0.2em 0 0 0;
                   6518:   padding: 0;
                   6519:   font-size: 90%;
                   6520:   display:none;
                   6521: }
                   6522: 
1.897     wenzelju 6523: ol.LC_primary_menu a:hover,
1.721     harmsja  6524: ol#LC_MenuBreadcrumbs a:hover,
                   6525: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6526: ul#LC_secondary_menu a:hover,
1.721     harmsja  6527: .LC_FormSectionClearButton input:hover
1.795     www      6528: ul.LC_TabContent   li:hover a {
1.952     onken    6529:   color:$button_hover;
1.911     bisitz   6530:   text-decoration:none;
1.693     droeschl 6531: }
                   6532: 
1.779     bisitz   6533: h1 {
1.911     bisitz   6534:   padding: 0;
                   6535:   line-height:130%;
1.693     droeschl 6536: }
1.698     harmsja  6537: 
1.911     bisitz   6538: h2,
                   6539: h3,
                   6540: h4,
                   6541: h5,
                   6542: h6 {
                   6543:   margin: 5px 0 5px 0;
                   6544:   padding: 0;
                   6545:   line-height:130%;
1.693     droeschl 6546: }
1.795     www      6547: 
                   6548: .LC_hcell {
1.911     bisitz   6549:   padding:3px 15px 3px 15px;
                   6550:   margin: 0;
                   6551:   background-color:$tabbg;
                   6552:   color:$fontmenu;
                   6553:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6554: }
1.795     www      6555: 
1.840     bisitz   6556: .LC_Box > .LC_hcell {
1.911     bisitz   6557:   margin: 0 -10px 10px -10px;
1.835     bisitz   6558: }
                   6559: 
1.721     harmsja  6560: .LC_noBorder {
1.911     bisitz   6561:   border: 0;
1.698     harmsja  6562: }
1.693     droeschl 6563: 
1.721     harmsja  6564: .LC_FormSectionClearButton input {
1.911     bisitz   6565:   background-color:transparent;
                   6566:   border: none;
                   6567:   cursor:pointer;
                   6568:   text-decoration:underline;
1.693     droeschl 6569: }
1.763     bisitz   6570: 
                   6571: .LC_help_open_topic {
1.911     bisitz   6572:   color: #FFFFFF;
                   6573:   background-color: #EEEEFF;
                   6574:   margin: 1px;
                   6575:   padding: 4px;
                   6576:   border: 1px solid #000033;
                   6577:   white-space: nowrap;
                   6578:   /* vertical-align: middle; */
1.759     neumanie 6579: }
1.693     droeschl 6580: 
1.911     bisitz   6581: dl,
                   6582: ul,
                   6583: div,
                   6584: fieldset {
                   6585:   margin: 10px 10px 10px 0;
                   6586:   /* overflow: hidden; */
1.693     droeschl 6587: }
1.795     www      6588: 
1.838     bisitz   6589: fieldset > legend {
1.911     bisitz   6590:   font-weight: bold;
                   6591:   padding: 0 5px 0 5px;
1.838     bisitz   6592: }
                   6593: 
1.813     bisitz   6594: #LC_nav_bar {
1.911     bisitz   6595:   float: left;
1.995     raeburn  6596:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6597:   margin: 0 0 2px 0;
1.807     droeschl 6598: }
                   6599: 
1.916     droeschl 6600: #LC_realm {
                   6601:   margin: 0.2em 0 0 0;
                   6602:   padding: 0;
                   6603:   font-weight: bold;
                   6604:   text-align: center;
1.995     raeburn  6605:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6606: }
                   6607: 
1.911     bisitz   6608: #LC_nav_bar em {
                   6609:   font-weight: bold;
                   6610:   font-style: normal;
1.807     droeschl 6611: }
                   6612: 
1.897     wenzelju 6613: ol.LC_primary_menu {
1.934     droeschl 6614:   margin: 0;
1.1075.2.2  raeburn  6615:   padding: 0;
1.995     raeburn  6616:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6617: }
                   6618: 
1.852     droeschl 6619: ol#LC_PathBreadcrumbs {
1.911     bisitz   6620:   margin: 0;
1.693     droeschl 6621: }
                   6622: 
1.897     wenzelju 6623: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6624:   color: RGB(80, 80, 80);
                   6625:   vertical-align: middle;
                   6626:   text-align: left;
                   6627:   list-style: none;
                   6628:   float: left;
                   6629: }
                   6630: 
                   6631: ol.LC_primary_menu li a {
                   6632:   display: block;
                   6633:   margin: 0;
                   6634:   padding: 0 5px 0 10px;
                   6635:   text-decoration: none;
                   6636: }
                   6637: 
                   6638: ol.LC_primary_menu li ul {
                   6639:   display: none;
                   6640:   width: 10em;
                   6641:   background-color: $data_table_light;
                   6642: }
                   6643: 
                   6644: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6645:   display: block;
                   6646:   position: absolute;
                   6647:   margin: 0;
                   6648:   padding: 0;
1.1075.2.5  raeburn  6649:   z-index: 2;
1.1075.2.2  raeburn  6650: }
                   6651: 
                   6652: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6653:   font-size: 90%;
1.911     bisitz   6654:   vertical-align: top;
1.1075.2.2  raeburn  6655:   float: none;
1.1075.2.5  raeburn  6656:   border-left: 1px solid black;
                   6657:   border-right: 1px solid black;
1.1075.2.2  raeburn  6658: }
                   6659: 
                   6660: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6661:   background-color:$data_table_light;
1.1075.2.2  raeburn  6662: }
                   6663: 
                   6664: ol.LC_primary_menu li li a:hover {
                   6665:    color:$button_hover;
                   6666:    background-color:$data_table_dark;
1.693     droeschl 6667: }
                   6668: 
1.897     wenzelju 6669: ol.LC_primary_menu li img {
1.911     bisitz   6670:   vertical-align: bottom;
1.934     droeschl 6671:   height: 1.1em;
1.1075.2.3  raeburn  6672:   margin: 0.2em 0 0 0;
1.693     droeschl 6673: }
                   6674: 
1.897     wenzelju 6675: ol.LC_primary_menu a {
1.911     bisitz   6676:   color: RGB(80, 80, 80);
                   6677:   text-decoration: none;
1.693     droeschl 6678: }
1.795     www      6679: 
1.949     droeschl 6680: ol.LC_primary_menu a.LC_new_message {
                   6681:   font-weight:bold;
                   6682:   color: darkred;
                   6683: }
                   6684: 
1.975     raeburn  6685: ol.LC_docs_parameters {
                   6686:   margin-left: 0;
                   6687:   padding: 0;
                   6688:   list-style: none;
                   6689: }
                   6690: 
                   6691: ol.LC_docs_parameters li {
                   6692:   margin: 0;
                   6693:   padding-right: 20px;
                   6694:   display: inline;
                   6695: }
                   6696: 
1.976     raeburn  6697: ol.LC_docs_parameters li:before {
                   6698:   content: "\\002022 \\0020";
                   6699: }
                   6700: 
                   6701: li.LC_docs_parameters_title {
                   6702:   font-weight: bold;
                   6703: }
                   6704: 
                   6705: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6706:   content: "";
                   6707: }
                   6708: 
1.897     wenzelju 6709: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6710:   clear: right;
1.911     bisitz   6711:   color: $fontmenu;
                   6712:   background: $tabbg;
                   6713:   list-style: none;
                   6714:   padding: 0;
                   6715:   margin: 0;
                   6716:   width: 100%;
1.995     raeburn  6717:   text-align: left;
1.1075.2.4  raeburn  6718:   float: left;
1.808     droeschl 6719: }
                   6720: 
1.897     wenzelju 6721: ul#LC_secondary_menu li {
1.911     bisitz   6722:   font-weight: bold;
                   6723:   line-height: 1.8em;
                   6724:   border-right: 1px solid black;
                   6725:   vertical-align: middle;
1.1075.2.4  raeburn  6726:   float: left;
                   6727: }
                   6728: 
                   6729: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6730:   background-color: $data_table_light;
                   6731: }
                   6732: 
                   6733: ul#LC_secondary_menu li a {
                   6734:   padding: 0 0.8em;
                   6735: }
                   6736: 
                   6737: ul#LC_secondary_menu li ul {
                   6738:   display: none;
                   6739: }
                   6740: 
                   6741: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6742:   display: block;
                   6743:   position: absolute;
                   6744:   margin: 0;
                   6745:   padding: 0;
                   6746:   list-style:none;
                   6747:   float: none;
                   6748:   background-color: $data_table_light;
1.1075.2.5  raeburn  6749:   z-index: 2;
1.1075.2.10  raeburn  6750:   margin-left: -1px;
1.1075.2.4  raeburn  6751: }
                   6752: 
                   6753: ul#LC_secondary_menu li ul li {
                   6754:   font-size: 90%;
                   6755:   vertical-align: top;
                   6756:   border-left: 1px solid black;
                   6757:   border-right: 1px solid black;
1.1075.2.33  raeburn  6758:   background-color: $data_table_light;
1.1075.2.4  raeburn  6759:   list-style:none;
                   6760:   float: none;
                   6761: }
                   6762: 
                   6763: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6764:   background-color: $data_table_dark;
1.807     droeschl 6765: }
                   6766: 
1.847     tempelho 6767: ul.LC_TabContent {
1.911     bisitz   6768:   display:block;
                   6769:   background: $sidebg;
                   6770:   border-bottom: solid 1px $lg_border_color;
                   6771:   list-style:none;
1.1020    raeburn  6772:   margin: -1px -10px 0 -10px;
1.911     bisitz   6773:   padding: 0;
1.693     droeschl 6774: }
                   6775: 
1.795     www      6776: ul.LC_TabContent li,
                   6777: ul.LC_TabContentBigger li {
1.911     bisitz   6778:   float:left;
1.741     harmsja  6779: }
1.795     www      6780: 
1.897     wenzelju 6781: ul#LC_secondary_menu li a {
1.911     bisitz   6782:   color: $fontmenu;
                   6783:   text-decoration: none;
1.693     droeschl 6784: }
1.795     www      6785: 
1.721     harmsja  6786: ul.LC_TabContent {
1.952     onken    6787:   min-height:20px;
1.721     harmsja  6788: }
1.795     www      6789: 
                   6790: ul.LC_TabContent li {
1.911     bisitz   6791:   vertical-align:middle;
1.959     onken    6792:   padding: 0 16px 0 10px;
1.911     bisitz   6793:   background-color:$tabbg;
                   6794:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6795:   border-left: solid 1px $font;
1.721     harmsja  6796: }
1.795     www      6797: 
1.847     tempelho 6798: ul.LC_TabContent .right {
1.911     bisitz   6799:   float:right;
1.847     tempelho 6800: }
                   6801: 
1.911     bisitz   6802: ul.LC_TabContent li a,
                   6803: ul.LC_TabContent li {
                   6804:   color:rgb(47,47,47);
                   6805:   text-decoration:none;
                   6806:   font-size:95%;
                   6807:   font-weight:bold;
1.952     onken    6808:   min-height:20px;
                   6809: }
                   6810: 
1.959     onken    6811: ul.LC_TabContent li a:hover,
                   6812: ul.LC_TabContent li a:focus {
1.952     onken    6813:   color: $button_hover;
1.959     onken    6814:   background:none;
                   6815:   outline:none;
1.952     onken    6816: }
                   6817: 
                   6818: ul.LC_TabContent li:hover {
                   6819:   color: $button_hover;
                   6820:   cursor:pointer;
1.721     harmsja  6821: }
1.795     www      6822: 
1.911     bisitz   6823: ul.LC_TabContent li.active {
1.952     onken    6824:   color: $font;
1.911     bisitz   6825:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6826:   border-bottom:solid 1px #FFFFFF;
                   6827:   cursor: default;
1.744     ehlerst  6828: }
1.795     www      6829: 
1.959     onken    6830: ul.LC_TabContent li.active a {
                   6831:   color:$font;
                   6832:   background:#FFFFFF;
                   6833:   outline: none;
                   6834: }
1.1047    raeburn  6835: 
                   6836: ul.LC_TabContent li.goback {
                   6837:   float: left;
                   6838:   border-left: none;
                   6839: }
                   6840: 
1.870     tempelho 6841: #maincoursedoc {
1.911     bisitz   6842:   clear:both;
1.870     tempelho 6843: }
                   6844: 
                   6845: ul.LC_TabContentBigger {
1.911     bisitz   6846:   display:block;
                   6847:   list-style:none;
                   6848:   padding: 0;
1.870     tempelho 6849: }
                   6850: 
1.795     www      6851: ul.LC_TabContentBigger li {
1.911     bisitz   6852:   vertical-align:bottom;
                   6853:   height: 30px;
                   6854:   font-size:110%;
                   6855:   font-weight:bold;
                   6856:   color: #737373;
1.841     tempelho 6857: }
                   6858: 
1.957     onken    6859: ul.LC_TabContentBigger li.active {
                   6860:   position: relative;
                   6861:   top: 1px;
                   6862: }
                   6863: 
1.870     tempelho 6864: ul.LC_TabContentBigger li a {
1.911     bisitz   6865:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6866:   height: 30px;
                   6867:   line-height: 30px;
                   6868:   text-align: center;
                   6869:   display: block;
                   6870:   text-decoration: none;
1.958     onken    6871:   outline: none;  
1.741     harmsja  6872: }
1.795     www      6873: 
1.870     tempelho 6874: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6875:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6876:   color:$font;
1.744     ehlerst  6877: }
1.795     www      6878: 
1.870     tempelho 6879: ul.LC_TabContentBigger li b {
1.911     bisitz   6880:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6881:   display: block;
                   6882:   float: left;
                   6883:   padding: 0 30px;
1.957     onken    6884:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6885: }
                   6886: 
1.956     onken    6887: ul.LC_TabContentBigger li:hover b {
                   6888:   color:$button_hover;
                   6889: }
                   6890: 
1.870     tempelho 6891: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6892:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6893:   color:$font;
1.957     onken    6894:   border: 0;
1.741     harmsja  6895: }
1.693     droeschl 6896: 
1.870     tempelho 6897: 
1.862     bisitz   6898: ul.LC_CourseBreadcrumbs {
                   6899:   background: $sidebg;
1.1020    raeburn  6900:   height: 2em;
1.862     bisitz   6901:   padding-left: 10px;
1.1020    raeburn  6902:   margin: 0;
1.862     bisitz   6903:   list-style-position: inside;
                   6904: }
                   6905: 
1.911     bisitz   6906: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6907: ol#LC_PathBreadcrumbs {
1.911     bisitz   6908:   padding-left: 10px;
                   6909:   margin: 0;
1.933     droeschl 6910:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6911: }
                   6912: 
1.911     bisitz   6913: ol#LC_MenuBreadcrumbs li,
                   6914: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6915: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6916:   display: inline;
1.933     droeschl 6917:   white-space: normal;  
1.693     droeschl 6918: }
                   6919: 
1.823     bisitz   6920: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6921: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6922:   text-decoration: none;
                   6923:   font-size:90%;
1.693     droeschl 6924: }
1.795     www      6925: 
1.969     droeschl 6926: ol#LC_MenuBreadcrumbs h1 {
                   6927:   display: inline;
                   6928:   font-size: 90%;
                   6929:   line-height: 2.5em;
                   6930:   margin: 0;
                   6931:   padding: 0;
                   6932: }
                   6933: 
1.795     www      6934: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6935:   text-decoration:none;
                   6936:   font-size:100%;
                   6937:   font-weight:bold;
1.693     droeschl 6938: }
1.795     www      6939: 
1.840     bisitz   6940: .LC_Box {
1.911     bisitz   6941:   border: solid 1px $lg_border_color;
                   6942:   padding: 0 10px 10px 10px;
1.746     neumanie 6943: }
1.795     www      6944: 
1.1020    raeburn  6945: .LC_DocsBox {
                   6946:   border: solid 1px $lg_border_color;
                   6947:   padding: 0 0 10px 10px;
                   6948: }
                   6949: 
1.795     www      6950: .LC_AboutMe_Image {
1.911     bisitz   6951:   float:left;
                   6952:   margin-right:10px;
1.747     neumanie 6953: }
1.795     www      6954: 
                   6955: .LC_Clear_AboutMe_Image {
1.911     bisitz   6956:   clear:left;
1.747     neumanie 6957: }
1.795     www      6958: 
1.721     harmsja  6959: dl.LC_ListStyleClean dt {
1.911     bisitz   6960:   padding-right: 5px;
                   6961:   display: table-header-group;
1.693     droeschl 6962: }
                   6963: 
1.721     harmsja  6964: dl.LC_ListStyleClean dd {
1.911     bisitz   6965:   display: table-row;
1.693     droeschl 6966: }
                   6967: 
1.721     harmsja  6968: .LC_ListStyleClean,
                   6969: .LC_ListStyleSimple,
                   6970: .LC_ListStyleNormal,
1.795     www      6971: .LC_ListStyleSpecial {
1.911     bisitz   6972:   /* display:block; */
                   6973:   list-style-position: inside;
                   6974:   list-style-type: none;
                   6975:   overflow: hidden;
                   6976:   padding: 0;
1.693     droeschl 6977: }
                   6978: 
1.721     harmsja  6979: .LC_ListStyleSimple li,
                   6980: .LC_ListStyleSimple dd,
                   6981: .LC_ListStyleNormal li,
                   6982: .LC_ListStyleNormal dd,
                   6983: .LC_ListStyleSpecial li,
1.795     www      6984: .LC_ListStyleSpecial dd {
1.911     bisitz   6985:   margin: 0;
                   6986:   padding: 5px 5px 5px 10px;
                   6987:   clear: both;
1.693     droeschl 6988: }
                   6989: 
1.721     harmsja  6990: .LC_ListStyleClean li,
                   6991: .LC_ListStyleClean dd {
1.911     bisitz   6992:   padding-top: 0;
                   6993:   padding-bottom: 0;
1.693     droeschl 6994: }
                   6995: 
1.721     harmsja  6996: .LC_ListStyleSimple dd,
1.795     www      6997: .LC_ListStyleSimple li {
1.911     bisitz   6998:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6999: }
                   7000: 
1.721     harmsja  7001: .LC_ListStyleSpecial li,
                   7002: .LC_ListStyleSpecial dd {
1.911     bisitz   7003:   list-style-type: none;
                   7004:   background-color: RGB(220, 220, 220);
                   7005:   margin-bottom: 4px;
1.693     droeschl 7006: }
                   7007: 
1.721     harmsja  7008: table.LC_SimpleTable {
1.911     bisitz   7009:   margin:5px;
                   7010:   border:solid 1px $lg_border_color;
1.795     www      7011: }
1.693     droeschl 7012: 
1.721     harmsja  7013: table.LC_SimpleTable tr {
1.911     bisitz   7014:   padding: 0;
                   7015:   border:solid 1px $lg_border_color;
1.693     droeschl 7016: }
1.795     www      7017: 
                   7018: table.LC_SimpleTable thead {
1.911     bisitz   7019:   background:rgb(220,220,220);
1.693     droeschl 7020: }
                   7021: 
1.721     harmsja  7022: div.LC_columnSection {
1.911     bisitz   7023:   display: block;
                   7024:   clear: both;
                   7025:   overflow: hidden;
                   7026:   margin: 0;
1.693     droeschl 7027: }
                   7028: 
1.721     harmsja  7029: div.LC_columnSection>* {
1.911     bisitz   7030:   float: left;
                   7031:   margin: 10px 20px 10px 0;
                   7032:   overflow:hidden;
1.693     droeschl 7033: }
1.721     harmsja  7034: 
1.795     www      7035: table em {
1.911     bisitz   7036:   font-weight: bold;
                   7037:   font-style: normal;
1.748     schulted 7038: }
1.795     www      7039: 
1.779     bisitz   7040: table.LC_tableBrowseRes,
1.795     www      7041: table.LC_tableOfContent {
1.911     bisitz   7042:   border:none;
                   7043:   border-spacing: 1px;
                   7044:   padding: 3px;
                   7045:   background-color: #FFFFFF;
                   7046:   font-size: 90%;
1.753     droeschl 7047: }
1.789     droeschl 7048: 
1.911     bisitz   7049: table.LC_tableOfContent {
                   7050:   border-collapse: collapse;
1.789     droeschl 7051: }
                   7052: 
1.771     droeschl 7053: table.LC_tableBrowseRes a,
1.768     schulted 7054: table.LC_tableOfContent a {
1.911     bisitz   7055:   background-color: transparent;
                   7056:   text-decoration: none;
1.753     droeschl 7057: }
                   7058: 
1.795     www      7059: table.LC_tableOfContent img {
1.911     bisitz   7060:   border: none;
                   7061:   height: 1.3em;
                   7062:   vertical-align: text-bottom;
                   7063:   margin-right: 0.3em;
1.753     droeschl 7064: }
1.757     schulted 7065: 
1.795     www      7066: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7067:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7068: }
                   7069: 
1.795     www      7070: a#LC_content_toolbar_everything {
1.911     bisitz   7071:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7072: }
                   7073: 
1.795     www      7074: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7075:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7076: }
                   7077: 
1.795     www      7078: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7079:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7080: }
                   7081: 
1.795     www      7082: a#LC_content_toolbar_changefolder {
1.911     bisitz   7083:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7084: }
                   7085: 
1.795     www      7086: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7087:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7088: }
                   7089: 
1.1043    raeburn  7090: a#LC_content_toolbar_edittoplevel {
                   7091:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7092: }
                   7093: 
1.795     www      7094: ul#LC_toolbar li a:hover {
1.911     bisitz   7095:   background-position: bottom center;
1.757     schulted 7096: }
                   7097: 
1.795     www      7098: ul#LC_toolbar {
1.911     bisitz   7099:   padding: 0;
                   7100:   margin: 2px;
                   7101:   list-style:none;
                   7102:   position:relative;
                   7103:   background-color:white;
1.1075.2.9  raeburn  7104:   overflow: auto;
1.757     schulted 7105: }
                   7106: 
1.795     www      7107: ul#LC_toolbar li {
1.911     bisitz   7108:   border:1px solid white;
                   7109:   padding: 0;
                   7110:   margin: 0;
                   7111:   float: left;
                   7112:   display:inline;
                   7113:   vertical-align:middle;
1.1075.2.9  raeburn  7114:   white-space: nowrap;
1.911     bisitz   7115: }
1.757     schulted 7116: 
1.783     amueller 7117: 
1.795     www      7118: a.LC_toolbarItem {
1.911     bisitz   7119:   display:block;
                   7120:   padding: 0;
                   7121:   margin: 0;
                   7122:   height: 32px;
                   7123:   width: 32px;
                   7124:   color:white;
                   7125:   border: none;
                   7126:   background-repeat:no-repeat;
                   7127:   background-color:transparent;
1.757     schulted 7128: }
                   7129: 
1.915     droeschl 7130: ul.LC_funclist {
                   7131:     margin: 0;
                   7132:     padding: 0.5em 1em 0.5em 0;
                   7133: }
                   7134: 
1.933     droeschl 7135: ul.LC_funclist > li:first-child {
                   7136:     font-weight:bold; 
                   7137:     margin-left:0.8em;
                   7138: }
                   7139: 
1.915     droeschl 7140: ul.LC_funclist + ul.LC_funclist {
                   7141:     /* 
                   7142:        left border as a seperator if we have more than
                   7143:        one list 
                   7144:     */
                   7145:     border-left: 1px solid $sidebg;
                   7146:     /* 
                   7147:        this hides the left border behind the border of the 
                   7148:        outer box if element is wrapped to the next 'line' 
                   7149:     */
                   7150:     margin-left: -1px;
                   7151: }
                   7152: 
1.843     bisitz   7153: ul.LC_funclist li {
1.915     droeschl 7154:   display: inline;
1.782     bisitz   7155:   white-space: nowrap;
1.915     droeschl 7156:   margin: 0 0 0 25px;
                   7157:   line-height: 150%;
1.782     bisitz   7158: }
                   7159: 
1.974     wenzelju 7160: .LC_hidden {
                   7161:   display: none;
                   7162: }
                   7163: 
1.1030    www      7164: .LCmodal-overlay {
                   7165: 		position:fixed;
                   7166: 		top:0;
                   7167: 		right:0;
                   7168: 		bottom:0;
                   7169: 		left:0;
                   7170: 		height:100%;
                   7171: 		width:100%;
                   7172: 		margin:0;
                   7173: 		padding:0;
                   7174: 		background:#999;
                   7175: 		opacity:.75;
                   7176: 		filter: alpha(opacity=75);
                   7177: 		-moz-opacity: 0.75;
                   7178: 		z-index:101;
                   7179: }
                   7180: 
                   7181: * html .LCmodal-overlay {   
                   7182: 		position: absolute;
                   7183: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7184: }
                   7185: 
                   7186: .LCmodal-window {
                   7187: 		position:fixed;
                   7188: 		top:50%;
                   7189: 		left:50%;
                   7190: 		margin:0;
                   7191: 		padding:0;
                   7192: 		z-index:102;
                   7193: 	}
                   7194: 
                   7195: * html .LCmodal-window {
                   7196: 		position:absolute;
                   7197: }
                   7198: 
                   7199: .LCclose-window {
                   7200: 		position:absolute;
                   7201: 		width:32px;
                   7202: 		height:32px;
                   7203: 		right:8px;
                   7204: 		top:8px;
                   7205: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7206: 		text-indent:-99999px;
                   7207: 		overflow:hidden;
                   7208: 		cursor:pointer;
                   7209: }
                   7210: 
1.1075.2.17  raeburn  7211: /*
                   7212:   styles used by TTH when "Default set of options to pass to tth/m
                   7213:   when converting TeX" in course settings has been set
                   7214: 
                   7215:   option passed: -t
                   7216: 
                   7217: */
                   7218: 
                   7219: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7220: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7221: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7222: td div.norm {line-height:normal;}
                   7223: 
                   7224: /*
                   7225:   option passed -y3
                   7226: */
                   7227: 
                   7228: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7229: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7230: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7231: 
1.343     albertel 7232: END
                   7233: }
                   7234: 
1.306     albertel 7235: =pod
                   7236: 
                   7237: =item * &headtag()
                   7238: 
                   7239: Returns a uniform footer for LON-CAPA web pages.
                   7240: 
1.307     albertel 7241: Inputs: $title - optional title for the head
                   7242:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7243:         $args - optional arguments
1.319     albertel 7244:             force_register - if is true call registerurl so the remote is 
                   7245:                              informed
1.415     albertel 7246:             redirect       -> array ref of
                   7247:                                    1- seconds before redirect occurs
                   7248:                                    2- url to redirect to
                   7249:                                    3- whether the side effect should occur
1.315     albertel 7250:                            (side effect of setting 
                   7251:                                $env{'internal.head.redirect'} to the url 
                   7252:                                redirected too)
1.352     albertel 7253:             domain         -> force to color decorate a page for a specific
                   7254:                                domain
                   7255:             function       -> force usage of a specific rolish color scheme
                   7256:             bgcolor        -> override the default page bgcolor
1.460     albertel 7257:             no_auto_mt_title
                   7258:                            -> prevent &mt()ing the title arg
1.464     albertel 7259: 
1.306     albertel 7260: =cut
                   7261: 
                   7262: sub headtag {
1.313     albertel 7263:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7264:     
1.363     albertel 7265:     my $function = $args->{'function'} || &get_users_function();
                   7266:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7267:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7268:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7269:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7270: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7271: 		   #time(),
1.418     albertel 7272: 		   $env{'environment.color.timestamp'},
1.363     albertel 7273: 		   $function,$domain,$bgcolor);
                   7274: 
1.369     www      7275:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7276: 
1.308     albertel 7277:     my $result =
                   7278: 	'<head>'.
1.1075.2.56  raeburn  7279: 	&font_settings($args);
1.319     albertel 7280: 
1.1064    raeburn  7281:     my $inhibitprint = &print_suppression();
                   7282: 
1.461     albertel 7283:     if (!$args->{'frameset'}) {
                   7284: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7285:     }
1.1075.2.12  raeburn  7286:     if ($args->{'force_register'}) {
                   7287:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7288:     }
1.436     albertel 7289:     if (!$args->{'no_nav_bar'} 
                   7290: 	&& !$args->{'only_body'}
                   7291: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7292: 	$result .= &help_menu_js($httphost);
1.1032    www      7293:         $result.=&modal_window();
1.1038    www      7294:         $result.=&togglebox_script();
1.1034    www      7295:         $result.=&wishlist_window();
1.1041    www      7296:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7297:     } else {
                   7298:         if ($args->{'add_modal'}) {
                   7299:            $result.=&modal_window();
                   7300:         }
                   7301:         if ($args->{'add_wishlist'}) {
                   7302:            $result.=&wishlist_window();
                   7303:         }
1.1038    www      7304:         if ($args->{'add_togglebox'}) {
                   7305:            $result.=&togglebox_script();
                   7306:         }
1.1041    www      7307:         if ($args->{'add_progressbar'}) {
                   7308:            $result.=&LCprogressbarUpdate_script();
                   7309:         }
1.436     albertel 7310:     }
1.314     albertel 7311:     if (ref($args->{'redirect'})) {
1.414     albertel 7312: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7313: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7314: 	if (!$inhibit_continue) {
                   7315: 	    $env{'internal.head.redirect'} = $url;
                   7316: 	}
1.313     albertel 7317: 	$result.=<<ADDMETA
                   7318: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7319: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7320: ADDMETA
                   7321:     }
1.306     albertel 7322:     if (!defined($title)) {
                   7323: 	$title = 'The LearningOnline Network with CAPA';
                   7324:     }
1.460     albertel 7325:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7326:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7327: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7328:         .$inhibitprint
1.414     albertel 7329: 	.$head_extra;
1.1075.2.42  raeburn  7330:     if ($env{'browser.mobile'}) {
                   7331:         $result .= '
                   7332: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7333: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7334:     }
1.962     droeschl 7335:     return $result.'</head>';
1.306     albertel 7336: }
                   7337: 
                   7338: =pod
                   7339: 
1.340     albertel 7340: =item * &font_settings()
                   7341: 
                   7342: Returns neccessary <meta> to set the proper encoding
                   7343: 
1.1075.2.56  raeburn  7344: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7345: 
                   7346: =cut
                   7347: 
                   7348: sub font_settings {
1.1075.2.56  raeburn  7349:     my ($args) = @_;
1.340     albertel 7350:     my $headerstring='';
1.1075.2.56  raeburn  7351:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7352:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7353: 	$headerstring.=
1.1075.2.56  raeburn  7354: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n";
1.340     albertel 7355:     }
                   7356:     return $headerstring;
                   7357: }
                   7358: 
1.341     albertel 7359: =pod
                   7360: 
1.1064    raeburn  7361: =item * &print_suppression()
                   7362: 
                   7363: In course context returns css which causes the body to be blank when media="print",
                   7364: if printout generation is unavailable for the current resource.
                   7365: 
                   7366: This could be because:
                   7367: 
                   7368: (a) printstartdate is in the future
                   7369: 
                   7370: (b) printenddate is in the past
                   7371: 
                   7372: (c) there is an active exam block with "printout"
                   7373: functionality blocked
                   7374: 
                   7375: Users with pav, pfo or evb privileges are exempt.
                   7376: 
                   7377: Inputs: none
                   7378: 
                   7379: =cut
                   7380: 
                   7381: 
                   7382: sub print_suppression {
                   7383:     my $noprint;
                   7384:     if ($env{'request.course.id'}) {
                   7385:         my $scope = $env{'request.course.id'};
                   7386:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7387:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7388:             return;
                   7389:         }
                   7390:         if ($env{'request.course.sec'} ne '') {
                   7391:             $scope .= "/$env{'request.course.sec'}";
                   7392:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7393:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7394:                 return;
1.1064    raeburn  7395:             }
                   7396:         }
                   7397:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7398:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7399:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7400:         if ($blocked) {
                   7401:             my $checkrole = "cm./$cdom/$cnum";
                   7402:             if ($env{'request.course.sec'} ne '') {
                   7403:                 $checkrole .= "/$env{'request.course.sec'}";
                   7404:             }
                   7405:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7406:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7407:                 $noprint = 1;
                   7408:             }
                   7409:         }
                   7410:         unless ($noprint) {
                   7411:             my $symb = &Apache::lonnet::symbread();
                   7412:             if ($symb ne '') {
                   7413:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7414:                 if (ref($navmap)) {
                   7415:                     my $res = $navmap->getBySymb($symb);
                   7416:                     if (ref($res)) {
                   7417:                         if (!$res->resprintable()) {
                   7418:                             $noprint = 1;
                   7419:                         }
                   7420:                     }
                   7421:                 }
                   7422:             }
                   7423:         }
                   7424:         if ($noprint) {
                   7425:             return <<"ENDSTYLE";
                   7426: <style type="text/css" media="print">
                   7427:     body { display:none }
                   7428: </style>
                   7429: ENDSTYLE
                   7430:         }
                   7431:     }
                   7432:     return;
                   7433: }
                   7434: 
                   7435: =pod
                   7436: 
1.341     albertel 7437: =item * &xml_begin()
                   7438: 
                   7439: Returns the needed doctype and <html>
                   7440: 
                   7441: Inputs: none
                   7442: 
                   7443: =cut
                   7444: 
                   7445: sub xml_begin {
                   7446:     my $output='';
                   7447: 
                   7448:     if ($env{'browser.mathml'}) {
                   7449: 	$output='<?xml version="1.0"?>'
                   7450:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7451: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7452:             
                   7453: #	    .'<!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">] >'
                   7454: 	    .'<!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">'
                   7455:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7456: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7457:     } else {
1.1075.2.56  raeburn  7458: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n"
                   7459:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7460:     }
                   7461:     return $output;
                   7462: }
1.340     albertel 7463: 
                   7464: =pod
                   7465: 
1.306     albertel 7466: =item * &start_page()
                   7467: 
                   7468: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7469: 
1.648     raeburn  7470: Inputs:
                   7471: 
                   7472: =over 4
                   7473: 
                   7474: $title - optional title for the page
                   7475: 
                   7476: $head_extra - optional extra HTML to incude inside the <head>
                   7477: 
                   7478: $args - additional optional args supported are:
                   7479: 
                   7480: =over 8
                   7481: 
                   7482:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7483:                                     arg on
1.814     bisitz   7484:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7485:              add_entries    -> additional attributes to add to the  <body>
                   7486:              domain         -> force to color decorate a page for a 
1.317     albertel 7487:                                     specific domain
1.648     raeburn  7488:              function       -> force usage of a specific rolish color
1.317     albertel 7489:                                     scheme
1.648     raeburn  7490:              redirect       -> see &headtag()
                   7491:              bgcolor        -> override the default page bg color
                   7492:              js_ready       -> return a string ready for being used in 
1.317     albertel 7493:                                     a javascript writeln
1.648     raeburn  7494:              html_encode    -> return a string ready for being used in 
1.320     albertel 7495:                                     a html attribute
1.648     raeburn  7496:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7497:                                     $forcereg arg
1.648     raeburn  7498:              frameset       -> if true will start with a <frameset>
1.330     albertel 7499:                                     rather than <body>
1.648     raeburn  7500:              skip_phases    -> hash ref of 
1.338     albertel 7501:                                     head -> skip the <html><head> generation
                   7502:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7503:              no_inline_link -> if true and in remote mode, don't show the
                   7504:                                     'Switch To Inline Menu' link
1.648     raeburn  7505:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7506:              inherit_jsmath -> when creating popup window in a page,
                   7507:                                     should it have jsmath forced on by the
                   7508:                                     current page
1.867     kalberla 7509:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7510:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7511:              group          -> includes the current group, if page is for a
                   7512:                                specific group
1.361     albertel 7513: 
1.648     raeburn  7514: =back
1.460     albertel 7515: 
1.648     raeburn  7516: =back
1.562     albertel 7517: 
1.306     albertel 7518: =cut
                   7519: 
                   7520: sub start_page {
1.309     albertel 7521:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7522:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7523: 
1.315     albertel 7524:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7525:     my ($result,@advtools);
1.964     droeschl 7526: 
1.338     albertel 7527:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7528:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7529:     }
                   7530:     
                   7531:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7532: 	if ($args->{'frameset'}) {
                   7533: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7534: 						$args->{'add_entries'});
                   7535: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7536:         } else {
                   7537:             $result .=
                   7538:                 &bodytag($title, 
                   7539:                          $args->{'function'},       $args->{'add_entries'},
                   7540:                          $args->{'only_body'},      $args->{'domain'},
                   7541:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7542:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7543:                          $args,                     \@advtools);
1.831     bisitz   7544:         }
1.330     albertel 7545:     }
1.338     albertel 7546: 
1.315     albertel 7547:     if ($args->{'js_ready'}) {
1.713     kaisler  7548: 		$result = &js_ready($result);
1.315     albertel 7549:     }
1.320     albertel 7550:     if ($args->{'html_encode'}) {
1.713     kaisler  7551: 		$result = &html_encode($result);
                   7552:     }
                   7553: 
1.813     bisitz   7554:     # Preparation for new and consistent functionlist at top of screen
                   7555:     # if ($args->{'functionlist'}) {
                   7556:     #            $result .= &build_functionlist();
                   7557:     #}
                   7558: 
1.964     droeschl 7559:     # Don't add anything more if only_body wanted or in const space
                   7560:     return $result if    $args->{'only_body'} 
                   7561:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7562: 
                   7563:     #Breadcrumbs
1.758     kaisler  7564:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7565: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7566: 		#if any br links exists, add them to the breadcrumbs
                   7567: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7568: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7569: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7570: 			}
                   7571: 		}
1.1075.2.19  raeburn  7572:                 # if @advtools array contains items add then to the breadcrumbs
                   7573:                 if (@advtools > 0) {
                   7574:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7575:                 }
1.758     kaisler  7576: 
                   7577: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7578: 		if(exists($args->{'bread_crumbs_component'})){
                   7579: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7580: 		}else{
                   7581: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7582: 		}
1.1075.2.24  raeburn  7583:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7584:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7585:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7586:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7587:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7588:     }
1.315     albertel 7589:     return $result;
1.306     albertel 7590: }
                   7591: 
                   7592: sub end_page {
1.315     albertel 7593:     my ($args) = @_;
                   7594:     $env{'internal.end_page'}++;
1.330     albertel 7595:     my $result;
1.335     albertel 7596:     if ($args->{'discussion'}) {
                   7597: 	my ($target,$parser);
                   7598: 	if (ref($args->{'discussion'})) {
                   7599: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7600: 				$args->{'discussion'}{'parser'});
                   7601: 	}
                   7602: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7603:     }
1.330     albertel 7604:     if ($args->{'frameset'}) {
                   7605: 	$result .= '</frameset>';
                   7606:     } else {
1.635     raeburn  7607: 	$result .= &endbodytag($args);
1.330     albertel 7608:     }
1.1075.2.6  raeburn  7609:     unless ($args->{'notbody'}) {
                   7610:         $result .= "\n</html>";
                   7611:     }
1.330     albertel 7612: 
1.315     albertel 7613:     if ($args->{'js_ready'}) {
1.317     albertel 7614: 	$result = &js_ready($result);
1.315     albertel 7615:     }
1.335     albertel 7616: 
1.320     albertel 7617:     if ($args->{'html_encode'}) {
                   7618: 	$result = &html_encode($result);
                   7619:     }
1.335     albertel 7620: 
1.315     albertel 7621:     return $result;
                   7622: }
                   7623: 
1.1034    www      7624: sub wishlist_window {
                   7625:     return(<<'ENDWISHLIST');
1.1046    raeburn  7626: <script type="text/javascript">
1.1034    www      7627: // <![CDATA[
                   7628: // <!-- BEGIN LON-CAPA Internal
                   7629: function set_wishlistlink(title, path) {
                   7630:     if (!title) {
                   7631:         title = document.title;
                   7632:         title = title.replace(/^LON-CAPA /,'');
                   7633:     }
                   7634:     if (!path) {
                   7635:         path = location.pathname;
                   7636:     }
                   7637:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7638:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7639: }
                   7640: // END LON-CAPA Internal -->
                   7641: // ]]>
                   7642: </script>
                   7643: ENDWISHLIST
                   7644: }
                   7645: 
1.1030    www      7646: sub modal_window {
                   7647:     return(<<'ENDMODAL');
1.1046    raeburn  7648: <script type="text/javascript">
1.1030    www      7649: // <![CDATA[
                   7650: // <!-- BEGIN LON-CAPA Internal
                   7651: var modalWindow = {
                   7652: 	parent:"body",
                   7653: 	windowId:null,
                   7654: 	content:null,
                   7655: 	width:null,
                   7656: 	height:null,
                   7657: 	close:function()
                   7658: 	{
                   7659: 	        $(".LCmodal-window").remove();
                   7660: 	        $(".LCmodal-overlay").remove();
                   7661: 	},
                   7662: 	open:function()
                   7663: 	{
                   7664: 		var modal = "";
                   7665: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7666: 		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;\">";
                   7667: 		modal += this.content;
                   7668: 		modal += "</div>";	
                   7669: 
                   7670: 		$(this.parent).append(modal);
                   7671: 
                   7672: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7673: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7674: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7675: 	}
                   7676: };
1.1075.2.42  raeburn  7677: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7678: 	{
                   7679: 		modalWindow.windowId = "myModal";
                   7680: 		modalWindow.width = width;
                   7681: 		modalWindow.height = height;
1.1075.2.42  raeburn  7682: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
1.1030    www      7683: 		modalWindow.open();
                   7684: 	};	
                   7685: // END LON-CAPA Internal -->
                   7686: // ]]>
                   7687: </script>
                   7688: ENDMODAL
                   7689: }
                   7690: 
                   7691: sub modal_link {
1.1075.2.42  raeburn  7692:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7693:     unless ($width) { $width=480; }
                   7694:     unless ($height) { $height=400; }
1.1031    www      7695:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  7696:     unless ($transparency) { $transparency='true'; }
                   7697: 
1.1074    raeburn  7698:     my $target_attr;
                   7699:     if (defined($target)) {
                   7700:         $target_attr = 'target="'.$target.'"';
                   7701:     }
                   7702:     return <<"ENDLINK";
1.1075.2.42  raeburn  7703: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7704:            $linktext</a>
                   7705: ENDLINK
1.1030    www      7706: }
                   7707: 
1.1032    www      7708: sub modal_adhoc_script {
                   7709:     my ($funcname,$width,$height,$content)=@_;
                   7710:     return (<<ENDADHOC);
1.1046    raeburn  7711: <script type="text/javascript">
1.1032    www      7712: // <![CDATA[
                   7713:         var $funcname = function()
                   7714:         {
                   7715:                 modalWindow.windowId = "myModal";
                   7716:                 modalWindow.width = $width;
                   7717:                 modalWindow.height = $height;
                   7718:                 modalWindow.content = '$content';
                   7719:                 modalWindow.open();
                   7720:         };  
                   7721: // ]]>
                   7722: </script>
                   7723: ENDADHOC
                   7724: }
                   7725: 
1.1041    www      7726: sub modal_adhoc_inner {
                   7727:     my ($funcname,$width,$height,$content)=@_;
                   7728:     my $innerwidth=$width-20;
                   7729:     $content=&js_ready(
1.1042    www      7730:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  7731:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7732:                  $content.
1.1041    www      7733:                  &end_scrollbox().
1.1075.2.42  raeburn  7734:                  &end_page()
1.1041    www      7735:              );
                   7736:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7737: }
                   7738: 
                   7739: sub modal_adhoc_window {
                   7740:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7741:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7742:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7743: }
                   7744: 
                   7745: sub modal_adhoc_launch {
                   7746:     my ($funcname,$width,$height,$content)=@_;
                   7747:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7748: <script type="text/javascript">
                   7749: // <![CDATA[
                   7750: $funcname();
                   7751: // ]]>
                   7752: </script>
                   7753: ENDLAUNCH
                   7754: }
                   7755: 
                   7756: sub modal_adhoc_close {
                   7757:     return (<<ENDCLOSE);
                   7758: <script type="text/javascript">
                   7759: // <![CDATA[
                   7760: modalWindow.close();
                   7761: // ]]>
                   7762: </script>
                   7763: ENDCLOSE
                   7764: }
                   7765: 
1.1038    www      7766: sub togglebox_script {
                   7767:    return(<<ENDTOGGLE);
                   7768: <script type="text/javascript"> 
                   7769: // <![CDATA[
                   7770: function LCtoggleDisplay(id,hidetext,showtext) {
                   7771:    link = document.getElementById(id + "link").childNodes[0];
                   7772:    with (document.getElementById(id).style) {
                   7773:       if (display == "none" ) {
                   7774:           display = "inline";
                   7775:           link.nodeValue = hidetext;
                   7776:         } else {
                   7777:           display = "none";
                   7778:           link.nodeValue = showtext;
                   7779:        }
                   7780:    }
                   7781: }
                   7782: // ]]>
                   7783: </script>
                   7784: ENDTOGGLE
                   7785: }
                   7786: 
1.1039    www      7787: sub start_togglebox {
                   7788:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7789:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7790:     unless ($showtext) { $showtext=&mt('show'); }
                   7791:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7792:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7793:     return &start_data_table().
                   7794:            &start_data_table_header_row().
                   7795:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7796:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7797:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7798:            &end_data_table_header_row().
                   7799:            '<tr id="'.$id.'" style="display:none""><td>';
                   7800: }
                   7801: 
                   7802: sub end_togglebox {
                   7803:     return '</td></tr>'.&end_data_table();
                   7804: }
                   7805: 
1.1041    www      7806: sub LCprogressbar_script {
1.1045    www      7807:    my ($id)=@_;
1.1041    www      7808:    return(<<ENDPROGRESS);
                   7809: <script type="text/javascript">
                   7810: // <![CDATA[
1.1045    www      7811: \$('#progressbar$id').progressbar({
1.1041    www      7812:   value: 0,
                   7813:   change: function(event, ui) {
                   7814:     var newVal = \$(this).progressbar('option', 'value');
                   7815:     \$('.pblabel', this).text(LCprogressTxt);
                   7816:   }
                   7817: });
                   7818: // ]]>
                   7819: </script>
                   7820: ENDPROGRESS
                   7821: }
                   7822: 
                   7823: sub LCprogressbarUpdate_script {
                   7824:    return(<<ENDPROGRESSUPDATE);
                   7825: <style type="text/css">
                   7826: .ui-progressbar { position:relative; }
                   7827: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7828: </style>
                   7829: <script type="text/javascript">
                   7830: // <![CDATA[
1.1045    www      7831: var LCprogressTxt='---';
                   7832: 
                   7833: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7834:    LCprogressTxt=progresstext;
1.1045    www      7835:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7836: }
                   7837: // ]]>
                   7838: </script>
                   7839: ENDPROGRESSUPDATE
                   7840: }
                   7841: 
1.1042    www      7842: my $LClastpercent;
1.1045    www      7843: my $LCidcnt;
                   7844: my $LCcurrentid;
1.1042    www      7845: 
1.1041    www      7846: sub LCprogressbar {
1.1042    www      7847:     my ($r)=(@_);
                   7848:     $LClastpercent=0;
1.1045    www      7849:     $LCidcnt++;
                   7850:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7851:     my $starting=&mt('Starting');
                   7852:     my $content=(<<ENDPROGBAR);
1.1045    www      7853:   <div id="progressbar$LCcurrentid">
1.1041    www      7854:     <span class="pblabel">$starting</span>
                   7855:   </div>
                   7856: ENDPROGBAR
1.1045    www      7857:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7858: }
                   7859: 
                   7860: sub LCprogressbarUpdate {
1.1042    www      7861:     my ($r,$val,$text)=@_;
                   7862:     unless ($val) { 
                   7863:        if ($LClastpercent) {
                   7864:            $val=$LClastpercent;
                   7865:        } else {
                   7866:            $val=0;
                   7867:        }
                   7868:     }
1.1041    www      7869:     if ($val<0) { $val=0; }
                   7870:     if ($val>100) { $val=0; }
1.1042    www      7871:     $LClastpercent=$val;
1.1041    www      7872:     unless ($text) { $text=$val.'%'; }
                   7873:     $text=&js_ready($text);
1.1044    www      7874:     &r_print($r,<<ENDUPDATE);
1.1041    www      7875: <script type="text/javascript">
                   7876: // <![CDATA[
1.1045    www      7877: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7878: // ]]>
                   7879: </script>
                   7880: ENDUPDATE
1.1035    www      7881: }
                   7882: 
1.1042    www      7883: sub LCprogressbarClose {
                   7884:     my ($r)=@_;
                   7885:     $LClastpercent=0;
1.1044    www      7886:     &r_print($r,<<ENDCLOSE);
1.1042    www      7887: <script type="text/javascript">
                   7888: // <![CDATA[
1.1045    www      7889: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7890: // ]]>
                   7891: </script>
                   7892: ENDCLOSE
1.1044    www      7893: }
                   7894: 
                   7895: sub r_print {
                   7896:     my ($r,$to_print)=@_;
                   7897:     if ($r) {
                   7898:       $r->print($to_print);
                   7899:       $r->rflush();
                   7900:     } else {
                   7901:       print($to_print);
                   7902:     }
1.1042    www      7903: }
                   7904: 
1.320     albertel 7905: sub html_encode {
                   7906:     my ($result) = @_;
                   7907: 
1.322     albertel 7908:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7909:     
                   7910:     return $result;
                   7911: }
1.1044    www      7912: 
1.317     albertel 7913: sub js_ready {
                   7914:     my ($result) = @_;
                   7915: 
1.323     albertel 7916:     $result =~ s/[\n\r]/ /xmsg;
                   7917:     $result =~ s/\\/\\\\/xmsg;
                   7918:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7919:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7920:     
                   7921:     return $result;
                   7922: }
                   7923: 
1.315     albertel 7924: sub validate_page {
                   7925:     if (  exists($env{'internal.start_page'})
1.316     albertel 7926: 	  &&     $env{'internal.start_page'} > 1) {
                   7927: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7928: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7929: 				 $ENV{'request.filename'});
1.315     albertel 7930:     }
                   7931:     if (  exists($env{'internal.end_page'})
1.316     albertel 7932: 	  &&     $env{'internal.end_page'} > 1) {
                   7933: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7934: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7935: 				 $env{'request.filename'});
1.315     albertel 7936:     }
                   7937:     if (     exists($env{'internal.start_page'})
                   7938: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7939: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7940: 				 $env{'request.filename'});
1.315     albertel 7941:     }
                   7942:     if (   ! exists($env{'internal.start_page'})
                   7943: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7944: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7945: 				 $env{'request.filename'});
1.315     albertel 7946:     }
1.306     albertel 7947: }
1.315     albertel 7948: 
1.996     www      7949: 
                   7950: sub start_scrollbox {
1.1075.2.56  raeburn  7951:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  7952:     unless ($outerwidth) { $outerwidth='520px'; }
                   7953:     unless ($width) { $width='500px'; }
                   7954:     unless ($height) { $height='200px'; }
1.1075    raeburn  7955:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7956:     if ($id ne '') {
1.1075.2.42  raeburn  7957:         $table_id = ' id="table_'.$id.'"';
                   7958:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  7959:     }
1.1075    raeburn  7960:     if ($bgcolor ne '') {
                   7961:         $tdcol = "background-color: $bgcolor;";
                   7962:     }
1.1075.2.42  raeburn  7963:     my $nicescroll_js;
                   7964:     if ($env{'browser.mobile'}) {
                   7965:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   7966:     }
1.1075    raeburn  7967:     return <<"END";
1.1075.2.42  raeburn  7968: $nicescroll_js
                   7969: 
                   7970: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  7971: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  7972: END
1.996     www      7973: }
                   7974: 
                   7975: sub end_scrollbox {
1.1036    www      7976:     return '</div></td></tr></table>';
1.996     www      7977: }
                   7978: 
1.1075.2.42  raeburn  7979: sub nicescroll_javascript {
                   7980:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   7981:     my %options;
                   7982:     if (ref($cursor) eq 'HASH') {
                   7983:         %options = %{$cursor};
                   7984:     }
                   7985:     unless ($options{'railalign'} =~ /^left|right$/) {
                   7986:         $options{'railalign'} = 'left';
                   7987:     }
                   7988:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   7989:         my $function  = &get_users_function();
                   7990:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   7991:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   7992:             $options{'cursorcolor'} = '#00F';
                   7993:         }
                   7994:     }
                   7995:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   7996:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   7997:             $options{'cursoropacity'}='1.0';
                   7998:         }
                   7999:     } else {
                   8000:         $options{'cursoropacity'}='1.0';
                   8001:     }
                   8002:     if ($options{'cursorfixedheight'} eq 'none') {
                   8003:         delete($options{'cursorfixedheight'});
                   8004:     } else {
                   8005:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8006:     }
                   8007:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8008:         delete($options{'railoffset'});
                   8009:     }
                   8010:     my @niceoptions;
                   8011:     while (my($key,$value) = each(%options)) {
                   8012:         if ($value =~ /^\{.+\}$/) {
                   8013:             push(@niceoptions,$key.':'.$value);
                   8014:         } else {
                   8015:             push(@niceoptions,$key.':"'.$value.'"');
                   8016:         }
                   8017:     }
                   8018:     my $nicescroll_js = '
                   8019: $(document).ready(
                   8020:       function() {
                   8021:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8022:       }
                   8023: );
                   8024: ';
                   8025:     if ($framecheck) {
                   8026:         $nicescroll_js .= '
                   8027: function expand_div(caller) {
                   8028:     if (top === self) {
                   8029:         document.getElementById("'.$id.'").style.width = "auto";
                   8030:         document.getElementById("'.$id.'").style.height = "auto";
                   8031:     } else {
                   8032:         try {
                   8033:             if (parent.frames) {
                   8034:                 if (parent.frames.length > 1) {
                   8035:                     var framesrc = parent.frames[1].location.href;
                   8036:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8037:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8038:                         document.getElementById("'.$id.'").style.width = "auto";
                   8039:                         document.getElementById("'.$id.'").style.height = "auto";
                   8040:                     }
                   8041:                 }
                   8042:             }
                   8043:         } catch (e) {
                   8044:             return;
                   8045:         }
                   8046:     }
                   8047:     return;
                   8048: }
                   8049: ';
                   8050:     }
                   8051:     if ($needjsready) {
                   8052:         $nicescroll_js = '
                   8053: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8054:     } else {
                   8055:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8056:     }
                   8057:     return $nicescroll_js;
                   8058: }
                   8059: 
1.318     albertel 8060: sub simple_error_page {
1.1075.2.49  raeburn  8061:     my ($r,$title,$msg,$args) = @_;
                   8062:     if (ref($args) eq 'HASH') {
                   8063:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8064:     } else {
                   8065:         $msg = &mt($msg);
                   8066:     }
                   8067: 
1.318     albertel 8068:     my $page =
                   8069: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8070: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8071: 	&Apache::loncommon::end_page();
                   8072:     if (ref($r)) {
                   8073: 	$r->print($page);
1.327     albertel 8074: 	return;
1.318     albertel 8075:     }
                   8076:     return $page;
                   8077: }
1.347     albertel 8078: 
                   8079: {
1.610     albertel 8080:     my @row_count;
1.961     onken    8081: 
                   8082:     sub start_data_table_count {
                   8083:         unshift(@row_count, 0);
                   8084:         return;
                   8085:     }
                   8086: 
                   8087:     sub end_data_table_count {
                   8088:         shift(@row_count);
                   8089:         return;
                   8090:     }
                   8091: 
1.347     albertel 8092:     sub start_data_table {
1.1018    raeburn  8093: 	my ($add_class,$id) = @_;
1.422     albertel 8094: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8095:         my $table_id;
                   8096:         if (defined($id)) {
                   8097:             $table_id = ' id="'.$id.'"';
                   8098:         }
1.961     onken    8099: 	&start_data_table_count();
1.1018    raeburn  8100: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8101:     }
                   8102: 
                   8103:     sub end_data_table {
1.961     onken    8104: 	&end_data_table_count();
1.389     albertel 8105: 	return '</table>'."\n";;
1.347     albertel 8106:     }
                   8107: 
                   8108:     sub start_data_table_row {
1.974     wenzelju 8109: 	my ($add_class, $id) = @_;
1.610     albertel 8110: 	$row_count[0]++;
                   8111: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8112: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8113:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8114:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8115:     }
1.471     banghart 8116:     
                   8117:     sub continue_data_table_row {
1.974     wenzelju 8118: 	my ($add_class, $id) = @_;
1.610     albertel 8119: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8120: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8121:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8122:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8123:     }
1.347     albertel 8124: 
                   8125:     sub end_data_table_row {
1.389     albertel 8126: 	return '</tr>'."\n";;
1.347     albertel 8127:     }
1.367     www      8128: 
1.421     albertel 8129:     sub start_data_table_empty_row {
1.707     bisitz   8130: #	$row_count[0]++;
1.421     albertel 8131: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8132:     }
                   8133: 
                   8134:     sub end_data_table_empty_row {
                   8135: 	return '</tr>'."\n";;
                   8136:     }
                   8137: 
1.367     www      8138:     sub start_data_table_header_row {
1.389     albertel 8139: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8140:     }
                   8141: 
                   8142:     sub end_data_table_header_row {
1.389     albertel 8143: 	return '</tr>'."\n";;
1.367     www      8144:     }
1.890     droeschl 8145: 
                   8146:     sub data_table_caption {
                   8147:         my $caption = shift;
                   8148:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8149:     }
1.347     albertel 8150: }
                   8151: 
1.548     albertel 8152: =pod
                   8153: 
                   8154: =item * &inhibit_menu_check($arg)
                   8155: 
                   8156: Checks for a inhibitmenu state and generates output to preserve it
                   8157: 
                   8158: Inputs:         $arg - can be any of
                   8159:                      - undef - in which case the return value is a string 
                   8160:                                to add  into arguments list of a uri
                   8161:                      - 'input' - in which case the return value is a HTML
                   8162:                                  <form> <input> field of type hidden to
                   8163:                                  preserve the value
                   8164:                      - a url - in which case the return value is the url with
                   8165:                                the neccesary cgi args added to preserve the
                   8166:                                inhibitmenu state
                   8167:                      - a ref to a url - no return value, but the string is
                   8168:                                         updated to include the neccessary cgi
                   8169:                                         args to preserve the inhibitmenu state
                   8170: 
                   8171: =cut
                   8172: 
                   8173: sub inhibit_menu_check {
                   8174:     my ($arg) = @_;
                   8175:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8176:     if ($arg eq 'input') {
                   8177: 	if ($env{'form.inhibitmenu'}) {
                   8178: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8179: 	} else {
                   8180: 	    return
                   8181: 	}
                   8182:     }
                   8183:     if ($env{'form.inhibitmenu'}) {
                   8184: 	if (ref($arg)) {
                   8185: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8186: 	} elsif ($arg eq '') {
                   8187: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8188: 	} else {
                   8189: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8190: 	}
                   8191:     }
                   8192:     if (!ref($arg)) {
                   8193: 	return $arg;
                   8194:     }
                   8195: }
                   8196: 
1.251     albertel 8197: ###############################################
1.182     matthew  8198: 
                   8199: =pod
                   8200: 
1.549     albertel 8201: =back
                   8202: 
                   8203: =head1 User Information Routines
                   8204: 
                   8205: =over 4
                   8206: 
1.405     albertel 8207: =item * &get_users_function()
1.182     matthew  8208: 
                   8209: Used by &bodytag to determine the current users primary role.
                   8210: Returns either 'student','coordinator','admin', or 'author'.
                   8211: 
                   8212: =cut
                   8213: 
                   8214: ###############################################
                   8215: sub get_users_function {
1.815     tempelho 8216:     my $function = 'norole';
1.818     tempelho 8217:     if ($env{'request.role'}=~/^(st)/) {
                   8218:         $function='student';
                   8219:     }
1.907     raeburn  8220:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8221:         $function='coordinator';
                   8222:     }
1.258     albertel 8223:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8224:         $function='admin';
                   8225:     }
1.826     bisitz   8226:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8227:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8228:         $function='author';
                   8229:     }
                   8230:     return $function;
1.54      www      8231: }
1.99      www      8232: 
                   8233: ###############################################
                   8234: 
1.233     raeburn  8235: =pod
                   8236: 
1.821     raeburn  8237: =item * &show_course()
                   8238: 
                   8239: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8240: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8241: 
                   8242: Inputs:
                   8243: None
                   8244: 
                   8245: Outputs:
                   8246: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8247: 
                   8248: =cut
                   8249: 
                   8250: ###############################################
                   8251: sub show_course {
                   8252:     my $course = !$env{'user.adv'};
                   8253:     if (!$env{'user.adv'}) {
                   8254:         foreach my $env (keys(%env)) {
                   8255:             next if ($env !~ m/^user\.priv\./);
                   8256:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8257:                 $course = 0;
                   8258:                 last;
                   8259:             }
                   8260:         }
                   8261:     }
                   8262:     return $course;
                   8263: }
                   8264: 
                   8265: ###############################################
                   8266: 
                   8267: =pod
                   8268: 
1.542     raeburn  8269: =item * &check_user_status()
1.274     raeburn  8270: 
                   8271: Determines current status of supplied role for a
                   8272: specific user. Roles can be active, previous or future.
                   8273: 
                   8274: Inputs: 
                   8275: user's domain, user's username, course's domain,
1.375     raeburn  8276: course's number, optional section ID.
1.274     raeburn  8277: 
                   8278: Outputs:
                   8279: role status: active, previous or future. 
                   8280: 
                   8281: =cut
                   8282: 
                   8283: sub check_user_status {
1.412     raeburn  8284:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8285:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8286:     my @uroles = keys %userinfo;
                   8287:     my $srchstr;
                   8288:     my $active_chk = 'none';
1.412     raeburn  8289:     my $now = time;
1.274     raeburn  8290:     if (@uroles > 0) {
1.908     raeburn  8291:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8292:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8293:         } else {
1.412     raeburn  8294:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8295:         }
                   8296:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8297:             my $role_end = 0;
                   8298:             my $role_start = 0;
                   8299:             $active_chk = 'active';
1.412     raeburn  8300:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8301:                 $role_end = $1;
                   8302:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8303:                     $role_start = $1;
1.274     raeburn  8304:                 }
                   8305:             }
                   8306:             if ($role_start > 0) {
1.412     raeburn  8307:                 if ($now < $role_start) {
1.274     raeburn  8308:                     $active_chk = 'future';
                   8309:                 }
                   8310:             }
                   8311:             if ($role_end > 0) {
1.412     raeburn  8312:                 if ($now > $role_end) {
1.274     raeburn  8313:                     $active_chk = 'previous';
                   8314:                 }
                   8315:             }
                   8316:         }
                   8317:     }
                   8318:     return $active_chk;
                   8319: }
                   8320: 
                   8321: ###############################################
                   8322: 
                   8323: =pod
                   8324: 
1.405     albertel 8325: =item * &get_sections()
1.233     raeburn  8326: 
                   8327: Determines all the sections for a course including
                   8328: sections with students and sections containing other roles.
1.419     raeburn  8329: Incoming parameters: 
                   8330: 
                   8331: 1. domain
                   8332: 2. course number 
                   8333: 3. reference to array containing roles for which sections should 
                   8334: be gathered (optional).
                   8335: 4. reference to array containing status types for which sections 
                   8336: should be gathered (optional).
                   8337: 
                   8338: If the third argument is undefined, sections are gathered for any role. 
                   8339: If the fourth argument is undefined, sections are gathered for any status.
                   8340: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8341:  
1.374     raeburn  8342: Returns section hash (keys are section IDs, values are
                   8343: number of users in each section), subject to the
1.419     raeburn  8344: optional roles filter, optional status filter 
1.233     raeburn  8345: 
                   8346: =cut
                   8347: 
                   8348: ###############################################
                   8349: sub get_sections {
1.419     raeburn  8350:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8351:     if (!defined($cdom) || !defined($cnum)) {
                   8352:         my $cid =  $env{'request.course.id'};
                   8353: 
                   8354: 	return if (!defined($cid));
                   8355: 
                   8356:         $cdom = $env{'course.'.$cid.'.domain'};
                   8357:         $cnum = $env{'course.'.$cid.'.num'};
                   8358:     }
                   8359: 
                   8360:     my %sectioncount;
1.419     raeburn  8361:     my $now = time;
1.240     albertel 8362: 
1.1075.2.33  raeburn  8363:     my $check_students = 1;
                   8364:     my $only_students = 0;
                   8365:     if (ref($possible_roles) eq 'ARRAY') {
                   8366:         if (grep(/^st$/,@{$possible_roles})) {
                   8367:             if (@{$possible_roles} == 1) {
                   8368:                 $only_students = 1;
                   8369:             }
                   8370:         } else {
                   8371:             $check_students = 0;
                   8372:         }
                   8373:     }
                   8374: 
                   8375:     if ($check_students) {
1.276     albertel 8376: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8377: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8378: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8379:         my $start_index = &Apache::loncoursedata::CL_START();
                   8380:         my $end_index = &Apache::loncoursedata::CL_END();
                   8381:         my $status;
1.366     albertel 8382: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8383: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8384: 				                     $data->[$status_index],
                   8385:                                                      $data->[$start_index],
                   8386:                                                      $data->[$end_index]);
                   8387:             if ($stu_status eq 'Active') {
                   8388:                 $status = 'active';
                   8389:             } elsif ($end < $now) {
                   8390:                 $status = 'previous';
                   8391:             } elsif ($start > $now) {
                   8392:                 $status = 'future';
                   8393:             } 
                   8394: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8395:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8396:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8397: 		    $sectioncount{$section}++;
                   8398:                 }
1.240     albertel 8399: 	    }
                   8400: 	}
                   8401:     }
1.1075.2.33  raeburn  8402:     if ($only_students) {
                   8403:         return %sectioncount;
                   8404:     }
1.240     albertel 8405:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8406:     foreach my $user (sort(keys(%courseroles))) {
                   8407: 	if ($user !~ /^(\w{2})/) { next; }
                   8408: 	my ($role) = ($user =~ /^(\w{2})/);
                   8409: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8410: 	my ($section,$status);
1.240     albertel 8411: 	if ($role eq 'cr' &&
                   8412: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8413: 	    $section=$1;
                   8414: 	}
                   8415: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8416: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8417:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8418:         if ($end == -1 && $start == -1) {
                   8419:             next; #deleted role
                   8420:         }
                   8421:         if (!defined($possible_status)) { 
                   8422:             $sectioncount{$section}++;
                   8423:         } else {
                   8424:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8425:                 $status = 'active';
                   8426:             } elsif ($end < $now) {
                   8427:                 $status = 'future';
                   8428:             } elsif ($start > $now) {
                   8429:                 $status = 'previous';
                   8430:             }
                   8431:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8432:                 $sectioncount{$section}++;
                   8433:             }
                   8434:         }
1.233     raeburn  8435:     }
1.366     albertel 8436:     return %sectioncount;
1.233     raeburn  8437: }
                   8438: 
1.274     raeburn  8439: ###############################################
1.294     raeburn  8440: 
                   8441: =pod
1.405     albertel 8442: 
                   8443: =item * &get_course_users()
                   8444: 
1.275     raeburn  8445: Retrieves usernames:domains for users in the specified course
                   8446: with specific role(s), and access status. 
                   8447: 
                   8448: Incoming parameters:
1.277     albertel 8449: 1. course domain
                   8450: 2. course number
                   8451: 3. access status: users must have - either active, 
1.275     raeburn  8452: previous, future, or all.
1.277     albertel 8453: 4. reference to array of permissible roles
1.288     raeburn  8454: 5. reference to array of section restrictions (optional)
                   8455: 6. reference to results object (hash of hashes).
                   8456: 7. reference to optional userdata hash
1.609     raeburn  8457: 8. reference to optional statushash
1.630     raeburn  8458: 9. flag if privileged users (except those set to unhide in
                   8459:    course settings) should be excluded    
1.609     raeburn  8460: Keys of top level results hash are roles.
1.275     raeburn  8461: Keys of inner hashes are username:domain, with 
                   8462: values set to access type.
1.288     raeburn  8463: Optional userdata hash returns an array with arguments in the 
                   8464: same order as loncoursedata::get_classlist() for student data.
                   8465: 
1.609     raeburn  8466: Optional statushash returns
                   8467: 
1.288     raeburn  8468: Entries for end, start, section and status are blank because
                   8469: of the possibility of multiple values for non-student roles.
                   8470: 
1.275     raeburn  8471: =cut
1.405     albertel 8472: 
1.275     raeburn  8473: ###############################################
1.405     albertel 8474: 
1.275     raeburn  8475: sub get_course_users {
1.630     raeburn  8476:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8477:     my %idx = ();
1.419     raeburn  8478:     my %seclists;
1.288     raeburn  8479: 
                   8480:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8481:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8482:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8483:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8484:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8485:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8486:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8487:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8488: 
1.290     albertel 8489:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8490:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8491:         my $now = time;
1.277     albertel 8492:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8493:             my $match = 0;
1.412     raeburn  8494:             my $secmatch = 0;
1.419     raeburn  8495:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8496:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8497:             if ($section eq '') {
                   8498:                 $section = 'none';
                   8499:             }
1.291     albertel 8500:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8501:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8502:                     $secmatch = 1;
                   8503:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8504:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8505:                         $secmatch = 1;
                   8506:                     }
                   8507:                 } else {  
1.419     raeburn  8508: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8509: 		        $secmatch = 1;
                   8510:                     }
1.290     albertel 8511: 		}
1.412     raeburn  8512:                 if (!$secmatch) {
                   8513:                     next;
                   8514:                 }
1.419     raeburn  8515:             }
1.275     raeburn  8516:             if (defined($$types{'active'})) {
1.288     raeburn  8517:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8518:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8519:                     $match = 1;
1.275     raeburn  8520:                 }
                   8521:             }
                   8522:             if (defined($$types{'previous'})) {
1.609     raeburn  8523:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8524:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8525:                     $match = 1;
1.275     raeburn  8526:                 }
                   8527:             }
                   8528:             if (defined($$types{'future'})) {
1.609     raeburn  8529:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8530:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8531:                     $match = 1;
1.275     raeburn  8532:                 }
                   8533:             }
1.609     raeburn  8534:             if ($match) {
                   8535:                 push(@{$seclists{$student}},$section);
                   8536:                 if (ref($userdata) eq 'HASH') {
                   8537:                     $$userdata{$student} = $$classlist{$student};
                   8538:                 }
                   8539:                 if (ref($statushash) eq 'HASH') {
                   8540:                     $statushash->{$student}{'st'}{$section} = $status;
                   8541:                 }
1.288     raeburn  8542:             }
1.275     raeburn  8543:         }
                   8544:     }
1.412     raeburn  8545:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8546:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8547:         my $now = time;
1.609     raeburn  8548:         my %displaystatus = ( previous => 'Expired',
                   8549:                               active   => 'Active',
                   8550:                               future   => 'Future',
                   8551:                             );
1.1075.2.36  raeburn  8552:         my (%nothide,@possdoms);
1.630     raeburn  8553:         if ($hidepriv) {
                   8554:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8555:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8556:                 if ($user !~ /:/) {
                   8557:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8558:                 } else {
                   8559:                     $nothide{$user} = 1;
                   8560:                 }
                   8561:             }
1.1075.2.36  raeburn  8562:             my @possdoms = ($cdom);
                   8563:             if ($coursehash{'checkforpriv'}) {
                   8564:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8565:             }
1.630     raeburn  8566:         }
1.439     raeburn  8567:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8568:             my $match = 0;
1.412     raeburn  8569:             my $secmatch = 0;
1.439     raeburn  8570:             my $status;
1.412     raeburn  8571:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8572:             $user =~ s/:$//;
1.439     raeburn  8573:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8574:             if ($end == -1 || $start == -1) {
                   8575:                 next;
                   8576:             }
                   8577:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8578:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8579:                 my ($uname,$udom) = split(/:/,$user);
                   8580:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8581:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8582:                         $secmatch = 1;
                   8583:                     } elsif ($usec eq '') {
1.420     albertel 8584:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8585:                             $secmatch = 1;
                   8586:                         }
                   8587:                     } else {
                   8588:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8589:                             $secmatch = 1;
                   8590:                         }
                   8591:                     }
                   8592:                     if (!$secmatch) {
                   8593:                         next;
                   8594:                     }
1.288     raeburn  8595:                 }
1.419     raeburn  8596:                 if ($usec eq '') {
                   8597:                     $usec = 'none';
                   8598:                 }
1.275     raeburn  8599:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8600:                     if ($hidepriv) {
1.1075.2.36  raeburn  8601:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8602:                             (!$nothide{$uname.':'.$udom})) {
                   8603:                             next;
                   8604:                         }
                   8605:                     }
1.503     raeburn  8606:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8607:                         $status = 'previous';
                   8608:                     } elsif ($start > $now) {
                   8609:                         $status = 'future';
                   8610:                     } else {
                   8611:                         $status = 'active';
                   8612:                     }
1.277     albertel 8613:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8614:                         if ($status eq $type) {
1.420     albertel 8615:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8616:                                 push(@{$$users{$role}{$user}},$type);
                   8617:                             }
1.288     raeburn  8618:                             $match = 1;
                   8619:                         }
                   8620:                     }
1.419     raeburn  8621:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8622:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8623: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8624:                         }
1.420     albertel 8625:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8626:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8627:                         }
1.609     raeburn  8628:                         if (ref($statushash) eq 'HASH') {
                   8629:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8630:                         }
1.275     raeburn  8631:                     }
                   8632:                 }
                   8633:             }
                   8634:         }
1.290     albertel 8635:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8636:             if ((defined($cdom)) && (defined($cnum))) {
                   8637:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8638:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8639:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8640:                     next if ($owner eq '');
                   8641:                     my ($ownername,$ownerdom);
                   8642:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8643:                         $ownername = $1;
                   8644:                         $ownerdom = $2;
                   8645:                     } else {
                   8646:                         $ownername = $owner;
                   8647:                         $ownerdom = $cdom;
                   8648:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8649:                     }
                   8650:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8651:                     if (defined($userdata) && 
1.609     raeburn  8652: 			!exists($$userdata{$owner})) {
                   8653: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8654:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8655:                             push(@{$seclists{$owner}},'none');
                   8656:                         }
                   8657:                         if (ref($statushash) eq 'HASH') {
                   8658:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8659:                         }
1.290     albertel 8660: 		    }
1.279     raeburn  8661:                 }
                   8662:             }
                   8663:         }
1.419     raeburn  8664:         foreach my $user (keys(%seclists)) {
                   8665:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8666:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8667:         }
1.275     raeburn  8668:     }
                   8669:     return;
                   8670: }
                   8671: 
1.288     raeburn  8672: sub get_user_info {
                   8673:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8674:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8675: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8676:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8677:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8678:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8679:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8680:     return;
                   8681: }
1.275     raeburn  8682: 
1.472     raeburn  8683: ###############################################
                   8684: 
                   8685: =pod
                   8686: 
                   8687: =item * &get_user_quota()
                   8688: 
1.1075.2.41  raeburn  8689: Retrieves quota assigned for storage of user files.
                   8690: Default is to report quota for portfolio files.
1.472     raeburn  8691: 
                   8692: Incoming parameters:
                   8693: 1. user's username
                   8694: 2. user's domain
1.1075.2.41  raeburn  8695: 3. quota name - portfolio, author, or course
                   8696:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  8697: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  8698:    course
1.472     raeburn  8699: 
                   8700: Returns:
1.1075.2.58  raeburn  8701: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8702: 2. (Optional) Type of setting: custom or default
                   8703:    (individually assigned or default for user's 
                   8704:    institutional status).
                   8705: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8706:    or student - types as defined in localenroll::inst_usertypes 
                   8707:    for user's domain, which determines default quota for user.
                   8708: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8709: 
                   8710: If a value has been stored in the user's environment, 
1.536     raeburn  8711: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  8712: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8713: 
                   8714: =cut
                   8715: 
                   8716: ###############################################
                   8717: 
                   8718: 
                   8719: sub get_user_quota {
1.1075.2.42  raeburn  8720:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8721:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8722:     if (!defined($udom)) {
                   8723:         $udom = $env{'user.domain'};
                   8724:     }
                   8725:     if (!defined($uname)) {
                   8726:         $uname = $env{'user.name'};
                   8727:     }
                   8728:     if (($udom eq '' || $uname eq '') ||
                   8729:         ($udom eq 'public') && ($uname eq 'public')) {
                   8730:         $quota = 0;
1.536     raeburn  8731:         $quotatype = 'default';
                   8732:         $defquota = 0; 
1.472     raeburn  8733:     } else {
1.536     raeburn  8734:         my $inststatus;
1.1075.2.41  raeburn  8735:         if ($quotaname eq 'course') {
                   8736:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8737:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8738:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8739:             } else {
                   8740:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8741:                 $quota = $cenv{'internal.uploadquota'};
                   8742:             }
1.536     raeburn  8743:         } else {
1.1075.2.41  raeburn  8744:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8745:                 if ($quotaname eq 'author') {
                   8746:                     $quota = $env{'environment.authorquota'};
                   8747:                 } else {
                   8748:                     $quota = $env{'environment.portfolioquota'};
                   8749:                 }
                   8750:                 $inststatus = $env{'environment.inststatus'};
                   8751:             } else {
                   8752:                 my %userenv = 
                   8753:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8754:                                          'authorquota','inststatus'],$udom,$uname);
                   8755:                 my ($tmp) = keys(%userenv);
                   8756:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8757:                     if ($quotaname eq 'author') {
                   8758:                         $quota = $userenv{'authorquota'};
                   8759:                     } else {
                   8760:                         $quota = $userenv{'portfolioquota'};
                   8761:                     }
                   8762:                     $inststatus = $userenv{'inststatus'};
                   8763:                 } else {
                   8764:                     undef(%userenv);
                   8765:                 }
                   8766:             }
                   8767:         }
                   8768:         if ($quota eq '' || wantarray) {
                   8769:             if ($quotaname eq 'course') {
                   8770:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  8771:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   8772:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  8773:                     $defquota = $domdefs{$crstype.'quota'};
                   8774:                 }
                   8775:                 if ($defquota eq '') {
                   8776:                     $defquota = 500;
                   8777:                 }
1.1075.2.41  raeburn  8778:             } else {
                   8779:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8780:             }
                   8781:             if ($quota eq '') {
                   8782:                 $quota = $defquota;
                   8783:                 $quotatype = 'default';
                   8784:             } else {
                   8785:                 $quotatype = 'custom';
                   8786:             }
1.472     raeburn  8787:         }
                   8788:     }
1.536     raeburn  8789:     if (wantarray) {
                   8790:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8791:     } else {
                   8792:         return $quota;
                   8793:     }
1.472     raeburn  8794: }
                   8795: 
                   8796: ###############################################
                   8797: 
                   8798: =pod
                   8799: 
                   8800: =item * &default_quota()
                   8801: 
1.536     raeburn  8802: Retrieves default quota assigned for storage of user portfolio files,
                   8803: given an (optional) user's institutional status.
1.472     raeburn  8804: 
                   8805: Incoming parameters:
1.1075.2.42  raeburn  8806: 
1.472     raeburn  8807: 1. domain
1.536     raeburn  8808: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8809:    status types (e.g., faculty, staff, student etc.)
                   8810:    which apply to the user for whom the default is being retrieved.
                   8811:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  8812:    default quota will be returned.
                   8813: 3.  quota name - portfolio, author, or course
                   8814:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  8815: 
                   8816: Returns:
1.1075.2.42  raeburn  8817: 
1.1075.2.58  raeburn  8818: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  8819: 2. (Optional) institutional type which determined the value of the
                   8820:    default quota.
1.472     raeburn  8821: 
                   8822: If a value has been stored in the domain's configuration db,
                   8823: it will return that, otherwise it returns 20 (for backwards 
                   8824: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  8825: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  8826: 
1.536     raeburn  8827: If the user's status includes multiple types (e.g., staff and student),
                   8828: the largest default quota which applies to the user determines the
                   8829: default quota returned.
                   8830: 
1.472     raeburn  8831: =cut
                   8832: 
                   8833: ###############################################
                   8834: 
                   8835: 
                   8836: sub default_quota {
1.1075.2.41  raeburn  8837:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  8838:     my ($defquota,$settingstatus);
                   8839:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8840:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  8841:     my $key = 'defaultquota';
                   8842:     if ($quotaname eq 'author') {
                   8843:         $key = 'authorquota';
                   8844:     }
1.622     raeburn  8845:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8846:         if ($inststatus ne '') {
1.765     raeburn  8847:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8848:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  8849:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8850:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  8851:                         if ($defquota eq '') {
1.1075.2.41  raeburn  8852:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8853:                             $settingstatus = $item;
1.1075.2.41  raeburn  8854:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   8855:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8856:                             $settingstatus = $item;
                   8857:                         }
                   8858:                     }
1.1075.2.41  raeburn  8859:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  8860:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8861:                         if ($defquota eq '') {
                   8862:                             $defquota = $quotahash{'quotas'}{$item};
                   8863:                             $settingstatus = $item;
                   8864:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8865:                             $defquota = $quotahash{'quotas'}{$item};
                   8866:                             $settingstatus = $item;
                   8867:                         }
1.536     raeburn  8868:                     }
                   8869:                 }
                   8870:             }
                   8871:         }
                   8872:         if ($defquota eq '') {
1.1075.2.41  raeburn  8873:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8874:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   8875:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  8876:                 $defquota = $quotahash{'quotas'}{'default'};
                   8877:             }
1.536     raeburn  8878:             $settingstatus = 'default';
1.1075.2.42  raeburn  8879:             if ($defquota eq '') {
                   8880:                 if ($quotaname eq 'author') {
                   8881:                     $defquota = 500;
                   8882:                 }
                   8883:             }
1.536     raeburn  8884:         }
                   8885:     } else {
                   8886:         $settingstatus = 'default';
1.1075.2.41  raeburn  8887:         if ($quotaname eq 'author') {
                   8888:             $defquota = 500;
                   8889:         } else {
                   8890:             $defquota = 20;
                   8891:         }
1.536     raeburn  8892:     }
                   8893:     if (wantarray) {
                   8894:         return ($defquota,$settingstatus);
1.472     raeburn  8895:     } else {
1.536     raeburn  8896:         return $defquota;
1.472     raeburn  8897:     }
                   8898: }
                   8899: 
1.1075.2.41  raeburn  8900: ###############################################
                   8901: 
                   8902: =pod
                   8903: 
1.1075.2.42  raeburn  8904: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  8905: 
                   8906: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  8907: of existing file within authoring space will cause quota for the authoring
                   8908: space to be exceeded.
                   8909: 
                   8910: Same, if upload of a file directly to a course/community via Course Editor
                   8911: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  8912: 
                   8913: Inputs: 6
1.1075.2.42  raeburn  8914: 1. username or coursenum
1.1075.2.41  raeburn  8915: 2. domain
1.1075.2.42  raeburn  8916: 3. context ('author' or 'course')
1.1075.2.41  raeburn  8917: 4. filename of file for which action is being requested
                   8918: 5. filesize (kB) of file
                   8919: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  8920: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  8921: 
                   8922: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   8923:          otherwise return null.
                   8924: 
1.1075.2.42  raeburn  8925: =back
                   8926: 
1.1075.2.41  raeburn  8927: =cut
                   8928: 
1.1075.2.42  raeburn  8929: sub excess_filesize_warning {
1.1075.2.59  raeburn  8930:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  8931:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  8932:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  8933:     if ($context eq 'author') {
                   8934:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   8935:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   8936:     } else {
                   8937:         foreach my $subdir ('docs','supplemental') {
                   8938:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   8939:         }
                   8940:     }
1.1075.2.41  raeburn  8941:     $disk_quota = int($disk_quota * 1000);
                   8942:     if (($current_disk_usage + $filesize) > $disk_quota) {
                   8943:         return '<p><span class="LC_warning">'.
                   8944:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
                   8945:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
                   8946:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   8947:                             $disk_quota,$current_disk_usage).
                   8948:                '</p>';
                   8949:     }
                   8950:     return;
                   8951: }
                   8952: 
                   8953: ###############################################
                   8954: 
                   8955: 
1.384     raeburn  8956: sub get_secgrprole_info {
                   8957:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8958:     my %sections_count = &get_sections($cdom,$cnum);
                   8959:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8960:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8961:     my @groups = sort(keys(%curr_groups));
                   8962:     my $allroles = [];
                   8963:     my $rolehash;
                   8964:     my $accesshash = {
                   8965:                      active => 'Currently has access',
                   8966:                      future => 'Will have future access',
                   8967:                      previous => 'Previously had access',
                   8968:                   };
                   8969:     if ($needroles) {
                   8970:         $rolehash = {'all' => 'all'};
1.385     albertel 8971:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8972: 	if (&Apache::lonnet::error(%user_roles)) {
                   8973: 	    undef(%user_roles);
                   8974: 	}
                   8975:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8976:             my ($role)=split(/\:/,$item,2);
                   8977:             if ($role eq 'cr') { next; }
                   8978:             if ($role =~ /^cr/) {
                   8979:                 $$rolehash{$role} = (split('/',$role))[3];
                   8980:             } else {
                   8981:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8982:             }
                   8983:         }
                   8984:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8985:             push(@{$allroles},$key);
                   8986:         }
                   8987:         push (@{$allroles},'st');
                   8988:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8989:     }
                   8990:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8991: }
                   8992: 
1.555     raeburn  8993: sub user_picker {
1.994     raeburn  8994:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8995:     my $currdom = $dom;
                   8996:     my %curr_selected = (
                   8997:                         srchin => 'dom',
1.580     raeburn  8998:                         srchby => 'lastname',
1.555     raeburn  8999:                       );
                   9000:     my $srchterm;
1.625     raeburn  9001:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9002:         if ($srch->{'srchby'} ne '') {
                   9003:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9004:         }
                   9005:         if ($srch->{'srchin'} ne '') {
                   9006:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9007:         }
                   9008:         if ($srch->{'srchtype'} ne '') {
                   9009:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9010:         }
                   9011:         if ($srch->{'srchdomain'} ne '') {
                   9012:             $currdom = $srch->{'srchdomain'};
                   9013:         }
                   9014:         $srchterm = $srch->{'srchterm'};
                   9015:     }
                   9016:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9017:                     'usr'       => 'Search criteria',
1.563     raeburn  9018:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9019:                     'uname'     => 'username',
                   9020:                     'lastname'  => 'last name',
1.555     raeburn  9021:                     'lastfirst' => 'last name, first name',
1.558     albertel 9022:                     'crs'       => 'in this course',
1.576     raeburn  9023:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9024:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9025:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9026:                     'exact'     => 'is',
                   9027:                     'contains'  => 'contains',
1.569     raeburn  9028:                     'begins'    => 'begins with',
1.571     raeburn  9029:                     'youm'      => "You must include some text to search for.",
                   9030:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9031:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9032:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9033:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9034:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9035:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9036:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9037:                                        );
1.563     raeburn  9038:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9039:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9040: 
                   9041:     my @srchins = ('crs','dom','alc','instd');
                   9042: 
                   9043:     foreach my $option (@srchins) {
                   9044:         # FIXME 'alc' option unavailable until 
                   9045:         #       loncreateuser::print_user_query_page()
                   9046:         #       has been completed.
                   9047:         next if ($option eq 'alc');
1.880     raeburn  9048:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9049:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9050:         if ($curr_selected{'srchin'} eq $option) {
                   9051:             $srchinsel .= ' 
                   9052:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9053:         } else {
                   9054:             $srchinsel .= '
                   9055:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9056:         }
1.555     raeburn  9057:     }
1.563     raeburn  9058:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9059: 
                   9060:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9061:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9062:         if ($curr_selected{'srchby'} eq $option) {
                   9063:             $srchbysel .= '
                   9064:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9065:         } else {
                   9066:             $srchbysel .= '
                   9067:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9068:          }
                   9069:     }
                   9070:     $srchbysel .= "\n  </select>\n";
                   9071: 
                   9072:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9073:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9074:         if ($curr_selected{'srchtype'} eq $option) {
                   9075:             $srchtypesel .= '
                   9076:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9077:         } else {
                   9078:             $srchtypesel .= '
                   9079:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9080:         }
                   9081:     }
                   9082:     $srchtypesel .= "\n  </select>\n";
                   9083: 
1.558     albertel 9084:     my ($newuserscript,$new_user_create);
1.994     raeburn  9085:     my $context_dom = $env{'request.role.domain'};
                   9086:     if ($context eq 'requestcrs') {
                   9087:         if ($env{'form.coursedom'} ne '') { 
                   9088:             $context_dom = $env{'form.coursedom'};
                   9089:         }
                   9090:     }
1.556     raeburn  9091:     if ($forcenewuser) {
1.576     raeburn  9092:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9093:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9094:                 if ($cancreate) {
                   9095:                     $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>';
                   9096:                 } else {
1.799     bisitz   9097:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9098:                     my %usertypetext = (
                   9099:                         official   => 'institutional',
                   9100:                         unofficial => 'non-institutional',
                   9101:                     );
1.799     bisitz   9102:                     $new_user_create = '<p class="LC_warning">'
                   9103:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9104:                                       .' '
                   9105:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9106:                                           ,'<a href="'.$helplink.'">','</a>')
                   9107:                                       .'</p><br />';
1.627     raeburn  9108:                 }
1.576     raeburn  9109:             }
                   9110:         }
                   9111: 
1.556     raeburn  9112:         $newuserscript = <<"ENDSCRIPT";
                   9113: 
1.570     raeburn  9114: function setSearch(createnew,callingForm) {
1.556     raeburn  9115:     if (createnew == 1) {
1.570     raeburn  9116:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9117:             if (callingForm.srchby.options[i].value == 'uname') {
                   9118:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9119:             }
                   9120:         }
1.570     raeburn  9121:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9122:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9123: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9124:             }
                   9125:         }
1.570     raeburn  9126:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9127:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9128:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9129:             }
                   9130:         }
1.570     raeburn  9131:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9132:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9133:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9134:             }
                   9135:         }
                   9136:     }
                   9137: }
                   9138: ENDSCRIPT
1.558     albertel 9139: 
1.556     raeburn  9140:     }
                   9141: 
1.555     raeburn  9142:     my $output = <<"END_BLOCK";
1.556     raeburn  9143: <script type="text/javascript">
1.824     bisitz   9144: // <![CDATA[
1.570     raeburn  9145: function validateEntry(callingForm) {
1.558     albertel 9146: 
1.556     raeburn  9147:     var checkok = 1;
1.558     albertel 9148:     var srchin;
1.570     raeburn  9149:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9150: 	if ( callingForm.srchin[i].checked ) {
                   9151: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9152: 	}
                   9153:     }
                   9154: 
1.570     raeburn  9155:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9156:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9157:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9158:     var srchterm =  callingForm.srchterm.value;
                   9159:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9160:     var msg = "";
                   9161: 
                   9162:     if (srchterm == "") {
                   9163:         checkok = 0;
1.571     raeburn  9164:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9165:     }
                   9166: 
1.569     raeburn  9167:     if (srchtype== 'begins') {
                   9168:         if (srchterm.length < 2) {
                   9169:             checkok = 0;
1.571     raeburn  9170:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9171:         }
                   9172:     }
                   9173: 
1.556     raeburn  9174:     if (srchtype== 'contains') {
                   9175:         if (srchterm.length < 3) {
                   9176:             checkok = 0;
1.571     raeburn  9177:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9178:         }
                   9179:     }
                   9180:     if (srchin == 'instd') {
                   9181:         if (srchdomain == '') {
                   9182:             checkok = 0;
1.571     raeburn  9183:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9184:         }
                   9185:     }
                   9186:     if (srchin == 'dom') {
                   9187:         if (srchdomain == '') {
                   9188:             checkok = 0;
1.571     raeburn  9189:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9190:         }
                   9191:     }
                   9192:     if (srchby == 'lastfirst') {
                   9193:         if (srchterm.indexOf(",") == -1) {
                   9194:             checkok = 0;
1.571     raeburn  9195:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9196:         }
                   9197:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9198:             checkok = 0;
1.571     raeburn  9199:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9200:         }
                   9201:     }
                   9202:     if (checkok == 0) {
1.571     raeburn  9203:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9204:         return;
                   9205:     }
                   9206:     if (checkok == 1) {
1.570     raeburn  9207:         callingForm.submit();
1.556     raeburn  9208:     }
                   9209: }
                   9210: 
                   9211: $newuserscript
                   9212: 
1.824     bisitz   9213: // ]]>
1.556     raeburn  9214: </script>
1.558     albertel 9215: 
                   9216: $new_user_create
                   9217: 
1.555     raeburn  9218: END_BLOCK
1.558     albertel 9219: 
1.876     raeburn  9220:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9221:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9222:                $domform.
                   9223:                &Apache::lonhtmlcommon::row_closure().
                   9224:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9225:                $srchbysel.
                   9226:                $srchtypesel. 
                   9227:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9228:                $srchinsel.
                   9229:                &Apache::lonhtmlcommon::row_closure(1). 
                   9230:                &Apache::lonhtmlcommon::end_pick_box().
                   9231:                '<br />';
1.555     raeburn  9232:     return $output;
                   9233: }
                   9234: 
1.612     raeburn  9235: sub user_rule_check {
1.615     raeburn  9236:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9237:     my $response;
                   9238:     if (ref($usershash) eq 'HASH') {
                   9239:         foreach my $user (keys(%{$usershash})) {
                   9240:             my ($uname,$udom) = split(/:/,$user);
                   9241:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9242:             my ($id,$newuser);
1.612     raeburn  9243:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9244:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9245:                 $id = $usershash->{$user}->{'id'};
                   9246:             }
                   9247:             my $inst_response;
                   9248:             if (ref($checks) eq 'HASH') {
                   9249:                 if (defined($checks->{'username'})) {
1.615     raeburn  9250:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9251:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9252:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9253:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9254:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9255:                 }
1.615     raeburn  9256:             } else {
                   9257:                 ($inst_response,%{$inst_results->{$user}}) =
                   9258:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9259:                 return;
1.612     raeburn  9260:             }
1.615     raeburn  9261:             if (!$got_rules->{$udom}) {
1.612     raeburn  9262:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9263:                                                   ['usercreation'],$udom);
                   9264:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9265:                     foreach my $item ('username','id') {
1.612     raeburn  9266:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9267:                             $$curr_rules{$udom}{$item} = 
                   9268:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9269:                         }
                   9270:                     }
                   9271:                 }
1.615     raeburn  9272:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9273:             }
1.612     raeburn  9274:             foreach my $item (keys(%{$checks})) {
                   9275:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9276:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9277:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9278:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9279:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9280:                                 if ($rule_check{$rule}) {
                   9281:                                     $$rulematch{$user}{$item} = $rule;
                   9282:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9283:                                         if (ref($inst_results) eq 'HASH') {
                   9284:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9285:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9286:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9287:                                                 }
1.612     raeburn  9288:                                             }
                   9289:                                         }
1.615     raeburn  9290:                                     }
                   9291:                                     last;
1.585     raeburn  9292:                                 }
                   9293:                             }
                   9294:                         }
                   9295:                     }
                   9296:                 }
                   9297:             }
                   9298:         }
                   9299:     }
1.612     raeburn  9300:     return;
                   9301: }
                   9302: 
                   9303: sub user_rule_formats {
                   9304:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9305:     my %text = ( 
                   9306:                  'username' => 'Usernames',
                   9307:                  'id'       => 'IDs',
                   9308:                );
                   9309:     my $output;
                   9310:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9311:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9312:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9313:             $output = '<br />'.
                   9314:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9315:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9316:                       ' <ul>';
1.612     raeburn  9317:             foreach my $rule (@{$ruleorder}) {
                   9318:                 if (ref($curr_rules) eq 'ARRAY') {
                   9319:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9320:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9321:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9322:                                         $rules->{$rule}{'desc'}.'</li>';
                   9323:                         }
                   9324:                     }
                   9325:                 }
                   9326:             }
                   9327:             $output .= '</ul>';
                   9328:         }
                   9329:     }
                   9330:     return $output;
                   9331: }
                   9332: 
                   9333: sub instrule_disallow_msg {
1.615     raeburn  9334:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9335:     my $response;
                   9336:     my %text = (
                   9337:                   item   => 'username',
                   9338:                   items  => 'usernames',
                   9339:                   match  => 'matches',
                   9340:                   do     => 'does',
                   9341:                   action => 'a username',
                   9342:                   one    => 'one',
                   9343:                );
                   9344:     if ($count > 1) {
                   9345:         $text{'item'} = 'usernames';
                   9346:         $text{'match'} ='match';
                   9347:         $text{'do'} = 'do';
                   9348:         $text{'action'} = 'usernames',
                   9349:         $text{'one'} = 'ones';
                   9350:     }
                   9351:     if ($checkitem eq 'id') {
                   9352:         $text{'items'} = 'IDs';
                   9353:         $text{'item'} = 'ID';
                   9354:         $text{'action'} = 'an ID';
1.615     raeburn  9355:         if ($count > 1) {
                   9356:             $text{'item'} = 'IDs';
                   9357:             $text{'action'} = 'IDs';
                   9358:         }
1.612     raeburn  9359:     }
1.674     bisitz   9360:     $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  9361:     if ($mode eq 'upload') {
                   9362:         if ($checkitem eq 'username') {
                   9363:             $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'}.");
                   9364:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9365:             $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  9366:         }
1.669     raeburn  9367:     } elsif ($mode eq 'selfcreate') {
                   9368:         if ($checkitem eq 'id') {
                   9369:             $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.");
                   9370:         }
1.615     raeburn  9371:     } else {
                   9372:         if ($checkitem eq 'username') {
                   9373:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9374:         } elsif ($checkitem eq 'id') {
                   9375:             $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.");
                   9376:         }
1.612     raeburn  9377:     }
                   9378:     return $response;
1.585     raeburn  9379: }
                   9380: 
1.624     raeburn  9381: sub personal_data_fieldtitles {
                   9382:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9383:                         id => 'Student/Employee ID',
                   9384:                         permanentemail => 'E-mail address',
                   9385:                         lastname => 'Last Name',
                   9386:                         firstname => 'First Name',
                   9387:                         middlename => 'Middle Name',
                   9388:                         generation => 'Generation',
                   9389:                         gen => 'Generation',
1.765     raeburn  9390:                         inststatus => 'Affiliation',
1.624     raeburn  9391:                    );
                   9392:     return %fieldtitles;
                   9393: }
                   9394: 
1.642     raeburn  9395: sub sorted_inst_types {
                   9396:     my ($dom) = @_;
                   9397:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9398:     my $othertitle = &mt('All users');
                   9399:     if ($env{'request.course.id'}) {
1.668     raeburn  9400:         $othertitle  = &mt('Any users');
1.642     raeburn  9401:     }
                   9402:     my @types;
                   9403:     if (ref($order) eq 'ARRAY') {
                   9404:         @types = @{$order};
                   9405:     }
                   9406:     if (@types == 0) {
                   9407:         if (ref($usertypes) eq 'HASH') {
                   9408:             @types = sort(keys(%{$usertypes}));
                   9409:         }
                   9410:     }
                   9411:     if (keys(%{$usertypes}) > 0) {
                   9412:         $othertitle = &mt('Other users');
                   9413:     }
                   9414:     return ($othertitle,$usertypes,\@types);
                   9415: }
                   9416: 
1.645     raeburn  9417: sub get_institutional_codes {
                   9418:     my ($settings,$allcourses,$LC_code) = @_;
                   9419: # Get complete list of course sections to update
                   9420:     my @currsections = ();
                   9421:     my @currxlists = ();
                   9422:     my $coursecode = $$settings{'internal.coursecode'};
                   9423: 
                   9424:     if ($$settings{'internal.sectionnums'} ne '') {
                   9425:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9426:     }
                   9427: 
                   9428:     if ($$settings{'internal.crosslistings'} ne '') {
                   9429:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9430:     }
                   9431: 
                   9432:     if (@currxlists > 0) {
                   9433:         foreach (@currxlists) {
                   9434:             if (m/^([^:]+):(\w*)$/) {
                   9435:                 unless (grep/^$1$/,@{$allcourses}) {
                   9436:                     push @{$allcourses},$1;
                   9437:                     $$LC_code{$1} = $2;
                   9438:                 }
                   9439:             }
                   9440:         }
                   9441:     }
                   9442:  
                   9443:     if (@currsections > 0) {
                   9444:         foreach (@currsections) {
                   9445:             if (m/^(\w+):(\w*)$/) {
                   9446:                 my $sec = $coursecode.$1;
                   9447:                 my $lc_sec = $2;
                   9448:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9449:                     push @{$allcourses},$sec;
                   9450:                     $$LC_code{$sec} = $lc_sec;
                   9451:                 }
                   9452:             }
                   9453:         }
                   9454:     }
                   9455:     return;
                   9456: }
                   9457: 
1.971     raeburn  9458: sub get_standard_codeitems {
                   9459:     return ('Year','Semester','Department','Number','Section');
                   9460: }
                   9461: 
1.112     bowersj2 9462: =pod
                   9463: 
1.780     raeburn  9464: =head1 Slot Helpers
                   9465: 
                   9466: =over 4
                   9467: 
                   9468: =item * sorted_slots()
                   9469: 
1.1040    raeburn  9470: Sorts an array of slot names in order of an optional sort key,
                   9471: default sort is by slot start time (earliest first). 
1.780     raeburn  9472: 
                   9473: Inputs:
                   9474: 
                   9475: =over 4
                   9476: 
                   9477: slotsarr  - Reference to array of unsorted slot names.
                   9478: 
                   9479: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9480: 
1.1040    raeburn  9481: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9482: 
1.549     albertel 9483: =back
                   9484: 
1.780     raeburn  9485: Returns:
                   9486: 
                   9487: =over 4
                   9488: 
1.1040    raeburn  9489: sorted   - An array of slot names sorted by a specified sort key 
                   9490:            (default sort key is start time of the slot).
1.780     raeburn  9491: 
                   9492: =back
                   9493: 
                   9494: =cut
                   9495: 
                   9496: 
                   9497: sub sorted_slots {
1.1040    raeburn  9498:     my ($slotsarr,$slots,$sortkey) = @_;
                   9499:     if ($sortkey eq '') {
                   9500:         $sortkey = 'starttime';
                   9501:     }
1.780     raeburn  9502:     my @sorted;
                   9503:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9504:         @sorted =
                   9505:             sort {
                   9506:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9507:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9508:                      }
                   9509:                      if (ref($slots->{$a})) { return -1;}
                   9510:                      if (ref($slots->{$b})) { return 1;}
                   9511:                      return 0;
                   9512:                  } @{$slotsarr};
                   9513:     }
                   9514:     return @sorted;
                   9515: }
                   9516: 
1.1040    raeburn  9517: =pod
                   9518: 
                   9519: =item * get_future_slots()
                   9520: 
                   9521: Inputs:
                   9522: 
                   9523: =over 4
                   9524: 
                   9525: cnum - course number
                   9526: 
                   9527: cdom - course domain
                   9528: 
                   9529: now - current UNIX time
                   9530: 
                   9531: symb - optional symb
                   9532: 
                   9533: =back
                   9534: 
                   9535: Returns:
                   9536: 
                   9537: =over 4
                   9538: 
                   9539: sorted_reservable - ref to array of student_schedulable slots currently 
                   9540:                     reservable, ordered by end date of reservation period.
                   9541: 
                   9542: reservable_now - ref to hash of student_schedulable slots currently
                   9543:                  reservable.
                   9544: 
                   9545:     Keys in inner hash are:
                   9546:     (a) symb: either blank or symb to which slot use is restricted.
                   9547:     (b) endreserve: end date of reservation period. 
                   9548: 
                   9549: sorted_future - ref to array of student_schedulable slots reservable in
                   9550:                 the future, ordered by start date of reservation period.
                   9551: 
                   9552: future_reservable - ref to hash of student_schedulable slots reservable
                   9553:                     in the future.
                   9554: 
                   9555:     Keys in inner hash are:
                   9556:     (a) symb: either blank or symb to which slot use is restricted.
                   9557:     (b) startreserve:  start date of reservation period.
                   9558: 
                   9559: =back
                   9560: 
                   9561: =cut
                   9562: 
                   9563: sub get_future_slots {
                   9564:     my ($cnum,$cdom,$now,$symb) = @_;
                   9565:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9566:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9567:     foreach my $slot (keys(%slots)) {
                   9568:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9569:         if ($symb) {
                   9570:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9571:                      ($slots{$slot}->{'symb'} ne $symb));
                   9572:         }
                   9573:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9574:             ($slots{$slot}->{'endtime'} > $now)) {
                   9575:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9576:                 my $userallowed = 0;
                   9577:                 if ($slots{$slot}->{'allowedsections'}) {
                   9578:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9579:                     if (!defined($env{'request.role.sec'})
                   9580:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9581:                         $userallowed=1;
                   9582:                     } else {
                   9583:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9584:                             $userallowed=1;
                   9585:                         }
                   9586:                     }
                   9587:                     unless ($userallowed) {
                   9588:                         if (defined($env{'request.course.groups'})) {
                   9589:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9590:                             foreach my $group (@groups) {
                   9591:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9592:                                     $userallowed=1;
                   9593:                                     last;
                   9594:                                 }
                   9595:                             }
                   9596:                         }
                   9597:                     }
                   9598:                 }
                   9599:                 if ($slots{$slot}->{'allowedusers'}) {
                   9600:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9601:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9602:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9603:                         $userallowed = 1;
                   9604:                     }
                   9605:                 }
                   9606:                 next unless($userallowed);
                   9607:             }
                   9608:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9609:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9610:             my $symb = $slots{$slot}->{'symb'};
                   9611:             if (($startreserve < $now) &&
                   9612:                 (!$endreserve || $endreserve > $now)) {
                   9613:                 my $lastres = $endreserve;
                   9614:                 if (!$lastres) {
                   9615:                     $lastres = $slots{$slot}->{'starttime'};
                   9616:                 }
                   9617:                 $reservable_now{$slot} = {
                   9618:                                            symb       => $symb,
                   9619:                                            endreserve => $lastres
                   9620:                                          };
                   9621:             } elsif (($startreserve > $now) &&
                   9622:                      (!$endreserve || $endreserve > $startreserve)) {
                   9623:                 $future_reservable{$slot} = {
                   9624:                                               symb         => $symb,
                   9625:                                               startreserve => $startreserve
                   9626:                                             };
                   9627:             }
                   9628:         }
                   9629:     }
                   9630:     my @unsorted_reservable = keys(%reservable_now);
                   9631:     if (@unsorted_reservable > 0) {
                   9632:         @sorted_reservable = 
                   9633:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9634:     }
                   9635:     my @unsorted_future = keys(%future_reservable);
                   9636:     if (@unsorted_future > 0) {
                   9637:         @sorted_future =
                   9638:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9639:     }
                   9640:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9641: }
1.780     raeburn  9642: 
                   9643: =pod
                   9644: 
1.1057    foxr     9645: =back
                   9646: 
1.549     albertel 9647: =head1 HTTP Helpers
                   9648: 
                   9649: =over 4
                   9650: 
1.648     raeburn  9651: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9652: 
1.258     albertel 9653: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9654: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9655: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9656: 
                   9657: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9658: $possible_names is an ref to an array of form element names.  As an example:
                   9659: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9660: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9661: 
                   9662: =cut
1.1       albertel 9663: 
1.6       albertel 9664: sub get_unprocessed_cgi {
1.25      albertel 9665:   my ($query,$possible_names)= @_;
1.26      matthew  9666:   # $Apache::lonxml::debug=1;
1.356     albertel 9667:   foreach my $pair (split(/&/,$query)) {
                   9668:     my ($name, $value) = split(/=/,$pair);
1.369     www      9669:     $name = &unescape($name);
1.25      albertel 9670:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9671:       $value =~ tr/+/ /;
                   9672:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9673:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9674:     }
1.16      harris41 9675:   }
1.6       albertel 9676: }
                   9677: 
1.112     bowersj2 9678: =pod
                   9679: 
1.648     raeburn  9680: =item * &cacheheader() 
1.112     bowersj2 9681: 
                   9682: returns cache-controlling header code
                   9683: 
                   9684: =cut
                   9685: 
1.7       albertel 9686: sub cacheheader {
1.258     albertel 9687:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9688:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9689:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9690:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9691:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9692:     return $output;
1.7       albertel 9693: }
                   9694: 
1.112     bowersj2 9695: =pod
                   9696: 
1.648     raeburn  9697: =item * &no_cache($r) 
1.112     bowersj2 9698: 
                   9699: specifies header code to not have cache
                   9700: 
                   9701: =cut
                   9702: 
1.9       albertel 9703: sub no_cache {
1.216     albertel 9704:     my ($r) = @_;
                   9705:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9706: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9707:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9708:     $r->no_cache(1);
                   9709:     $r->header_out("Expires" => $date);
                   9710:     $r->header_out("Pragma" => "no-cache");
1.123     www      9711: }
                   9712: 
                   9713: sub content_type {
1.181     albertel 9714:     my ($r,$type,$charset) = @_;
1.299     foxr     9715:     if ($r) {
                   9716: 	#  Note that printout.pl calls this with undef for $r.
                   9717: 	&no_cache($r);
                   9718:     }
1.258     albertel 9719:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9720:     unless ($charset) {
                   9721: 	$charset=&Apache::lonlocal::current_encoding;
                   9722:     }
                   9723:     if ($charset) { $type.='; charset='.$charset; }
                   9724:     if ($r) {
                   9725: 	$r->content_type($type);
                   9726:     } else {
                   9727: 	print("Content-type: $type\n\n");
                   9728:     }
1.9       albertel 9729: }
1.25      albertel 9730: 
1.112     bowersj2 9731: =pod
                   9732: 
1.648     raeburn  9733: =item * &add_to_env($name,$value) 
1.112     bowersj2 9734: 
1.258     albertel 9735: adds $name to the %env hash with value
1.112     bowersj2 9736: $value, if $name already exists, the entry is converted to an array
                   9737: reference and $value is added to the array.
                   9738: 
                   9739: =cut
                   9740: 
1.25      albertel 9741: sub add_to_env {
                   9742:   my ($name,$value)=@_;
1.258     albertel 9743:   if (defined($env{$name})) {
                   9744:     if (ref($env{$name})) {
1.25      albertel 9745:       #already have multiple values
1.258     albertel 9746:       push(@{ $env{$name} },$value);
1.25      albertel 9747:     } else {
                   9748:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9749:       my $first=$env{$name};
                   9750:       undef($env{$name});
                   9751:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9752:     }
                   9753:   } else {
1.258     albertel 9754:     $env{$name}=$value;
1.25      albertel 9755:   }
1.31      albertel 9756: }
1.149     albertel 9757: 
                   9758: =pod
                   9759: 
1.648     raeburn  9760: =item * &get_env_multiple($name) 
1.149     albertel 9761: 
1.258     albertel 9762: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9763: values may be defined and end up as an array ref.
                   9764: 
                   9765: returns an array of values
                   9766: 
                   9767: =cut
                   9768: 
                   9769: sub get_env_multiple {
                   9770:     my ($name) = @_;
                   9771:     my @values;
1.258     albertel 9772:     if (defined($env{$name})) {
1.149     albertel 9773:         # exists is it an array
1.258     albertel 9774:         if (ref($env{$name})) {
                   9775:             @values=@{ $env{$name} };
1.149     albertel 9776:         } else {
1.258     albertel 9777:             $values[0]=$env{$name};
1.149     albertel 9778:         }
                   9779:     }
                   9780:     return(@values);
                   9781: }
                   9782: 
1.660     raeburn  9783: sub ask_for_embedded_content {
                   9784:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9785:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  9786:         %currsubfile,%unused,$rem);
1.1071    raeburn  9787:     my $counter = 0;
                   9788:     my $numnew = 0;
1.987     raeburn  9789:     my $numremref = 0;
                   9790:     my $numinvalid = 0;
                   9791:     my $numpathchg = 0;
                   9792:     my $numexisting = 0;
1.1071    raeburn  9793:     my $numunused = 0;
                   9794:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  9795:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  9796:     my $heading = &mt('Upload embedded files');
                   9797:     my $buttontext = &mt('Upload');
                   9798: 
1.1075.2.11  raeburn  9799:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  9800:         if ($actionurl eq '/adm/dependencies') {
                   9801:             $navmap = Apache::lonnavmaps::navmap->new();
                   9802:         }
                   9803:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9804:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  9805:     }
1.1075.2.35  raeburn  9806:     if (($actionurl eq '/adm/portfolio') ||
                   9807:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  9808:         my $current_path='/';
                   9809:         if ($env{'form.currentpath'}) {
                   9810:             $current_path = $env{'form.currentpath'};
                   9811:         }
                   9812:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  9813:             $udom = $cdom;
                   9814:             $uname = $cnum;
1.984     raeburn  9815:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9816:         } else {
                   9817:             $udom = $env{'user.domain'};
                   9818:             $uname = $env{'user.name'};
                   9819:             $url = '/userfiles/portfolio';
                   9820:         }
1.987     raeburn  9821:         $toplevel = $url.'/';
1.984     raeburn  9822:         $url .= $current_path;
                   9823:         $getpropath = 1;
1.987     raeburn  9824:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9825:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9826:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9827:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9828:         $toplevel = $url;
1.984     raeburn  9829:         if ($rest ne '') {
1.987     raeburn  9830:             $url .= $rest;
                   9831:         }
                   9832:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9833:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9834:             $url = $args->{'docs_url'};
                   9835:             $toplevel = $url;
1.1075.2.11  raeburn  9836:             if ($args->{'context'} eq 'paste') {
                   9837:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9838:                 ($path) =
                   9839:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9840:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9841:                 $fileloc =~ s{^/}{};
                   9842:             }
1.1071    raeburn  9843:         }
                   9844:     } elsif ($actionurl eq '/adm/dependencies') {
                   9845:         if ($env{'request.course.id'} ne '') {
                   9846:             if (ref($args) eq 'HASH') {
                   9847:                 $url = $args->{'docs_url'};
                   9848:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  9849:                 $toplevel = $url;
                   9850:                 unless ($toplevel =~ m{^/}) {
                   9851:                     $toplevel = "/$url";
                   9852:                 }
1.1075.2.11  raeburn  9853:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  9854:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   9855:                     $path = $1;
                   9856:                 } else {
                   9857:                     ($path) =
                   9858:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9859:                 }
1.1071    raeburn  9860:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9861:                 $fileloc =~ s{^/}{};
                   9862:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9863:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9864:             }
1.987     raeburn  9865:         }
1.1075.2.35  raeburn  9866:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9867:         $udom = $cdom;
                   9868:         $uname = $cnum;
                   9869:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   9870:         $toplevel = $url;
                   9871:         $path = $url;
                   9872:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   9873:         $fileloc =~ s{^/}{};
                   9874:     }
                   9875:     foreach my $file (keys(%{$allfiles})) {
                   9876:         my $embed_file;
                   9877:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   9878:             $embed_file = $1;
                   9879:         } else {
                   9880:             $embed_file = $file;
                   9881:         }
1.1075.2.55  raeburn  9882:         my ($absolutepath,$cleaned_file);
                   9883:         if ($embed_file =~ m{^\w+://}) {
                   9884:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  9885:             $newfiles{$cleaned_file} = 1;
                   9886:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9887:         } else {
1.1075.2.55  raeburn  9888:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  9889:             if ($embed_file =~ m{^/}) {
                   9890:                 $absolutepath = $embed_file;
                   9891:             }
1.1075.2.47  raeburn  9892:             if ($cleaned_file =~ m{/}) {
                   9893:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  9894:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9895:                 my $item = $fname;
                   9896:                 if ($path ne '') {
                   9897:                     $item = $path.'/'.$fname;
                   9898:                     $subdependencies{$path}{$fname} = 1;
                   9899:                 } else {
                   9900:                     $dependencies{$item} = 1;
                   9901:                 }
                   9902:                 if ($absolutepath) {
                   9903:                     $mapping{$item} = $absolutepath;
                   9904:                 } else {
                   9905:                     $mapping{$item} = $embed_file;
                   9906:                 }
                   9907:             } else {
                   9908:                 $dependencies{$embed_file} = 1;
                   9909:                 if ($absolutepath) {
1.1075.2.47  raeburn  9910:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  9911:                 } else {
1.1075.2.47  raeburn  9912:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9913:                 }
                   9914:             }
1.984     raeburn  9915:         }
                   9916:     }
1.1071    raeburn  9917:     my $dirptr = 16384;
1.984     raeburn  9918:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9919:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  9920:         if (($actionurl eq '/adm/portfolio') ||
                   9921:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9922:             my ($sublistref,$listerror) =
                   9923:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9924:             if (ref($sublistref) eq 'ARRAY') {
                   9925:                 foreach my $line (@{$sublistref}) {
                   9926:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9927:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9928:                 }
1.984     raeburn  9929:             }
1.987     raeburn  9930:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9931:             if (opendir(my $dir,$url.'/'.$path)) {
                   9932:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9933:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9934:             }
1.1075.2.11  raeburn  9935:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9936:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  9937:                   ($args->{'context'} eq 'paste')) ||
                   9938:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9939:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  9940:                 my $dir;
                   9941:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9942:                     $dir = $fileloc;
                   9943:                 } else {
                   9944:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9945:                 }
1.1071    raeburn  9946:                 if ($dir ne '') {
                   9947:                     my ($sublistref,$listerror) =
                   9948:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9949:                     if (ref($sublistref) eq 'ARRAY') {
                   9950:                         foreach my $line (@{$sublistref}) {
                   9951:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9952:                                 undef,$mtime)=split(/\&/,$line,12);
                   9953:                             unless (($testdir&$dirptr) ||
                   9954:                                     ($file_name =~ /^\.\.?$/)) {
                   9955:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9956:                             }
                   9957:                         }
                   9958:                     }
                   9959:                 }
1.984     raeburn  9960:             }
                   9961:         }
                   9962:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9963:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9964:                 my $item = $path.'/'.$file;
                   9965:                 unless ($mapping{$item} eq $item) {
                   9966:                     $pathchanges{$item} = 1;
                   9967:                 }
                   9968:                 $existing{$item} = 1;
                   9969:                 $numexisting ++;
                   9970:             } else {
                   9971:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9972:             }
                   9973:         }
1.1071    raeburn  9974:         if ($actionurl eq '/adm/dependencies') {
                   9975:             foreach my $path (keys(%currsubfile)) {
                   9976:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9977:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9978:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  9979:                              next if (($rem ne '') &&
                   9980:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9981:                                        (ref($navmap) &&
                   9982:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9983:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9984:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9985:                              $unused{$path.'/'.$file} = 1; 
                   9986:                          }
                   9987:                     }
                   9988:                 }
                   9989:             }
                   9990:         }
1.984     raeburn  9991:     }
1.987     raeburn  9992:     my %currfile;
1.1075.2.35  raeburn  9993:     if (($actionurl eq '/adm/portfolio') ||
                   9994:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9995:         my ($dirlistref,$listerror) =
                   9996:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9997:         if (ref($dirlistref) eq 'ARRAY') {
                   9998:             foreach my $line (@{$dirlistref}) {
                   9999:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10000:                 $currfile{$file_name} = 1;
                   10001:             }
1.984     raeburn  10002:         }
1.987     raeburn  10003:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10004:         if (opendir(my $dir,$url)) {
1.987     raeburn  10005:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10006:             map {$currfile{$_} = 1;} @dir_list;
                   10007:         }
1.1075.2.11  raeburn  10008:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10009:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10010:               ($args->{'context'} eq 'paste')) ||
                   10011:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10012:         if ($env{'request.course.id'} ne '') {
                   10013:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10014:             if ($dir ne '') {
                   10015:                 my ($dirlistref,$listerror) =
                   10016:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10017:                 if (ref($dirlistref) eq 'ARRAY') {
                   10018:                     foreach my $line (@{$dirlistref}) {
                   10019:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10020:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10021:                         unless (($testdir&$dirptr) ||
                   10022:                                 ($file_name =~ /^\.\.?$/)) {
                   10023:                             $currfile{$file_name} = [$size,$mtime];
                   10024:                         }
                   10025:                     }
                   10026:                 }
                   10027:             }
                   10028:         }
1.984     raeburn  10029:     }
                   10030:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10031:         if (exists($currfile{$file})) {
1.987     raeburn  10032:             unless ($mapping{$file} eq $file) {
                   10033:                 $pathchanges{$file} = 1;
                   10034:             }
                   10035:             $existing{$file} = 1;
                   10036:             $numexisting ++;
                   10037:         } else {
1.984     raeburn  10038:             $newfiles{$file} = 1;
                   10039:         }
                   10040:     }
1.1071    raeburn  10041:     foreach my $file (keys(%currfile)) {
                   10042:         unless (($file eq $filename) ||
                   10043:                 ($file eq $filename.'.bak') ||
                   10044:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10045:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10046:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10047:                     next if (($rem ne '') &&
                   10048:                              (($env{"httpref.$rem".$file} ne '') ||
                   10049:                               (ref($navmap) &&
                   10050:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10051:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10052:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10053:                 }
1.1075.2.11  raeburn  10054:             }
1.1071    raeburn  10055:             $unused{$file} = 1;
                   10056:         }
                   10057:     }
1.1075.2.11  raeburn  10058:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10059:         ($args->{'context'} eq 'paste')) {
                   10060:         $counter = scalar(keys(%existing));
                   10061:         $numpathchg = scalar(keys(%pathchanges));
                   10062:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10063:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10064:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10065:         $counter = scalar(keys(%existing));
                   10066:         $numpathchg = scalar(keys(%pathchanges));
                   10067:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10068:     }
1.984     raeburn  10069:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10070:         if ($actionurl eq '/adm/dependencies') {
                   10071:             next if ($embed_file =~ m{^\w+://});
                   10072:         }
1.660     raeburn  10073:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10074:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10075:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10076:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10077:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10078:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10079:         }
1.1075.2.35  raeburn  10080:         $upload_output .= '</td>';
1.1071    raeburn  10081:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10082:             $upload_output.='<td align="right">'.
                   10083:                             '<span class="LC_info LC_fontsize_medium">'.
                   10084:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10085:             $numremref++;
1.660     raeburn  10086:         } elsif ($args->{'error_on_invalid_names'}
                   10087:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10088:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10089:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10090:             $numinvalid++;
1.660     raeburn  10091:         } else {
1.1075.2.35  raeburn  10092:             $upload_output .= '<td>'.
                   10093:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10094:                                                      $embed_file,\%mapping,
1.1071    raeburn  10095:                                                      $allfiles,$codebase,'upload');
                   10096:             $counter ++;
                   10097:             $numnew ++;
1.987     raeburn  10098:         }
                   10099:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10100:     }
                   10101:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10102:         if ($actionurl eq '/adm/dependencies') {
                   10103:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10104:             $modify_output .= &start_data_table_row().
                   10105:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10106:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10107:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10108:                               '<td>'.$size.'</td>'.
                   10109:                               '<td>'.$mtime.'</td>'.
                   10110:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10111:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10112:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10113:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10114:                               &embedded_file_element('upload_embedded',$counter,
                   10115:                                                      $embed_file,\%mapping,
                   10116:                                                      $allfiles,$codebase,'modify').
                   10117:                               '</div></td>'.
                   10118:                               &end_data_table_row()."\n";
                   10119:             $counter ++;
                   10120:         } else {
                   10121:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10122:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10123:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10124:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10125:                               &Apache::loncommon::end_data_table_row()."\n";
                   10126:         }
                   10127:     }
                   10128:     my $delidx = $counter;
                   10129:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10130:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10131:         $delete_output .= &start_data_table_row().
                   10132:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10133:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10134:                           '<td>'.$size.'</td>'.
                   10135:                           '<td>'.$mtime.'</td>'.
                   10136:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10137:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10138:                           &embedded_file_element('upload_embedded',$delidx,
                   10139:                                                  $oldfile,\%mapping,$allfiles,
                   10140:                                                  $codebase,'delete').'</td>'.
                   10141:                           &end_data_table_row()."\n"; 
                   10142:         $numunused ++;
                   10143:         $delidx ++;
1.987     raeburn  10144:     }
                   10145:     if ($upload_output) {
                   10146:         $upload_output = &start_data_table().
                   10147:                          $upload_output.
                   10148:                          &end_data_table()."\n";
                   10149:     }
1.1071    raeburn  10150:     if ($modify_output) {
                   10151:         $modify_output = &start_data_table().
                   10152:                          &start_data_table_header_row().
                   10153:                          '<th>'.&mt('File').'</th>'.
                   10154:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10155:                          '<th>'.&mt('Modified').'</th>'.
                   10156:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10157:                          &end_data_table_header_row().
                   10158:                          $modify_output.
                   10159:                          &end_data_table()."\n";
                   10160:     }
                   10161:     if ($delete_output) {
                   10162:         $delete_output = &start_data_table().
                   10163:                          &start_data_table_header_row().
                   10164:                          '<th>'.&mt('File').'</th>'.
                   10165:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10166:                          '<th>'.&mt('Modified').'</th>'.
                   10167:                          '<th>'.&mt('Delete?').'</th>'.
                   10168:                          &end_data_table_header_row().
                   10169:                          $delete_output.
                   10170:                          &end_data_table()."\n";
                   10171:     }
1.987     raeburn  10172:     my $applies = 0;
                   10173:     if ($numremref) {
                   10174:         $applies ++;
                   10175:     }
                   10176:     if ($numinvalid) {
                   10177:         $applies ++;
                   10178:     }
                   10179:     if ($numexisting) {
                   10180:         $applies ++;
                   10181:     }
1.1071    raeburn  10182:     if ($counter || $numunused) {
1.987     raeburn  10183:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10184:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10185:                   $state.'<h3>'.$heading.'</h3>'; 
                   10186:         if ($actionurl eq '/adm/dependencies') {
                   10187:             if ($numnew) {
                   10188:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10189:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10190:                            $upload_output.'<br />'."\n";
                   10191:             }
                   10192:             if ($numexisting) {
                   10193:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10194:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10195:                            $modify_output.'<br />'."\n";
                   10196:                            $buttontext = &mt('Save changes');
                   10197:             }
                   10198:             if ($numunused) {
                   10199:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10200:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10201:                            $delete_output.'<br />'."\n";
                   10202:                            $buttontext = &mt('Save changes');
                   10203:             }
                   10204:         } else {
                   10205:             $output .= $upload_output.'<br />'."\n";
                   10206:         }
                   10207:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10208:                    $counter.'" />'."\n";
                   10209:         if ($actionurl eq '/adm/dependencies') { 
                   10210:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10211:                        $numnew.'" />'."\n";
                   10212:         } elsif ($actionurl eq '') {
1.987     raeburn  10213:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10214:         }
                   10215:     } elsif ($applies) {
                   10216:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10217:         if ($applies > 1) {
                   10218:             $output .=  
1.1075.2.35  raeburn  10219:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10220:             if ($numremref) {
                   10221:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10222:             }
                   10223:             if ($numinvalid) {
                   10224:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10225:             }
                   10226:             if ($numexisting) {
                   10227:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10228:             }
                   10229:             $output .= '</ul><br />';
                   10230:         } elsif ($numremref) {
                   10231:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10232:         } elsif ($numinvalid) {
                   10233:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10234:         } elsif ($numexisting) {
                   10235:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10236:         }
                   10237:         $output .= $upload_output.'<br />';
                   10238:     }
                   10239:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10240:     $chgcount = $counter;
1.987     raeburn  10241:     if (keys(%pathchanges) > 0) {
                   10242:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10243:             if ($counter) {
1.987     raeburn  10244:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10245:                                                   $embed_file,\%mapping,
1.1071    raeburn  10246:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10247:             } else {
                   10248:                 $pathchange_output .= 
                   10249:                     &start_data_table_row().
                   10250:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10251:                     $chgcount.'" checked="checked" /></td>'.
                   10252:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10253:                     '<td>'.$embed_file.
                   10254:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10255:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10256:                     '</td>'.&end_data_table_row();
1.660     raeburn  10257:             }
1.987     raeburn  10258:             $numpathchg ++;
                   10259:             $chgcount ++;
1.660     raeburn  10260:         }
                   10261:     }
1.1075.2.35  raeburn  10262:     if (($counter) || ($numunused)) {
1.987     raeburn  10263:         if ($numpathchg) {
                   10264:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10265:                        $numpathchg.'" />'."\n";
                   10266:         }
                   10267:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10268:             ($actionurl eq '/adm/imsimport')) {
                   10269:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10270:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10271:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10272:         } elsif ($actionurl eq '/adm/dependencies') {
                   10273:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10274:         }
1.1075.2.35  raeburn  10275:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10276:     } elsif ($numpathchg) {
                   10277:         my %pathchange = ();
                   10278:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10279:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10280:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10281:         }
1.987     raeburn  10282:     }
1.1071    raeburn  10283:     return ($output,$counter,$numpathchg);
1.987     raeburn  10284: }
                   10285: 
1.1075.2.47  raeburn  10286: =pod
                   10287: 
                   10288: =item * clean_path($name)
                   10289: 
                   10290: Performs clean-up of directories, subdirectories and filename in an
                   10291: embedded object, referenced in an HTML file which is being uploaded
                   10292: to a course or portfolio, where
                   10293: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10294: checked.
                   10295: 
                   10296: Clean-up is similar to replacements in lonnet::clean_filename()
                   10297: except each / between sub-directory and next level is preserved.
                   10298: 
                   10299: =cut
                   10300: 
                   10301: sub clean_path {
                   10302:     my ($embed_file) = @_;
                   10303:     $embed_file =~s{^/+}{};
                   10304:     my @contents;
                   10305:     if ($embed_file =~ m{/}) {
                   10306:         @contents = split(/\//,$embed_file);
                   10307:     } else {
                   10308:         @contents = ($embed_file);
                   10309:     }
                   10310:     my $lastidx = scalar(@contents)-1;
                   10311:     for (my $i=0; $i<=$lastidx; $i++) {
                   10312:         $contents[$i]=~s{\\}{/}g;
                   10313:         $contents[$i]=~s/\s+/\_/g;
                   10314:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10315:         if ($i == $lastidx) {
                   10316:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10317:         }
                   10318:     }
                   10319:     if ($lastidx > 0) {
                   10320:         return join('/',@contents);
                   10321:     } else {
                   10322:         return $contents[0];
                   10323:     }
                   10324: }
                   10325: 
1.987     raeburn  10326: sub embedded_file_element {
1.1071    raeburn  10327:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10328:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10329:                    (ref($codebase) eq 'HASH'));
                   10330:     my $output;
1.1071    raeburn  10331:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10332:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10333:     }
                   10334:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10335:                &escape($embed_file).'" />';
                   10336:     unless (($context eq 'upload_embedded') && 
                   10337:             ($mapping->{$embed_file} eq $embed_file)) {
                   10338:         $output .='
                   10339:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10340:     }
                   10341:     my $attrib;
                   10342:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10343:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10344:     }
                   10345:     $output .=
                   10346:         "\n\t\t".
                   10347:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10348:         $attrib.'" />';
                   10349:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10350:         $output .=
                   10351:             "\n\t\t".
                   10352:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10353:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10354:     }
1.987     raeburn  10355:     return $output;
1.660     raeburn  10356: }
                   10357: 
1.1071    raeburn  10358: sub get_dependency_details {
                   10359:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10360:     my ($size,$mtime,$showsize,$showmtime);
                   10361:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10362:         if ($embed_file =~ m{/}) {
                   10363:             my ($path,$fname) = split(/\//,$embed_file);
                   10364:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10365:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10366:             }
                   10367:         } else {
                   10368:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10369:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10370:             }
                   10371:         }
                   10372:         $showsize = $size/1024.0;
                   10373:         $showsize = sprintf("%.1f",$showsize);
                   10374:         if ($mtime > 0) {
                   10375:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10376:         }
                   10377:     }
                   10378:     return ($showsize,$showmtime);
                   10379: }
                   10380: 
                   10381: sub ask_embedded_js {
                   10382:     return <<"END";
                   10383: <script type="text/javascript"">
                   10384: // <![CDATA[
                   10385: function toggleBrowse(counter) {
                   10386:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10387:     var fileid = document.getElementById('embedded_item_'+counter);
                   10388:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10389:     if (chkboxid.checked == true) {
                   10390:         uploaddivid.style.display='block';
                   10391:     } else {
                   10392:         uploaddivid.style.display='none';
                   10393:         fileid.value = '';
                   10394:     }
                   10395: }
                   10396: // ]]>
                   10397: </script>
                   10398: 
                   10399: END
                   10400: }
                   10401: 
1.661     raeburn  10402: sub upload_embedded {
                   10403:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10404:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10405:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10406:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10407:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10408:         my $orig_uploaded_filename =
                   10409:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10410:         foreach my $type ('orig','ref','attrib','codebase') {
                   10411:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10412:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10413:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10414:             }
                   10415:         }
1.661     raeburn  10416:         my ($path,$fname) =
                   10417:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10418:         # no path, whole string is fname
                   10419:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10420:         $fname = &Apache::lonnet::clean_filename($fname);
                   10421:         # See if there is anything left
                   10422:         next if ($fname eq '');
                   10423: 
                   10424:         # Check if file already exists as a file or directory.
                   10425:         my ($state,$msg);
                   10426:         if ($context eq 'portfolio') {
                   10427:             my $port_path = $dirpath;
                   10428:             if ($group ne '') {
                   10429:                 $port_path = "groups/$group/$port_path";
                   10430:             }
1.987     raeburn  10431:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10432:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10433:                                               $dir_root,$port_path,$disk_quota,
                   10434:                                               $current_disk_usage,$uname,$udom);
                   10435:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10436:                 || $state eq 'file_locked') {
1.661     raeburn  10437:                 $output .= $msg;
                   10438:                 next;
                   10439:             }
                   10440:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10441:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10442:             if ($state eq 'exists') {
                   10443:                 $output .= $msg;
                   10444:                 next;
                   10445:             }
                   10446:         }
                   10447:         # Check if extension is valid
                   10448:         if (($fname =~ /\.(\w+)$/) &&
                   10449:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  10450:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10451:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10452:             next;
                   10453:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10454:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10455:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10456:             next;
                   10457:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10458:             $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  10459:             next;
                   10460:         }
                   10461:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10462:         my $subdir = $path;
                   10463:         $subdir =~ s{/+$}{};
1.661     raeburn  10464:         if ($context eq 'portfolio') {
1.984     raeburn  10465:             my $result;
                   10466:             if ($state eq 'existingfile') {
                   10467:                 $result=
                   10468:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10469:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10470:             } else {
1.984     raeburn  10471:                 $result=
                   10472:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10473:                                                     $dirpath.
1.1075.2.35  raeburn  10474:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10475:                 if ($result !~ m|^/uploaded/|) {
                   10476:                     $output .= '<span class="LC_error">'
                   10477:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10478:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10479:                                .'</span><br />';
                   10480:                     next;
                   10481:                 } else {
1.987     raeburn  10482:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10483:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10484:                 }
1.661     raeburn  10485:             }
1.1075.2.35  raeburn  10486:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10487:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10488:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10489:             my $result =
1.1075.2.35  raeburn  10490:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10491:             if ($result !~ m|^/uploaded/|) {
                   10492:                 $output .= '<span class="LC_error">'
                   10493:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10494:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10495:                            .'</span><br />';
                   10496:                     next;
                   10497:             } else {
                   10498:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10499:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10500:                 if ($context eq 'syllabus') {
                   10501:                     &Apache::lonnet::make_public_indefinitely($result);
                   10502:                 }
1.987     raeburn  10503:             }
1.661     raeburn  10504:         } else {
                   10505: # Save the file
                   10506:             my $target = $env{'form.embedded_item_'.$i};
                   10507:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10508:             my $dest = $fullpath.$fname;
                   10509:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10510:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10511:             my $count;
                   10512:             my $filepath = $dir_root;
1.1027    raeburn  10513:             foreach my $subdir (@parts) {
                   10514:                 $filepath .= "/$subdir";
                   10515:                 if (!-e $filepath) {
1.661     raeburn  10516:                     mkdir($filepath,0770);
                   10517:                 }
                   10518:             }
                   10519:             my $fh;
                   10520:             if (!open($fh,'>'.$dest)) {
                   10521:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10522:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10523:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10524:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10525:                            '</span><br />';
                   10526:             } else {
                   10527:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10528:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10529:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10530:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10531:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10532:                               '</span><br />';
                   10533:                 } else {
1.987     raeburn  10534:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10535:                                $url.'</span>').'<br />';
                   10536:                     unless ($context eq 'testbank') {
                   10537:                         $footer .= &mt('View embedded file: [_1]',
                   10538:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10539:                     }
                   10540:                 }
                   10541:                 close($fh);
                   10542:             }
                   10543:         }
                   10544:         if ($env{'form.embedded_ref_'.$i}) {
                   10545:             $pathchange{$i} = 1;
                   10546:         }
                   10547:     }
                   10548:     if ($output) {
                   10549:         $output = '<p>'.$output.'</p>';
                   10550:     }
                   10551:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10552:     $returnflag = 'ok';
1.1071    raeburn  10553:     my $numpathchgs = scalar(keys(%pathchange));
                   10554:     if ($numpathchgs > 0) {
1.987     raeburn  10555:         if ($context eq 'portfolio') {
                   10556:             $output .= '<p>'.&mt('or').'</p>';
                   10557:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10558:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10559:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10560:             $returnflag = 'modify_orightml';
                   10561:         }
                   10562:     }
1.1071    raeburn  10563:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10564: }
                   10565: 
                   10566: sub modify_html_form {
                   10567:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10568:     my $end = 0;
                   10569:     my $modifyform;
                   10570:     if ($context eq 'upload_embedded') {
                   10571:         return unless (ref($pathchange) eq 'HASH');
                   10572:         if ($env{'form.number_embedded_items'}) {
                   10573:             $end += $env{'form.number_embedded_items'};
                   10574:         }
                   10575:         if ($env{'form.number_pathchange_items'}) {
                   10576:             $end += $env{'form.number_pathchange_items'};
                   10577:         }
                   10578:         if ($end) {
                   10579:             for (my $i=0; $i<$end; $i++) {
                   10580:                 if ($i < $env{'form.number_embedded_items'}) {
                   10581:                     next unless($pathchange->{$i});
                   10582:                 }
                   10583:                 $modifyform .=
                   10584:                     &start_data_table_row().
                   10585:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10586:                     'checked="checked" /></td>'.
                   10587:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10588:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10589:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10590:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10591:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10592:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10593:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10594:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10595:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10596:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10597:                     &end_data_table_row();
1.1071    raeburn  10598:             }
1.987     raeburn  10599:         }
                   10600:     } else {
                   10601:         $modifyform = $pathchgtable;
                   10602:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10603:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10604:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10605:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10606:         }
                   10607:     }
                   10608:     if ($modifyform) {
1.1071    raeburn  10609:         if ($actionurl eq '/adm/dependencies') {
                   10610:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10611:         }
1.987     raeburn  10612:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10613:                '<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".
                   10614:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10615:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10616:                '</ol></p>'."\n".'<p>'.
                   10617:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10618:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10619:                &start_data_table()."\n".
                   10620:                &start_data_table_header_row().
                   10621:                '<th>'.&mt('Change?').'</th>'.
                   10622:                '<th>'.&mt('Current reference').'</th>'.
                   10623:                '<th>'.&mt('Required reference').'</th>'.
                   10624:                &end_data_table_header_row()."\n".
                   10625:                $modifyform.
                   10626:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10627:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10628:                '</form>'."\n";
                   10629:     }
                   10630:     return;
                   10631: }
                   10632: 
                   10633: sub modify_html_refs {
1.1075.2.35  raeburn  10634:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10635:     my $container;
                   10636:     if ($context eq 'portfolio') {
                   10637:         $container = $env{'form.container'};
                   10638:     } elsif ($context eq 'coursedoc') {
                   10639:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10640:     } elsif ($context eq 'manage_dependencies') {
                   10641:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10642:         $container = "/$container";
1.1075.2.35  raeburn  10643:     } elsif ($context eq 'syllabus') {
                   10644:         $container = $url;
1.987     raeburn  10645:     } else {
1.1027    raeburn  10646:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10647:     }
                   10648:     my (%allfiles,%codebase,$output,$content);
                   10649:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10650:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10651:         if (wantarray) {
                   10652:             return ('',0,0); 
                   10653:         } else {
                   10654:             return;
                   10655:         }
                   10656:     }
                   10657:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10658:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10659:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10660:             if (wantarray) {
                   10661:                 return ('',0,0);
                   10662:             } else {
                   10663:                 return;
                   10664:             }
                   10665:         } 
1.987     raeburn  10666:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10667:         if ($content eq '-1') {
                   10668:             if (wantarray) {
                   10669:                 return ('',0,0);
                   10670:             } else {
                   10671:                 return;
                   10672:             }
                   10673:         }
1.987     raeburn  10674:     } else {
1.1071    raeburn  10675:         unless ($container =~ /^\Q$dir_root\E/) {
                   10676:             if (wantarray) {
                   10677:                 return ('',0,0);
                   10678:             } else {
                   10679:                 return;
                   10680:             }
                   10681:         } 
1.987     raeburn  10682:         if (open(my $fh,"<$container")) {
                   10683:             $content = join('', <$fh>);
                   10684:             close($fh);
                   10685:         } else {
1.1071    raeburn  10686:             if (wantarray) {
                   10687:                 return ('',0,0);
                   10688:             } else {
                   10689:                 return;
                   10690:             }
1.987     raeburn  10691:         }
                   10692:     }
                   10693:     my ($count,$codebasecount) = (0,0);
                   10694:     my $mm = new File::MMagic;
                   10695:     my $mime_type = $mm->checktype_contents($content);
                   10696:     if ($mime_type eq 'text/html') {
                   10697:         my $parse_result = 
                   10698:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10699:                                                     \%codebase,\$content);
                   10700:         if ($parse_result eq 'ok') {
                   10701:             foreach my $i (@changes) {
                   10702:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10703:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10704:                 if ($allfiles{$ref}) {
                   10705:                     my $newname =  $orig;
                   10706:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10707:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10708:                     if ($attrib_regexp =~ /:/) {
                   10709:                         $attrib_regexp =~ s/\:/|/g;
                   10710:                     }
                   10711:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10712:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10713:                         $count += $numchg;
1.1075.2.35  raeburn  10714:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  10715:                         delete($allfiles{$ref});
1.987     raeburn  10716:                     }
                   10717:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10718:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10719:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10720:                         $codebasecount ++;
                   10721:                     }
                   10722:                 }
                   10723:             }
1.1075.2.35  raeburn  10724:             my $skiprewrites;
1.987     raeburn  10725:             if ($count || $codebasecount) {
                   10726:                 my $saveresult;
1.1071    raeburn  10727:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10728:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10729:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10730:                     if ($url eq $container) {
                   10731:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10732:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10733:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10734:                                             $fname.'</span>').'</p>';
1.987     raeburn  10735:                     } else {
                   10736:                          $output = '<p class="LC_error">'.
                   10737:                                    &mt('Error: update failed for: [_1].',
                   10738:                                    '<span class="LC_filename">'.
                   10739:                                    $container.'</span>').'</p>';
                   10740:                     }
1.1075.2.35  raeburn  10741:                     if ($context eq 'syllabus') {
                   10742:                         unless ($saveresult eq 'ok') {
                   10743:                             $skiprewrites = 1;
                   10744:                         }
                   10745:                     }
1.987     raeburn  10746:                 } else {
                   10747:                     if (open(my $fh,">$container")) {
                   10748:                         print $fh $content;
                   10749:                         close($fh);
                   10750:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10751:                                   $count,'<span class="LC_filename">'.
                   10752:                                   $container.'</span>').'</p>';
1.661     raeburn  10753:                     } else {
1.987     raeburn  10754:                          $output = '<p class="LC_error">'.
                   10755:                                    &mt('Error: could not update [_1].',
                   10756:                                    '<span class="LC_filename">'.
                   10757:                                    $container.'</span>').'</p>';
1.661     raeburn  10758:                     }
                   10759:                 }
                   10760:             }
1.1075.2.35  raeburn  10761:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10762:                 my ($actionurl,$state);
                   10763:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10764:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10765:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10766:                                               \%codebase,
                   10767:                                               {'context' => 'rewrites',
                   10768:                                                'ignore_remote_references' => 1,});
                   10769:                 if (ref($mapping) eq 'HASH') {
                   10770:                     my $rewrites = 0;
                   10771:                     foreach my $key (keys(%{$mapping})) {
                   10772:                         next if ($key =~ m{^https?://});
                   10773:                         my $ref = $mapping->{$key};
                   10774:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10775:                         my $attrib;
                   10776:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10777:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10778:                         }
                   10779:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10780:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10781:                             $rewrites += $numchg;
                   10782:                         }
                   10783:                     }
                   10784:                     if ($rewrites) {
                   10785:                         my $saveresult;
                   10786:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10787:                         if ($url eq $container) {
                   10788:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   10789:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   10790:                                             $count,'<span class="LC_filename">'.
                   10791:                                             $fname.'</span>').'</p>';
                   10792:                         } else {
                   10793:                             $output .= '<p class="LC_error">'.
                   10794:                                        &mt('Error: could not update links in [_1].',
                   10795:                                        '<span class="LC_filename">'.
                   10796:                                        $container.'</span>').'</p>';
                   10797: 
                   10798:                         }
                   10799:                     }
                   10800:                 }
                   10801:             }
1.987     raeburn  10802:         } else {
                   10803:             &logthis('Failed to parse '.$container.
                   10804:                      ' to modify references: '.$parse_result);
1.661     raeburn  10805:         }
                   10806:     }
1.1071    raeburn  10807:     if (wantarray) {
                   10808:         return ($output,$count,$codebasecount);
                   10809:     } else {
                   10810:         return $output;
                   10811:     }
1.661     raeburn  10812: }
                   10813: 
                   10814: sub check_for_existing {
                   10815:     my ($path,$fname,$element) = @_;
                   10816:     my ($state,$msg);
                   10817:     if (-d $path.'/'.$fname) {
                   10818:         $state = 'exists';
                   10819:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10820:     } elsif (-e $path.'/'.$fname) {
                   10821:         $state = 'exists';
                   10822:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10823:     }
                   10824:     if ($state eq 'exists') {
                   10825:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10826:     }
                   10827:     return ($state,$msg);
                   10828: }
                   10829: 
                   10830: sub check_for_upload {
                   10831:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10832:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10833:     my $filesize = length($env{'form.'.$element});
                   10834:     if (!$filesize) {
                   10835:         my $msg = '<span class="LC_error">'.
                   10836:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10837:                       '<span class="LC_filename">'.$fname.'</span>',
                   10838:                       $filesize).'<br />'.
1.1007    raeburn  10839:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10840:                   '</span>';
                   10841:         return ('zero_bytes',$msg);
                   10842:     }
                   10843:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10844:     my $getpropath = 1;
1.1021    raeburn  10845:     my ($dirlistref,$listerror) =
                   10846:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10847:     my $found_file = 0;
                   10848:     my $locked_file = 0;
1.991     raeburn  10849:     my @lockers;
                   10850:     my $navmap;
                   10851:     if ($env{'request.course.id'}) {
                   10852:         $navmap = Apache::lonnavmaps::navmap->new();
                   10853:     }
1.1021    raeburn  10854:     if (ref($dirlistref) eq 'ARRAY') {
                   10855:         foreach my $line (@{$dirlistref}) {
                   10856:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10857:             if ($file_name eq $fname){
                   10858:                 $file_name = $path.$file_name;
                   10859:                 if ($group ne '') {
                   10860:                     $file_name = $group.$file_name;
                   10861:                 }
                   10862:                 $found_file = 1;
                   10863:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10864:                     foreach my $lock (@lockers) {
                   10865:                         if (ref($lock) eq 'ARRAY') {
                   10866:                             my ($symb,$crsid) = @{$lock};
                   10867:                             if ($crsid eq $env{'request.course.id'}) {
                   10868:                                 if (ref($navmap)) {
                   10869:                                     my $res = $navmap->getBySymb($symb);
                   10870:                                     foreach my $part (@{$res->parts()}) { 
                   10871:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10872:                                         unless (($slot_status == $res->RESERVED) ||
                   10873:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10874:                                             $locked_file = 1;
                   10875:                                         }
1.991     raeburn  10876:                                     }
1.1021    raeburn  10877:                                 } else {
                   10878:                                     $locked_file = 1;
1.991     raeburn  10879:                                 }
                   10880:                             } else {
                   10881:                                 $locked_file = 1;
                   10882:                             }
                   10883:                         }
1.1021    raeburn  10884:                    }
                   10885:                 } else {
                   10886:                     my @info = split(/\&/,$rest);
                   10887:                     my $currsize = $info[6]/1000;
                   10888:                     if ($currsize < $filesize) {
                   10889:                         my $extra = $filesize - $currsize;
                   10890:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10891:                             my $msg = '<span class="LC_error">'.
                   10892:                                       &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.',
                   10893:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10894:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10895:                                                    $disk_quota,$current_disk_usage);
                   10896:                             return ('will_exceed_quota',$msg);
                   10897:                         }
1.984     raeburn  10898:                     }
                   10899:                 }
1.661     raeburn  10900:             }
                   10901:         }
                   10902:     }
                   10903:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10904:         my $msg = '<span class="LC_error">'.
                   10905:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10906:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10907:         return ('will_exceed_quota',$msg);
                   10908:     } elsif ($found_file) {
                   10909:         if ($locked_file) {
                   10910:             my $msg = '<span class="LC_error">';
                   10911:             $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>');
                   10912:             $msg .= '</span><br />';
                   10913:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10914:             return ('file_locked',$msg);
                   10915:         } else {
                   10916:             my $msg = '<span class="LC_error">';
1.984     raeburn  10917:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.661     raeburn  10918:             $msg .= '</span>';
1.984     raeburn  10919:             return ('existingfile',$msg);
1.661     raeburn  10920:         }
                   10921:     }
                   10922: }
                   10923: 
1.987     raeburn  10924: sub check_for_traversal {
                   10925:     my ($path,$url,$toplevel) = @_;
                   10926:     my @parts=split(/\//,$path);
                   10927:     my $cleanpath;
                   10928:     my $fullpath = $url;
                   10929:     for (my $i=0;$i<@parts;$i++) {
                   10930:         next if ($parts[$i] eq '.');
                   10931:         if ($parts[$i] eq '..') {
                   10932:             $fullpath =~ s{([^/]+/)$}{};
                   10933:         } else {
                   10934:             $fullpath .= $parts[$i].'/';
                   10935:         }
                   10936:     }
                   10937:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10938:         $cleanpath = $1;
                   10939:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10940:         my $curr_toprel = $1;
                   10941:         my @parts = split(/\//,$curr_toprel);
                   10942:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10943:         my @urlparts = split(/\//,$url_toprel);
                   10944:         my $doubledots;
                   10945:         my $startdiff = -1;
                   10946:         for (my $i=0; $i<@urlparts; $i++) {
                   10947:             if ($startdiff == -1) {
                   10948:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10949:                     $startdiff = $i;
                   10950:                     $doubledots .= '../';
                   10951:                 }
                   10952:             } else {
                   10953:                 $doubledots .= '../';
                   10954:             }
                   10955:         }
                   10956:         if ($startdiff > -1) {
                   10957:             $cleanpath = $doubledots;
                   10958:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10959:                 $cleanpath .= $parts[$i].'/';
                   10960:             }
                   10961:         }
                   10962:     }
                   10963:     $cleanpath =~ s{(/)$}{};
                   10964:     return $cleanpath;
                   10965: }
1.31      albertel 10966: 
1.1053    raeburn  10967: sub is_archive_file {
                   10968:     my ($mimetype) = @_;
                   10969:     if (($mimetype eq 'application/octet-stream') ||
                   10970:         ($mimetype eq 'application/x-stuffit') ||
                   10971:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10972:         return 1;
                   10973:     }
                   10974:     return;
                   10975: }
                   10976: 
                   10977: sub decompress_form {
1.1065    raeburn  10978:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10979:     my %lt = &Apache::lonlocal::texthash (
                   10980:         this => 'This file is an archive file.',
1.1067    raeburn  10981:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10982:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10983:         youm => 'You may wish to extract its contents.',
                   10984:         extr => 'Extract contents',
1.1067    raeburn  10985:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10986:         proa => 'Process automatically?',
1.1053    raeburn  10987:         yes  => 'Yes',
                   10988:         no   => 'No',
1.1067    raeburn  10989:         fold => 'Title for folder containing movie',
                   10990:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10991:     );
1.1065    raeburn  10992:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10993:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10994:     my $info = &list_archive_contents($fileloc,\@paths);
                   10995:     if (@paths) {
                   10996:         foreach my $path (@paths) {
                   10997:             $path =~ s{^/}{};
1.1067    raeburn  10998:             if ($path =~ m{^([^/]+)/$}) {
                   10999:                 $topdir = $1;
                   11000:             }
1.1065    raeburn  11001:             if ($path =~ m{^([^/]+)/}) {
                   11002:                 $toplevel{$1} = $path;
                   11003:             } else {
                   11004:                 $toplevel{$path} = $path;
                   11005:             }
                   11006:         }
                   11007:     }
1.1067    raeburn  11008:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11009:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11010:                         "$topdir/media/",
                   11011:                         "$topdir/media/$topdir.mp4",
                   11012:                         "$topdir/media/FirstFrame.png",
                   11013:                         "$topdir/media/player.swf",
                   11014:                         "$topdir/media/swfobject.js",
                   11015:                         "$topdir/media/expressInstall.swf");
1.1075.2.59  raeburn  11016:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
                   11017:                          "$topdir/$topdir.mp4",
                   11018:                          "$topdir/$topdir\_config.xml",
                   11019:                          "$topdir/$topdir\_controller.swf",
                   11020:                          "$topdir/$topdir\_embed.css",
                   11021:                          "$topdir/$topdir\_First_Frame.png",
                   11022:                          "$topdir/$topdir\_player.html",
                   11023:                          "$topdir/$topdir\_Thumbnails.png",
                   11024:                          "$topdir/playerProductInstall.swf",
                   11025:                          "$topdir/scripts/",
                   11026:                          "$topdir/scripts/config_xml.js",
                   11027:                          "$topdir/scripts/handlebars.js",
                   11028:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11029:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11030:                          "$topdir/scripts/modernizr.js",
                   11031:                          "$topdir/scripts/player-min.js",
                   11032:                          "$topdir/scripts/swfobject.js",
                   11033:                          "$topdir/skins/",
                   11034:                          "$topdir/skins/configuration_express.xml",
                   11035:                          "$topdir/skins/express_show/",
                   11036:                          "$topdir/skins/express_show/player-min.css",
                   11037:                          "$topdir/skins/express_show/spritesheet.png");
                   11038:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11039:         if (@diffs == 0) {
1.1075.2.59  raeburn  11040:             $is_camtasia = 6;
                   11041:         } else {
                   11042:             @diffs = &compare_arrays(\@paths,\@camtasia8);
                   11043:             if (@diffs == 0) {
                   11044:                 $is_camtasia = 8;
                   11045:             }
1.1067    raeburn  11046:         }
                   11047:     }
                   11048:     my $output;
                   11049:     if ($is_camtasia) {
                   11050:         $output = <<"ENDCAM";
                   11051: <script type="text/javascript" language="Javascript">
                   11052: // <![CDATA[
                   11053: 
                   11054: function camtasiaToggle() {
                   11055:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11056:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11057:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11058:                 document.getElementById('camtasia_titles').style.display='block';
                   11059:             } else {
                   11060:                 document.getElementById('camtasia_titles').style.display='none';
                   11061:             }
                   11062:         }
                   11063:     }
                   11064:     return;
                   11065: }
                   11066: 
                   11067: // ]]>
                   11068: </script>
                   11069: <p>$lt{'camt'}</p>
                   11070: ENDCAM
1.1065    raeburn  11071:     } else {
1.1067    raeburn  11072:         $output = '<p>'.$lt{'this'};
                   11073:         if ($info eq '') {
                   11074:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11075:         } else {
                   11076:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11077:                        '<div><pre>'.$info.'</pre></div>';
                   11078:         }
1.1065    raeburn  11079:     }
1.1067    raeburn  11080:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11081:     my $duplicates;
                   11082:     my $num = 0;
                   11083:     if (ref($dirlist) eq 'ARRAY') {
                   11084:         foreach my $item (@{$dirlist}) {
                   11085:             if (ref($item) eq 'ARRAY') {
                   11086:                 if (exists($toplevel{$item->[0]})) {
                   11087:                     $duplicates .= 
                   11088:                         &start_data_table_row().
                   11089:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11090:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11091:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11092:                         'value="1" />'.&mt('Yes').'</label>'.
                   11093:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11094:                         '<td>'.$item->[0].'</td>';
                   11095:                     if ($item->[2]) {
                   11096:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11097:                     } else {
                   11098:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11099:                     }
                   11100:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11101:                                    '<td>'.
                   11102:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11103:                                    '</td>'.
                   11104:                                    &end_data_table_row();
                   11105:                     $num ++;
                   11106:                 }
                   11107:             }
                   11108:         }
                   11109:     }
                   11110:     my $itemcount;
                   11111:     if (@paths > 0) {
                   11112:         $itemcount = scalar(@paths);
                   11113:     } else {
                   11114:         $itemcount = 1;
                   11115:     }
1.1067    raeburn  11116:     if ($is_camtasia) {
                   11117:         $output .= $lt{'auto'}.'<br />'.
                   11118:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11119:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11120:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11121:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11122:                    $lt{'no'}.'</label></span><br />'.
                   11123:                    '<div id="camtasia_titles" style="display:block">'.
                   11124:                    &Apache::lonhtmlcommon::start_pick_box().
                   11125:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11126:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11127:                    &Apache::lonhtmlcommon::row_closure().
                   11128:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11129:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11130:                    &Apache::lonhtmlcommon::row_closure(1).
                   11131:                    &Apache::lonhtmlcommon::end_pick_box().
                   11132:                    '</div>';
                   11133:     }
1.1065    raeburn  11134:     $output .= 
                   11135:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11136:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11137:         "\n";
1.1065    raeburn  11138:     if ($duplicates ne '') {
                   11139:         $output .= '<p><span class="LC_warning">'.
                   11140:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11141:                    &start_data_table().
                   11142:                    &start_data_table_header_row().
                   11143:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11144:                    '<th>'.&mt('Name').'</th>'.
                   11145:                    '<th>'.&mt('Type').'</th>'.
                   11146:                    '<th>'.&mt('Size').'</th>'.
                   11147:                    '<th>'.&mt('Last modified').'</th>'.
                   11148:                    &end_data_table_header_row().
                   11149:                    $duplicates.
                   11150:                    &end_data_table().
                   11151:                    '</p>';
                   11152:     }
1.1067    raeburn  11153:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11154:     if (ref($hiddenelements) eq 'HASH') {
                   11155:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11156:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11157:         }
                   11158:     }
                   11159:     $output .= <<"END";
1.1067    raeburn  11160: <br />
1.1053    raeburn  11161: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11162: </form>
                   11163: $noextract
                   11164: END
                   11165:     return $output;
                   11166: }
                   11167: 
1.1065    raeburn  11168: sub decompression_utility {
                   11169:     my ($program) = @_;
                   11170:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11171:     my $location;
                   11172:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11173:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11174:                          '/usr/sbin/') {
                   11175:             if (-x $dir.$program) {
                   11176:                 $location = $dir.$program;
                   11177:                 last;
                   11178:             }
                   11179:         }
                   11180:     }
                   11181:     return $location;
                   11182: }
                   11183: 
                   11184: sub list_archive_contents {
                   11185:     my ($file,$pathsref) = @_;
                   11186:     my (@cmd,$output);
                   11187:     my $needsregexp;
                   11188:     if ($file =~ /\.zip$/) {
                   11189:         @cmd = (&decompression_utility('unzip'),"-l");
                   11190:         $needsregexp = 1;
                   11191:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11192:              ($file =~ /\.tgz$/)) {
                   11193:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11194:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11195:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11196:     } elsif ($file =~ m|\.tar$|) {
                   11197:         @cmd = (&decompression_utility('tar'),"-tf");
                   11198:     }
                   11199:     if (@cmd) {
                   11200:         undef($!);
                   11201:         undef($@);
                   11202:         if (open(my $fh,"-|", @cmd, $file)) {
                   11203:             while (my $line = <$fh>) {
                   11204:                 $output .= $line;
                   11205:                 chomp($line);
                   11206:                 my $item;
                   11207:                 if ($needsregexp) {
                   11208:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11209:                 } else {
                   11210:                     $item = $line;
                   11211:                 }
                   11212:                 if ($item ne '') {
                   11213:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11214:                         push(@{$pathsref},$item);
                   11215:                     } 
                   11216:                 }
                   11217:             }
                   11218:             close($fh);
                   11219:         }
                   11220:     }
                   11221:     return $output;
                   11222: }
                   11223: 
1.1053    raeburn  11224: sub decompress_uploaded_file {
                   11225:     my ($file,$dir) = @_;
                   11226:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11227:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11228:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11229:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11230:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11231:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11232:     my $decompressed = $env{'cgi.decompressed'};
                   11233:     &Apache::lonnet::delenv('cgi.file');
                   11234:     &Apache::lonnet::delenv('cgi.dir');
                   11235:     &Apache::lonnet::delenv('cgi.decompressed');
                   11236:     return ($decompressed,$result);
                   11237: }
                   11238: 
1.1055    raeburn  11239: sub process_decompression {
                   11240:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11241:     my ($dir,$error,$warning,$output);
                   11242:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1075.2.34  raeburn  11243:         $error = &mt('Filename not a supported archive file type.').
                   11244:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11245:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11246:     } else {
                   11247:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11248:         if ($docuhome eq 'no_host') {
                   11249:             $error = &mt('Could not determine home server for course.');
                   11250:         } else {
                   11251:             my @ids=&Apache::lonnet::current_machine_ids();
                   11252:             my $currdir = "$dir_root/$destination";
                   11253:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11254:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11255:                        "$dir_root/$destination";
                   11256:             } else {
                   11257:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11258:                        "$dir_root/$docudom/$docuname/$destination";
                   11259:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11260:                     $error = &mt('Archive file not found.');
                   11261:                 }
                   11262:             }
1.1065    raeburn  11263:             my (@to_overwrite,@to_skip);
                   11264:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11265:                 my $total = $env{'form.archive_overwrite_total'};
                   11266:                 for (my $i=0; $i<$total; $i++) {
                   11267:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11268:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11269:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11270:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11271:                     }
                   11272:                 }
                   11273:             }
                   11274:             my $numskip = scalar(@to_skip);
                   11275:             if (($numskip > 0) && 
                   11276:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11277:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11278:             } elsif ($dir eq '') {
1.1055    raeburn  11279:                 $error = &mt('Directory containing archive file unavailable.');
                   11280:             } elsif (!$error) {
1.1065    raeburn  11281:                 my ($decompressed,$display);
                   11282:                 if ($numskip > 0) {
                   11283:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11284:                     mkdir("$dir/$tempdir",0755);
                   11285:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11286:                     ($decompressed,$display) = 
                   11287:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11288:                     foreach my $item (@to_skip) {
                   11289:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11290:                             if (-f "$dir/$tempdir/$item") { 
                   11291:                                 unlink("$dir/$tempdir/$item");
                   11292:                             } elsif (-d "$dir/$tempdir/$item") {
                   11293:                                 system("rm -rf $dir/$tempdir/$item");
                   11294:                             }
                   11295:                         }
                   11296:                     }
                   11297:                     system("mv $dir/$tempdir/* $dir");
                   11298:                     rmdir("$dir/$tempdir");   
                   11299:                 } else {
                   11300:                     ($decompressed,$display) = 
                   11301:                         &decompress_uploaded_file($file,$dir);
                   11302:                 }
1.1055    raeburn  11303:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11304:                     $output = '<p class="LC_info">'.
                   11305:                               &mt('Files extracted successfully from archive.').
                   11306:                               '</p>'."\n";
1.1055    raeburn  11307:                     my ($warning,$result,@contents);
                   11308:                     my ($newdirlistref,$newlisterror) =
                   11309:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11310:                                                  $docuname,1);
                   11311:                     my (%is_dir,%changes,@newitems);
                   11312:                     my $dirptr = 16384;
1.1065    raeburn  11313:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11314:                         foreach my $dir_line (@{$newdirlistref}) {
                   11315:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11316:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11317:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11318:                                 push(@newitems,$item);
                   11319:                                 if ($dirptr&$testdir) {
                   11320:                                     $is_dir{$item} = 1;
                   11321:                                 }
                   11322:                                 $changes{$item} = 1;
                   11323:                             }
                   11324:                         }
                   11325:                     }
                   11326:                     if (keys(%changes) > 0) {
                   11327:                         foreach my $item (sort(@newitems)) {
                   11328:                             if ($changes{$item}) {
                   11329:                                 push(@contents,$item);
                   11330:                             }
                   11331:                         }
                   11332:                     }
                   11333:                     if (@contents > 0) {
1.1067    raeburn  11334:                         my $wantform;
                   11335:                         unless ($env{'form.autoextract_camtasia'}) {
                   11336:                             $wantform = 1;
                   11337:                         }
1.1056    raeburn  11338:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11339:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11340:                                                                 $currdir,\%is_dir,
                   11341:                                                                 \%children,\%parent,
1.1056    raeburn  11342:                                                                 \@contents,\%dirorder,
                   11343:                                                                 \%titles,$wantform);
1.1055    raeburn  11344:                         if ($datatable ne '') {
                   11345:                             $output .= &archive_options_form('decompressed',$datatable,
                   11346:                                                              $count,$hiddenelem);
1.1065    raeburn  11347:                             my $startcount = 6;
1.1055    raeburn  11348:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11349:                                                            \%titles,\%children);
1.1055    raeburn  11350:                         }
1.1067    raeburn  11351:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  11352:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11353:                             my %displayed;
                   11354:                             my $total = 1;
                   11355:                             $env{'form.archive_directory'} = [];
                   11356:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11357:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11358:                                 $path =~ s{/$}{};
                   11359:                                 my $item;
                   11360:                                 if ($path ne '') {
                   11361:                                     $item = "$path/$titles{$i}";
                   11362:                                 } else {
                   11363:                                     $item = $titles{$i};
                   11364:                                 }
                   11365:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11366:                                 if ($item eq $contents[0]) {
                   11367:                                     push(@{$env{'form.archive_directory'}},$i);
                   11368:                                     $env{'form.archive_'.$i} = 'display';
                   11369:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11370:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  11371:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11372:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  11373:                                     $env{'form.archive_'.$i} = 'display';
                   11374:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11375:                                     $displayed{'web'} = $i;
                   11376:                                 } else {
1.1075.2.59  raeburn  11377:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11378:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11379:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11380:                                         push(@{$env{'form.archive_directory'}},$i);
                   11381:                                     }
                   11382:                                     $env{'form.archive_'.$i} = 'dependency';
                   11383:                                 }
                   11384:                                 $total ++;
                   11385:                             }
                   11386:                             for (my $i=1; $i<$total; $i++) {
                   11387:                                 next if ($i == $displayed{'web'});
                   11388:                                 next if ($i == $displayed{'folder'});
                   11389:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11390:                             }
                   11391:                             $env{'form.phase'} = 'decompress_cleanup';
                   11392:                             $env{'form.archivedelete'} = 1;
                   11393:                             $env{'form.archive_count'} = $total-1;
                   11394:                             $output .=
                   11395:                                 &process_extracted_files('coursedocs',$docudom,
                   11396:                                                          $docuname,$destination,
                   11397:                                                          $dir_root,$hiddenelem);
                   11398:                         }
1.1055    raeburn  11399:                     } else {
                   11400:                         $warning = &mt('No new items extracted from archive file.');
                   11401:                     }
                   11402:                 } else {
                   11403:                     $output = $display;
                   11404:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11405:                 }
                   11406:             }
                   11407:         }
                   11408:     }
                   11409:     if ($error) {
                   11410:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11411:                    $error.'</p>'."\n";
                   11412:     }
                   11413:     if ($warning) {
                   11414:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11415:     }
                   11416:     return $output;
                   11417: }
                   11418: 
                   11419: sub get_extracted {
1.1056    raeburn  11420:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11421:         $titles,$wantform) = @_;
1.1055    raeburn  11422:     my $count = 0;
                   11423:     my $depth = 0;
                   11424:     my $datatable;
1.1056    raeburn  11425:     my @hierarchy;
1.1055    raeburn  11426:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11427:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11428:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11429:     foreach my $item (@{$contents}) {
                   11430:         $count ++;
1.1056    raeburn  11431:         @{$dirorder->{$count}} = @hierarchy;
                   11432:         $titles->{$count} = $item;
1.1055    raeburn  11433:         &archive_hierarchy($depth,$count,$parent,$children);
                   11434:         if ($wantform) {
                   11435:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11436:                                        $currdir,$depth,$count);
                   11437:         }
                   11438:         if ($is_dir->{$item}) {
                   11439:             $depth ++;
1.1056    raeburn  11440:             push(@hierarchy,$count);
                   11441:             $parent->{$depth} = $count;
1.1055    raeburn  11442:             $datatable .=
                   11443:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11444:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11445:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11446:             $depth --;
1.1056    raeburn  11447:             pop(@hierarchy);
1.1055    raeburn  11448:         }
                   11449:     }
                   11450:     return ($count,$datatable);
                   11451: }
                   11452: 
                   11453: sub recurse_extracted_archive {
1.1056    raeburn  11454:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11455:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11456:     my $result='';
1.1056    raeburn  11457:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11458:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11459:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11460:         return $result;
                   11461:     }
                   11462:     my $dirptr = 16384;
                   11463:     my ($newdirlistref,$newlisterror) =
                   11464:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11465:     if (ref($newdirlistref) eq 'ARRAY') {
                   11466:         foreach my $dir_line (@{$newdirlistref}) {
                   11467:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11468:             unless ($item =~ /^\.+$/) {
                   11469:                 $$count ++;
1.1056    raeburn  11470:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11471:                 $titles->{$$count} = $item;
1.1055    raeburn  11472:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11473: 
1.1055    raeburn  11474:                 my $is_dir;
                   11475:                 if ($dirptr&$testdir) {
                   11476:                     $is_dir = 1;
                   11477:                 }
                   11478:                 if ($wantform) {
                   11479:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11480:                 }
                   11481:                 if ($is_dir) {
                   11482:                     $$depth ++;
1.1056    raeburn  11483:                     push(@{$hierarchy},$$count);
                   11484:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11485:                     $result .=
                   11486:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11487:                                                    $docuname,$depth,$count,
1.1056    raeburn  11488:                                                    $hierarchy,$dirorder,$children,
                   11489:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11490:                     $$depth --;
1.1056    raeburn  11491:                     pop(@{$hierarchy});
1.1055    raeburn  11492:                 }
                   11493:             }
                   11494:         }
                   11495:     }
                   11496:     return $result;
                   11497: }
                   11498: 
                   11499: sub archive_hierarchy {
                   11500:     my ($depth,$count,$parent,$children) =@_;
                   11501:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11502:         if (exists($parent->{$depth})) {
                   11503:              $children->{$parent->{$depth}} .= $count.':';
                   11504:         }
                   11505:     }
                   11506:     return;
                   11507: }
                   11508: 
                   11509: sub archive_row {
                   11510:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11511:     my ($name) = ($item =~ m{([^/]+)$});
                   11512:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11513:                                        'display'    => 'Add as file',
1.1055    raeburn  11514:                                        'dependency' => 'Include as dependency',
                   11515:                                        'discard'    => 'Discard',
                   11516:                                       );
                   11517:     if ($is_dir) {
1.1059    raeburn  11518:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11519:     }
1.1056    raeburn  11520:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11521:     my $offset = 0;
1.1055    raeburn  11522:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11523:         $offset ++;
1.1065    raeburn  11524:         if ($action ne 'display') {
                   11525:             $offset ++;
                   11526:         }  
1.1055    raeburn  11527:         $output .= '<td><span class="LC_nobreak">'.
                   11528:                    '<label><input type="radio" name="archive_'.$count.
                   11529:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11530:         my $text = $choices{$action};
                   11531:         if ($is_dir) {
                   11532:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11533:             if ($action eq 'display') {
1.1059    raeburn  11534:                 $text = &mt('Add as folder');
1.1055    raeburn  11535:             }
1.1056    raeburn  11536:         } else {
                   11537:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11538: 
                   11539:         }
                   11540:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11541:         if ($action eq 'dependency') {
                   11542:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11543:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11544:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11545:                        '<option value=""></option>'."\n".
                   11546:                        '</select>'."\n".
                   11547:                        '</div>';
1.1059    raeburn  11548:         } elsif ($action eq 'display') {
                   11549:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11550:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11551:                        '</div>';
1.1055    raeburn  11552:         }
1.1056    raeburn  11553:         $output .= '</td>';
1.1055    raeburn  11554:     }
                   11555:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11556:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11557:     for (my $i=0; $i<$depth; $i++) {
                   11558:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11559:     }
                   11560:     if ($is_dir) {
                   11561:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11562:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11563:     } else {
                   11564:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11565:     }
                   11566:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11567:                &end_data_table_row();
                   11568:     return $output;
                   11569: }
                   11570: 
                   11571: sub archive_options_form {
1.1065    raeburn  11572:     my ($form,$display,$count,$hiddenelem) = @_;
                   11573:     my %lt = &Apache::lonlocal::texthash(
                   11574:                perm => 'Permanently remove archive file?',
                   11575:                hows => 'How should each extracted item be incorporated in the course?',
                   11576:                cont => 'Content actions for all',
                   11577:                addf => 'Add as folder/file',
                   11578:                incd => 'Include as dependency for a displayed file',
                   11579:                disc => 'Discard',
                   11580:                no   => 'No',
                   11581:                yes  => 'Yes',
                   11582:                save => 'Save',
                   11583:     );
                   11584:     my $output = <<"END";
                   11585: <form name="$form" method="post" action="">
                   11586: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11587: <label>
                   11588:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11589: </label>
                   11590: &nbsp;
                   11591: <label>
                   11592:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11593: </span>
                   11594: </p>
                   11595: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11596: <br />$lt{'hows'}
                   11597: <div class="LC_columnSection">
                   11598:   <fieldset>
                   11599:     <legend>$lt{'cont'}</legend>
                   11600:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11601:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11602:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11603:   </fieldset>
                   11604: </div>
                   11605: END
                   11606:     return $output.
1.1055    raeburn  11607:            &start_data_table()."\n".
1.1065    raeburn  11608:            $display."\n".
1.1055    raeburn  11609:            &end_data_table()."\n".
                   11610:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11611:            $hiddenelem.
1.1065    raeburn  11612:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11613:            '</form>';
                   11614: }
                   11615: 
                   11616: sub archive_javascript {
1.1056    raeburn  11617:     my ($startcount,$numitems,$titles,$children) = @_;
                   11618:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11619:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11620:     my $scripttag = <<START;
                   11621: <script type="text/javascript">
                   11622: // <![CDATA[
                   11623: 
                   11624: function checkAll(form,prefix) {
                   11625:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11626:     for (var i=0; i < form.elements.length; i++) {
                   11627:         var id = form.elements[i].id;
                   11628:         if ((id != '') && (id != undefined)) {
                   11629:             if (idstr.test(id)) {
                   11630:                 if (form.elements[i].type == 'radio') {
                   11631:                     form.elements[i].checked = true;
1.1056    raeburn  11632:                     var nostart = i-$startcount;
1.1059    raeburn  11633:                     var offset = nostart%7;
                   11634:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11635:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11636:                 }
                   11637:             }
                   11638:         }
                   11639:     }
                   11640: }
                   11641: 
                   11642: function propagateCheck(form,count) {
                   11643:     if (count > 0) {
1.1059    raeburn  11644:         var startelement = $startcount + ((count-1) * 7);
                   11645:         for (var j=1; j<6; j++) {
                   11646:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11647:                 var item = startelement + j; 
                   11648:                 if (form.elements[item].type == 'radio') {
                   11649:                     if (form.elements[item].checked) {
                   11650:                         containerCheck(form,count,j);
                   11651:                         break;
                   11652:                     }
1.1055    raeburn  11653:                 }
                   11654:             }
                   11655:         }
                   11656:     }
                   11657: }
                   11658: 
                   11659: numitems = $numitems
1.1056    raeburn  11660: var titles = new Array(numitems);
                   11661: var parents = new Array(numitems);
1.1055    raeburn  11662: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11663:     parents[i] = new Array;
1.1055    raeburn  11664: }
1.1059    raeburn  11665: var maintitle = '$maintitle';
1.1055    raeburn  11666: 
                   11667: START
                   11668: 
1.1056    raeburn  11669:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11670:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11671:         for (my $i=0; $i<@contents; $i ++) {
                   11672:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11673:         }
                   11674:     }
                   11675: 
1.1056    raeburn  11676:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11677:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11678:     }
                   11679: 
1.1055    raeburn  11680:     $scripttag .= <<END;
                   11681: 
                   11682: function containerCheck(form,count,offset) {
                   11683:     if (count > 0) {
1.1056    raeburn  11684:         dependencyCheck(form,count,offset);
1.1059    raeburn  11685:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11686:         form.elements[item].checked = true;
                   11687:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11688:             if (parents[count].length > 0) {
                   11689:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11690:                     containerCheck(form,parents[count][j],offset);
                   11691:                 }
                   11692:             }
                   11693:         }
                   11694:     }
                   11695: }
                   11696: 
                   11697: function dependencyCheck(form,count,offset) {
                   11698:     if (count > 0) {
1.1059    raeburn  11699:         var chosen = (offset+$startcount)+7*(count-1);
                   11700:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11701:         var currtype = form.elements[depitem].type;
                   11702:         if (form.elements[chosen].value == 'dependency') {
                   11703:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11704:             form.elements[depitem].options.length = 0;
                   11705:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  11706:             for (var i=1; i<=numitems; i++) {
                   11707:                 if (i == count) {
                   11708:                     continue;
                   11709:                 }
1.1059    raeburn  11710:                 var startelement = $startcount + (i-1) * 7;
                   11711:                 for (var j=1; j<6; j++) {
                   11712:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11713:                         var item = startelement + j;
                   11714:                         if (form.elements[item].type == 'radio') {
                   11715:                             if (form.elements[item].checked) {
                   11716:                                 if (form.elements[item].value == 'display') {
                   11717:                                     var n = form.elements[depitem].options.length;
                   11718:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11719:                                 }
                   11720:                             }
                   11721:                         }
                   11722:                     }
                   11723:                 }
                   11724:             }
                   11725:         } else {
                   11726:             document.getElementById('arc_depon_'+count).style.display='none';
                   11727:             form.elements[depitem].options.length = 0;
                   11728:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11729:         }
1.1059    raeburn  11730:         titleCheck(form,count,offset);
1.1056    raeburn  11731:     }
                   11732: }
                   11733: 
                   11734: function propagateSelect(form,count,offset) {
                   11735:     if (count > 0) {
1.1065    raeburn  11736:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11737:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11738:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11739:             if (parents[count].length > 0) {
                   11740:                 for (var j=0; j<parents[count].length; j++) {
                   11741:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11742:                 }
                   11743:             }
                   11744:         }
                   11745:     }
                   11746: }
1.1056    raeburn  11747: 
                   11748: function containerSelect(form,count,offset,picked) {
                   11749:     if (count > 0) {
1.1065    raeburn  11750:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11751:         if (form.elements[item].type == 'radio') {
                   11752:             if (form.elements[item].value == 'dependency') {
                   11753:                 if (form.elements[item+1].type == 'select-one') {
                   11754:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11755:                         if (form.elements[item+1].options[i].value == picked) {
                   11756:                             form.elements[item+1].selectedIndex = i;
                   11757:                             break;
                   11758:                         }
                   11759:                     }
                   11760:                 }
                   11761:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11762:                     if (parents[count].length > 0) {
                   11763:                         for (var j=0; j<parents[count].length; j++) {
                   11764:                             containerSelect(form,parents[count][j],offset,picked);
                   11765:                         }
                   11766:                     }
                   11767:                 }
                   11768:             }
                   11769:         }
                   11770:     }
                   11771: }
                   11772: 
1.1059    raeburn  11773: function titleCheck(form,count,offset) {
                   11774:     if (count > 0) {
                   11775:         var chosen = (offset+$startcount)+7*(count-1);
                   11776:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11777:         var currtype = form.elements[depitem].type;
                   11778:         if (form.elements[chosen].value == 'display') {
                   11779:             document.getElementById('arc_title_'+count).style.display='block';
                   11780:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11781:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11782:             }
                   11783:         } else {
                   11784:             document.getElementById('arc_title_'+count).style.display='none';
                   11785:             if (currtype == 'text') { 
                   11786:                 document.getElementById('archive_title_'+count).value='';
                   11787:             }
                   11788:         }
                   11789:     }
                   11790:     return;
                   11791: }
                   11792: 
1.1055    raeburn  11793: // ]]>
                   11794: </script>
                   11795: END
                   11796:     return $scripttag;
                   11797: }
                   11798: 
                   11799: sub process_extracted_files {
1.1067    raeburn  11800:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11801:     my $numitems = $env{'form.archive_count'};
                   11802:     return unless ($numitems);
                   11803:     my @ids=&Apache::lonnet::current_machine_ids();
                   11804:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11805:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11806:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11807:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11808:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11809:         $pathtocheck = "$dir_root/$destination";
                   11810:         $dir = $dir_root;
                   11811:         $ishome = 1;
                   11812:     } else {
                   11813:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11814:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11815:         $dir = "$dir_root/$docudom/$docuname";    
                   11816:     }
                   11817:     my $currdir = "$dir_root/$destination";
                   11818:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11819:     if ($env{'form.folderpath'}) {
                   11820:         my @items = split('&',$env{'form.folderpath'});
                   11821:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  11822:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11823:             $containers{'0'}='page';
                   11824:         } else {
                   11825:             $containers{'0'}='sequence';
                   11826:         }
1.1055    raeburn  11827:     }
                   11828:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11829:     if ($numitems) {
                   11830:         for (my $i=1; $i<=$numitems; $i++) {
                   11831:             my $path = $env{'form.archive_content_'.$i};
                   11832:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11833:                 my $item = $1;
                   11834:                 $toplevelitems{$item} = $i;
                   11835:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11836:                     $is_dir{$item} = 1;
                   11837:                 }
                   11838:             }
                   11839:         }
                   11840:     }
1.1067    raeburn  11841:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11842:     if (keys(%toplevelitems) > 0) {
                   11843:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11844:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11845:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11846:     }
1.1066    raeburn  11847:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11848:     if ($numitems) {
                   11849:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  11850:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11851:             my $path = $env{'form.archive_content_'.$i};
                   11852:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11853:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11854:                     if ($prefix ne '' && $path ne '') {
                   11855:                         if (-e $prefix.$path) {
1.1066    raeburn  11856:                             if ((@archdirs > 0) && 
                   11857:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11858:                                 $todeletedir{$prefix.$path} = 1;
                   11859:                             } else {
                   11860:                                 $todelete{$prefix.$path} = 1;
                   11861:                             }
1.1055    raeburn  11862:                         }
                   11863:                     }
                   11864:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11865:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11866:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11867:                     $docstitle = $env{'form.archive_title_'.$i};
                   11868:                     if ($docstitle eq '') {
                   11869:                         $docstitle = $title;
                   11870:                     }
1.1055    raeburn  11871:                     $outer = 0;
1.1056    raeburn  11872:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11873:                         if (@{$dirorder{$i}} > 0) {
                   11874:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11875:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11876:                                     $outer = $item;
                   11877:                                     last;
                   11878:                                 }
                   11879:                             }
                   11880:                         }
                   11881:                     }
                   11882:                     my ($errtext,$fatal) = 
                   11883:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11884:                                                '/'.$folders{$outer}.'.'.
                   11885:                                                $containers{$outer});
                   11886:                     next if ($fatal);
                   11887:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11888:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11889:                             $mapinner{$i} = time;
1.1055    raeburn  11890:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11891:                             $containers{$i} = 'sequence';
                   11892:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11893:                                       $folders{$i}.'.'.$containers{$i};
                   11894:                             my $newidx = &LONCAPA::map::getresidx();
                   11895:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11896:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11897:                             push(@LONCAPA::map::order,$newidx);
                   11898:                             my ($outtext,$errtext) =
                   11899:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11900:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11901:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11902:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11903:                             unless ($errtext) {
                   11904:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11905:                             }
1.1055    raeburn  11906:                         }
                   11907:                     } else {
                   11908:                         if ($context eq 'coursedocs') {
                   11909:                             my $newidx=&LONCAPA::map::getresidx();
                   11910:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11911:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11912:                                       $title;
                   11913:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11914:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11915:                             }
                   11916:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11917:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11918:                             }
                   11919:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11920:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11921:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11922:                                 unless ($ishome) {
                   11923:                                     my $fetch = "$newdest{$i}/$title";
                   11924:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11925:                                     $prompttofetch{$fetch} = 1;
                   11926:                                 }
1.1055    raeburn  11927:                             }
                   11928:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11929:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11930:                             push(@LONCAPA::map::order, $newidx);
                   11931:                             my ($outtext,$errtext)=
                   11932:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11933:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11934:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11935:                             unless ($errtext) {
                   11936:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11937:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11938:                                 }
                   11939:                             }
1.1055    raeburn  11940:                         }
                   11941:                     }
1.1075.2.11  raeburn  11942:                 }
                   11943:             } else {
                   11944:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   11945:             }
                   11946:         }
                   11947:         for (my $i=1; $i<=$numitems; $i++) {
                   11948:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11949:             my $path = $env{'form.archive_content_'.$i};
                   11950:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11951:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11952:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11953:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11954:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11955:                         my ($itemidx,$fullpath,$relpath);
                   11956:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11957:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11958:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  11959:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11960:                                     $itemidx = $j;
1.1056    raeburn  11961:                                 }
                   11962:                             }
1.1075.2.11  raeburn  11963:                         }
                   11964:                         if ($itemidx eq '') {
                   11965:                             $itemidx =  0;
                   11966:                         }
                   11967:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11968:                             if ($mapinner{$referrer{$i}}) {
                   11969:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11970:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11971:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11972:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11973:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11974:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11975:                                             if (!-e $fullpath) {
                   11976:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11977:                                             }
                   11978:                                         }
1.1075.2.11  raeburn  11979:                                     } else {
                   11980:                                         last;
1.1056    raeburn  11981:                                     }
1.1075.2.11  raeburn  11982:                                 }
                   11983:                             }
                   11984:                         } elsif ($newdest{$referrer{$i}}) {
                   11985:                             $fullpath = $newdest{$referrer{$i}};
                   11986:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11987:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11988:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11989:                                     last;
                   11990:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11991:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11992:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11993:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11994:                                         if (!-e $fullpath) {
                   11995:                                             mkdir($fullpath,0755);
1.1056    raeburn  11996:                                         }
                   11997:                                     }
1.1075.2.11  raeburn  11998:                                 } else {
                   11999:                                     last;
1.1056    raeburn  12000:                                 }
1.1075.2.11  raeburn  12001:                             }
                   12002:                         }
                   12003:                         if ($fullpath ne '') {
                   12004:                             if (-e "$prefix$path") {
                   12005:                                 system("mv $prefix$path $fullpath/$title");
                   12006:                             }
                   12007:                             if (-e "$fullpath/$title") {
                   12008:                                 my $showpath;
                   12009:                                 if ($relpath ne '') {
                   12010:                                     $showpath = "$relpath/$title";
                   12011:                                 } else {
                   12012:                                     $showpath = "/$title";
1.1056    raeburn  12013:                                 }
1.1075.2.11  raeburn  12014:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12015:                             }
                   12016:                             unless ($ishome) {
                   12017:                                 my $fetch = "$fullpath/$title";
                   12018:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12019:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12020:                             }
                   12021:                         }
                   12022:                     }
1.1075.2.11  raeburn  12023:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12024:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12025:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12026:                 }
                   12027:             } else {
1.1075.2.11  raeburn  12028:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12029:             }
                   12030:         }
                   12031:         if (keys(%todelete)) {
                   12032:             foreach my $key (keys(%todelete)) {
                   12033:                 unlink($key);
1.1066    raeburn  12034:             }
                   12035:         }
                   12036:         if (keys(%todeletedir)) {
                   12037:             foreach my $key (keys(%todeletedir)) {
                   12038:                 rmdir($key);
                   12039:             }
                   12040:         }
                   12041:         foreach my $dir (sort(keys(%is_dir))) {
                   12042:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12043:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12044:             }
                   12045:         }
1.1067    raeburn  12046:         if ($result ne '') {
                   12047:             $output .= '<ul>'."\n".
                   12048:                        $result."\n".
                   12049:                        '</ul>';
                   12050:         }
                   12051:         unless ($ishome) {
                   12052:             my $replicationfail;
                   12053:             foreach my $item (keys(%prompttofetch)) {
                   12054:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12055:                 unless ($fetchresult eq 'ok') {
                   12056:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12057:                 }
                   12058:             }
                   12059:             if ($replicationfail) {
                   12060:                 $output .= '<p class="LC_error">'.
                   12061:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12062:                            $replicationfail.
                   12063:                            '</ul></p>';
                   12064:             }
                   12065:         }
1.1055    raeburn  12066:     } else {
                   12067:         $warning = &mt('No items found in archive.');
                   12068:     }
                   12069:     if ($error) {
                   12070:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12071:                    $error.'</p>'."\n";
                   12072:     }
                   12073:     if ($warning) {
                   12074:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12075:     }
                   12076:     return $output;
                   12077: }
                   12078: 
1.1066    raeburn  12079: sub cleanup_empty_dirs {
                   12080:     my ($path) = @_;
                   12081:     if (($path ne '') && (-d $path)) {
                   12082:         if (opendir(my $dirh,$path)) {
                   12083:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12084:             my $numitems = 0;
                   12085:             foreach my $item (@dircontents) {
                   12086:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12087:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12088:                     if (-e "$path/$item") {
                   12089:                         $numitems ++;
                   12090:                     }
                   12091:                 } else {
                   12092:                     $numitems ++;
                   12093:                 }
                   12094:             }
                   12095:             if ($numitems == 0) {
                   12096:                 rmdir($path);
                   12097:             }
                   12098:             closedir($dirh);
                   12099:         }
                   12100:     }
                   12101:     return;
                   12102: }
                   12103: 
1.41      ng       12104: =pod
1.45      matthew  12105: 
1.1075.2.56  raeburn  12106: =item * &get_folder_hierarchy()
1.1068    raeburn  12107: 
                   12108: Provides hierarchy of names of folders/sub-folders containing the current
                   12109: item,
                   12110: 
                   12111: Inputs: 3
                   12112:      - $navmap - navmaps object
                   12113: 
                   12114:      - $map - url for map (either the trigger itself, or map containing
                   12115:                            the resource, which is the trigger).
                   12116: 
                   12117:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12118: 
                   12119: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12120: 
                   12121: =cut
                   12122: 
                   12123: sub get_folder_hierarchy {
                   12124:     my ($navmap,$map,$showitem) = @_;
                   12125:     my @pathitems;
                   12126:     if (ref($navmap)) {
                   12127:         my $mapres = $navmap->getResourceByUrl($map);
                   12128:         if (ref($mapres)) {
                   12129:             my $pcslist = $mapres->map_hierarchy();
                   12130:             if ($pcslist ne '') {
                   12131:                 my @pcs = split(/,/,$pcslist);
                   12132:                 foreach my $pc (@pcs) {
                   12133:                     if ($pc == 1) {
1.1075.2.38  raeburn  12134:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12135:                     } else {
                   12136:                         my $res = $navmap->getByMapPc($pc);
                   12137:                         if (ref($res)) {
                   12138:                             my $title = $res->compTitle();
                   12139:                             $title =~ s/\W+/_/g;
                   12140:                             if ($title ne '') {
                   12141:                                 push(@pathitems,$title);
                   12142:                             }
                   12143:                         }
                   12144:                     }
                   12145:                 }
                   12146:             }
1.1071    raeburn  12147:             if ($showitem) {
                   12148:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12149:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12150:                 } else {
                   12151:                     my $maptitle = $mapres->compTitle();
                   12152:                     $maptitle =~ s/\W+/_/g;
                   12153:                     if ($maptitle ne '') {
                   12154:                         push(@pathitems,$maptitle);
                   12155:                     }
1.1068    raeburn  12156:                 }
                   12157:             }
                   12158:         }
                   12159:     }
                   12160:     return @pathitems;
                   12161: }
                   12162: 
                   12163: =pod
                   12164: 
1.1015    raeburn  12165: =item * &get_turnedin_filepath()
                   12166: 
                   12167: Determines path in a user's portfolio file for storage of files uploaded
                   12168: to a specific essayresponse or dropbox item.
                   12169: 
                   12170: Inputs: 3 required + 1 optional.
                   12171: $symb is symb for resource, $uname and $udom are for current user (required).
                   12172: $caller is optional (can be "submission", if routine is called when storing
                   12173: an upoaded file when "Submit Answer" button was pressed).
                   12174: 
                   12175: Returns array containing $path and $multiresp. 
                   12176: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12177: than one file upload item.  Callers of routine should append partid as a 
                   12178: subdirectory to $path in cases where $multiresp is 1.
                   12179: 
                   12180: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12181: 
                   12182: =cut
                   12183: 
                   12184: sub get_turnedin_filepath {
                   12185:     my ($symb,$uname,$udom,$caller) = @_;
                   12186:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12187:     my $turnindir;
                   12188:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12189:     $turnindir = $userhash{'turnindir'};
                   12190:     my ($path,$multiresp);
                   12191:     if ($turnindir eq '') {
                   12192:         if ($caller eq 'submission') {
                   12193:             $turnindir = &mt('turned in');
                   12194:             $turnindir =~ s/\W+/_/g;
                   12195:             my %newhash = (
                   12196:                             'turnindir' => $turnindir,
                   12197:                           );
                   12198:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12199:         }
                   12200:     }
                   12201:     if ($turnindir ne '') {
                   12202:         $path = '/'.$turnindir.'/';
                   12203:         my ($multipart,$turnin,@pathitems);
                   12204:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12205:         if (defined($navmap)) {
                   12206:             my $mapres = $navmap->getResourceByUrl($map);
                   12207:             if (ref($mapres)) {
                   12208:                 my $pcslist = $mapres->map_hierarchy();
                   12209:                 if ($pcslist ne '') {
                   12210:                     foreach my $pc (split(/,/,$pcslist)) {
                   12211:                         my $res = $navmap->getByMapPc($pc);
                   12212:                         if (ref($res)) {
                   12213:                             my $title = $res->compTitle();
                   12214:                             $title =~ s/\W+/_/g;
                   12215:                             if ($title ne '') {
1.1075.2.48  raeburn  12216:                                 if (($pc > 1) && (length($title) > 12)) {
                   12217:                                     $title = substr($title,0,12);
                   12218:                                 }
1.1015    raeburn  12219:                                 push(@pathitems,$title);
                   12220:                             }
                   12221:                         }
                   12222:                     }
                   12223:                 }
                   12224:                 my $maptitle = $mapres->compTitle();
                   12225:                 $maptitle =~ s/\W+/_/g;
                   12226:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12227:                     if (length($maptitle) > 12) {
                   12228:                         $maptitle = substr($maptitle,0,12);
                   12229:                     }
1.1015    raeburn  12230:                     push(@pathitems,$maptitle);
                   12231:                 }
                   12232:                 unless ($env{'request.state'} eq 'construct') {
                   12233:                     my $res = $navmap->getBySymb($symb);
                   12234:                     if (ref($res)) {
                   12235:                         my $partlist = $res->parts();
                   12236:                         my $totaluploads = 0;
                   12237:                         if (ref($partlist) eq 'ARRAY') {
                   12238:                             foreach my $part (@{$partlist}) {
                   12239:                                 my @types = $res->responseType($part);
                   12240:                                 my @ids = $res->responseIds($part);
                   12241:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12242:                                     if ($types[$i] eq 'essay') {
                   12243:                                         my $partid = $part.'_'.$ids[$i];
                   12244:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12245:                                             $totaluploads ++;
                   12246:                                         }
                   12247:                                     }
                   12248:                                 }
                   12249:                             }
                   12250:                             if ($totaluploads > 1) {
                   12251:                                 $multiresp = 1;
                   12252:                             }
                   12253:                         }
                   12254:                     }
                   12255:                 }
                   12256:             } else {
                   12257:                 return;
                   12258:             }
                   12259:         } else {
                   12260:             return;
                   12261:         }
                   12262:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12263:         $restitle =~ s/\W+/_/g;
                   12264:         if ($restitle eq '') {
                   12265:             $restitle = ($resurl =~ m{/[^/]+$});
                   12266:             if ($restitle eq '') {
                   12267:                 $restitle = time;
                   12268:             }
                   12269:         }
1.1075.2.48  raeburn  12270:         if (length($restitle) > 12) {
                   12271:             $restitle = substr($restitle,0,12);
                   12272:         }
1.1015    raeburn  12273:         push(@pathitems,$restitle);
                   12274:         $path .= join('/',@pathitems);
                   12275:     }
                   12276:     return ($path,$multiresp);
                   12277: }
                   12278: 
                   12279: =pod
                   12280: 
1.464     albertel 12281: =back
1.41      ng       12282: 
1.112     bowersj2 12283: =head1 CSV Upload/Handling functions
1.38      albertel 12284: 
1.41      ng       12285: =over 4
                   12286: 
1.648     raeburn  12287: =item * &upfile_store($r)
1.41      ng       12288: 
                   12289: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12290: needs $env{'form.upfile'}
1.41      ng       12291: returns $datatoken to be put into hidden field
                   12292: 
                   12293: =cut
1.31      albertel 12294: 
                   12295: sub upfile_store {
                   12296:     my $r=shift;
1.258     albertel 12297:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12298:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12299:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12300:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12301: 
1.258     albertel 12302:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12303: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12304:     {
1.158     raeburn  12305:         my $datafile = $r->dir_config('lonDaemons').
                   12306:                            '/tmp/'.$datatoken.'.tmp';
                   12307:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12308:             print $fh $env{'form.upfile'};
1.158     raeburn  12309:             close($fh);
                   12310:         }
1.31      albertel 12311:     }
                   12312:     return $datatoken;
                   12313: }
                   12314: 
1.56      matthew  12315: =pod
                   12316: 
1.648     raeburn  12317: =item * &load_tmp_file($r)
1.41      ng       12318: 
                   12319: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12320: needs $env{'form.datatoken'},
                   12321: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12322: 
                   12323: =cut
1.31      albertel 12324: 
                   12325: sub load_tmp_file {
                   12326:     my $r=shift;
                   12327:     my @studentdata=();
                   12328:     {
1.158     raeburn  12329:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12330:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12331:         if ( open(my $fh,"<$studentfile") ) {
                   12332:             @studentdata=<$fh>;
                   12333:             close($fh);
                   12334:         }
1.31      albertel 12335:     }
1.258     albertel 12336:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12337: }
                   12338: 
1.56      matthew  12339: =pod
                   12340: 
1.648     raeburn  12341: =item * &upfile_record_sep()
1.41      ng       12342: 
                   12343: Separate uploaded file into records
                   12344: returns array of records,
1.258     albertel 12345: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12346: 
                   12347: =cut
1.31      albertel 12348: 
                   12349: sub upfile_record_sep {
1.258     albertel 12350:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12351:     } else {
1.248     albertel 12352: 	my @records;
1.258     albertel 12353: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12354: 	    if ($line=~/^\s*$/) { next; }
                   12355: 	    push(@records,$line);
                   12356: 	}
                   12357: 	return @records;
1.31      albertel 12358:     }
                   12359: }
                   12360: 
1.56      matthew  12361: =pod
                   12362: 
1.648     raeburn  12363: =item * &record_sep($record)
1.41      ng       12364: 
1.258     albertel 12365: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12366: 
                   12367: =cut
                   12368: 
1.263     www      12369: sub takeleft {
                   12370:     my $index=shift;
                   12371:     return substr('0000'.$index,-4,4);
                   12372: }
                   12373: 
1.31      albertel 12374: sub record_sep {
                   12375:     my $record=shift;
                   12376:     my %components=();
1.258     albertel 12377:     if ($env{'form.upfiletype'} eq 'xml') {
                   12378:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12379:         my $i=0;
1.356     albertel 12380:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12381:             $field=~s/^(\"|\')//;
                   12382:             $field=~s/(\"|\')$//;
1.263     www      12383:             $components{&takeleft($i)}=$field;
1.31      albertel 12384:             $i++;
                   12385:         }
1.258     albertel 12386:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12387:         my $i=0;
1.356     albertel 12388:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12389:             $field=~s/^(\"|\')//;
                   12390:             $field=~s/(\"|\')$//;
1.263     www      12391:             $components{&takeleft($i)}=$field;
1.31      albertel 12392:             $i++;
                   12393:         }
                   12394:     } else {
1.561     www      12395:         my $separator=',';
1.480     banghart 12396:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12397:             $separator=';';
1.480     banghart 12398:         }
1.31      albertel 12399:         my $i=0;
1.561     www      12400: # the character we are looking for to indicate the end of a quote or a record 
                   12401:         my $looking_for=$separator;
                   12402: # do not add the characters to the fields
                   12403:         my $ignore=0;
                   12404: # we just encountered a separator (or the beginning of the record)
                   12405:         my $just_found_separator=1;
                   12406: # store the field we are working on here
                   12407:         my $field='';
                   12408: # work our way through all characters in record
                   12409:         foreach my $character ($record=~/(.)/g) {
                   12410:             if ($character eq $looking_for) {
                   12411:                if ($character ne $separator) {
                   12412: # Found the end of a quote, again looking for separator
                   12413:                   $looking_for=$separator;
                   12414:                   $ignore=1;
                   12415:                } else {
                   12416: # Found a separator, store away what we got
                   12417:                   $components{&takeleft($i)}=$field;
                   12418: 	          $i++;
                   12419:                   $just_found_separator=1;
                   12420:                   $ignore=0;
                   12421:                   $field='';
                   12422:                }
                   12423:                next;
                   12424:             }
                   12425: # single or double quotation marks after a separator indicate beginning of a quote
                   12426: # we are now looking for the end of the quote and need to ignore separators
                   12427:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12428:                $looking_for=$character;
                   12429:                next;
                   12430:             }
                   12431: # ignore would be true after we reached the end of a quote
                   12432:             if ($ignore) { next; }
                   12433:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12434:             $field.=$character;
                   12435:             $just_found_separator=0; 
1.31      albertel 12436:         }
1.561     www      12437: # catch the very last entry, since we never encountered the separator
                   12438:         $components{&takeleft($i)}=$field;
1.31      albertel 12439:     }
                   12440:     return %components;
                   12441: }
                   12442: 
1.144     matthew  12443: ######################################################
                   12444: ######################################################
                   12445: 
1.56      matthew  12446: =pod
                   12447: 
1.648     raeburn  12448: =item * &upfile_select_html()
1.41      ng       12449: 
1.144     matthew  12450: Return HTML code to select a file from the users machine and specify 
                   12451: the file type.
1.41      ng       12452: 
                   12453: =cut
                   12454: 
1.144     matthew  12455: ######################################################
                   12456: ######################################################
1.31      albertel 12457: sub upfile_select_html {
1.144     matthew  12458:     my %Types = (
                   12459:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12460:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12461:                  space => &mt('Space separated'),
                   12462:                  tab   => &mt('Tabulator separated'),
                   12463: #                 xml   => &mt('HTML/XML'),
                   12464:                  );
                   12465:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12466:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12467:     foreach my $type (sort(keys(%Types))) {
                   12468:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12469:     }
                   12470:     $Str .= "</select>\n";
                   12471:     return $Str;
1.31      albertel 12472: }
                   12473: 
1.301     albertel 12474: sub get_samples {
                   12475:     my ($records,$toget) = @_;
                   12476:     my @samples=({});
                   12477:     my $got=0;
                   12478:     foreach my $rec (@$records) {
                   12479: 	my %temp = &record_sep($rec);
                   12480: 	if (! grep(/\S/, values(%temp))) { next; }
                   12481: 	if (%temp) {
                   12482: 	    $samples[$got]=\%temp;
                   12483: 	    $got++;
                   12484: 	    if ($got == $toget) { last; }
                   12485: 	}
                   12486:     }
                   12487:     return \@samples;
                   12488: }
                   12489: 
1.144     matthew  12490: ######################################################
                   12491: ######################################################
                   12492: 
1.56      matthew  12493: =pod
                   12494: 
1.648     raeburn  12495: =item * &csv_print_samples($r,$records)
1.41      ng       12496: 
                   12497: Prints a table of sample values from each column uploaded $r is an
                   12498: Apache Request ref, $records is an arrayref from
                   12499: &Apache::loncommon::upfile_record_sep
                   12500: 
                   12501: =cut
                   12502: 
1.144     matthew  12503: ######################################################
                   12504: ######################################################
1.31      albertel 12505: sub csv_print_samples {
                   12506:     my ($r,$records) = @_;
1.662     bisitz   12507:     my $samples = &get_samples($records,5);
1.301     albertel 12508: 
1.594     raeburn  12509:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12510:               &start_data_table_header_row());
1.356     albertel 12511:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12512:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12513:     $r->print(&end_data_table_header_row());
1.301     albertel 12514:     foreach my $hash (@$samples) {
1.594     raeburn  12515: 	$r->print(&start_data_table_row());
1.356     albertel 12516: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12517: 	    $r->print('<td>');
1.356     albertel 12518: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12519: 	    $r->print('</td>');
                   12520: 	}
1.594     raeburn  12521: 	$r->print(&end_data_table_row());
1.31      albertel 12522:     }
1.594     raeburn  12523:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12524: }
                   12525: 
1.144     matthew  12526: ######################################################
                   12527: ######################################################
                   12528: 
1.56      matthew  12529: =pod
                   12530: 
1.648     raeburn  12531: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12532: 
                   12533: Prints a table to create associations between values and table columns.
1.144     matthew  12534: 
1.41      ng       12535: $r is an Apache Request ref,
                   12536: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12537: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12538: 
                   12539: =cut
                   12540: 
1.144     matthew  12541: ######################################################
                   12542: ######################################################
1.31      albertel 12543: sub csv_print_select_table {
                   12544:     my ($r,$records,$d) = @_;
1.301     albertel 12545:     my $i=0;
                   12546:     my $samples = &get_samples($records,1);
1.144     matthew  12547:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12548: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12549:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12550:               '<th>'.&mt('Column').'</th>'.
                   12551:               &end_data_table_header_row()."\n");
1.356     albertel 12552:     foreach my $array_ref (@$d) {
                   12553: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12554: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12555: 
1.875     bisitz   12556: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12557: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12558: 	$r->print('<option value="none"></option>');
1.356     albertel 12559: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12560: 	    $r->print('<option value="'.$sample.'"'.
                   12561:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12562:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12563: 	}
1.594     raeburn  12564: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12565: 	$i++;
                   12566:     }
1.594     raeburn  12567:     $r->print(&end_data_table());
1.31      albertel 12568:     $i--;
                   12569:     return $i;
                   12570: }
1.56      matthew  12571: 
1.144     matthew  12572: ######################################################
                   12573: ######################################################
                   12574: 
1.56      matthew  12575: =pod
1.31      albertel 12576: 
1.648     raeburn  12577: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12578: 
                   12579: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12580: 
                   12581: $r is an Apache Request ref,
                   12582: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12583: $d is an array of 2 element arrays (internal name, displayed name)
                   12584: 
                   12585: =cut
                   12586: 
1.144     matthew  12587: ######################################################
                   12588: ######################################################
1.31      albertel 12589: sub csv_samples_select_table {
                   12590:     my ($r,$records,$d) = @_;
                   12591:     my $i=0;
1.144     matthew  12592:     #
1.662     bisitz   12593:     my $max_samples = 5;
                   12594:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12595:     $r->print(&start_data_table().
                   12596:               &start_data_table_header_row().'<th>'.
                   12597:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12598:               &end_data_table_header_row());
1.301     albertel 12599: 
                   12600:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12601: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12602: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12603: 	foreach my $option (@$d) {
                   12604: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12605: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12606:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12607:                       $display.'</option>');
1.31      albertel 12608: 	}
                   12609: 	$r->print('</select></td><td>');
1.662     bisitz   12610: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12611: 	    if (defined($samples->[$line]{$key})) { 
                   12612: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12613: 	    }
                   12614: 	}
1.594     raeburn  12615: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12616: 	$i++;
                   12617:     }
1.594     raeburn  12618:     $r->print(&end_data_table());
1.31      albertel 12619:     $i--;
                   12620:     return($i);
1.115     matthew  12621: }
                   12622: 
1.144     matthew  12623: ######################################################
                   12624: ######################################################
                   12625: 
1.115     matthew  12626: =pod
                   12627: 
1.648     raeburn  12628: =item * &clean_excel_name($name)
1.115     matthew  12629: 
                   12630: Returns a replacement for $name which does not contain any illegal characters.
                   12631: 
                   12632: =cut
                   12633: 
1.144     matthew  12634: ######################################################
                   12635: ######################################################
1.115     matthew  12636: sub clean_excel_name {
                   12637:     my ($name) = @_;
                   12638:     $name =~ s/[:\*\?\/\\]//g;
                   12639:     if (length($name) > 31) {
                   12640:         $name = substr($name,0,31);
                   12641:     }
                   12642:     return $name;
1.25      albertel 12643: }
1.84      albertel 12644: 
1.85      albertel 12645: =pod
                   12646: 
1.648     raeburn  12647: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12648: 
                   12649: Returns either 1 or undef
                   12650: 
                   12651: 1 if the part is to be hidden, undef if it is to be shown
                   12652: 
                   12653: Arguments are:
                   12654: 
                   12655: $id the id of the part to be checked
                   12656: $symb, optional the symb of the resource to check
                   12657: $udom, optional the domain of the user to check for
                   12658: $uname, optional the username of the user to check for
                   12659: 
                   12660: =cut
1.84      albertel 12661: 
                   12662: sub check_if_partid_hidden {
                   12663:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12664:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12665: 					 $symb,$udom,$uname);
1.141     albertel 12666:     my $truth=1;
                   12667:     #if the string starts with !, then the list is the list to show not hide
                   12668:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12669:     my @hiddenlist=split(/,/,$hiddenparts);
                   12670:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12671: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12672:     }
1.141     albertel 12673:     return !$truth;
1.84      albertel 12674: }
1.127     matthew  12675: 
1.138     matthew  12676: 
                   12677: ############################################################
                   12678: ############################################################
                   12679: 
                   12680: =pod
                   12681: 
1.157     matthew  12682: =back 
                   12683: 
1.138     matthew  12684: =head1 cgi-bin script and graphing routines
                   12685: 
1.157     matthew  12686: =over 4
                   12687: 
1.648     raeburn  12688: =item * &get_cgi_id()
1.138     matthew  12689: 
                   12690: Inputs: none
                   12691: 
                   12692: Returns an id which can be used to pass environment variables
                   12693: to various cgi-bin scripts.  These environment variables will
                   12694: be removed from the users environment after a given time by
                   12695: the routine &Apache::lonnet::transfer_profile_to_env.
                   12696: 
                   12697: =cut
                   12698: 
                   12699: ############################################################
                   12700: ############################################################
1.152     albertel 12701: my $uniq=0;
1.136     matthew  12702: sub get_cgi_id {
1.154     albertel 12703:     $uniq=($uniq+1)%100000;
1.280     albertel 12704:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12705: }
                   12706: 
1.127     matthew  12707: ############################################################
                   12708: ############################################################
                   12709: 
                   12710: =pod
                   12711: 
1.648     raeburn  12712: =item * &DrawBarGraph()
1.127     matthew  12713: 
1.138     matthew  12714: Facilitates the plotting of data in a (stacked) bar graph.
                   12715: Puts plot definition data into the users environment in order for 
                   12716: graph.png to plot it.  Returns an <img> tag for the plot.
                   12717: The bars on the plot are labeled '1','2',...,'n'.
                   12718: 
                   12719: Inputs:
                   12720: 
                   12721: =over 4
                   12722: 
                   12723: =item $Title: string, the title of the plot
                   12724: 
                   12725: =item $xlabel: string, text describing the X-axis of the plot
                   12726: 
                   12727: =item $ylabel: string, text describing the Y-axis of the plot
                   12728: 
                   12729: =item $Max: scalar, the maximum Y value to use in the plot
                   12730: If $Max is < any data point, the graph will not be rendered.
                   12731: 
1.140     matthew  12732: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12733: they are plotted.  If undefined, default values will be used.
                   12734: 
1.178     matthew  12735: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12736: 
1.138     matthew  12737: =item @Values: An array of array references.  Each array reference holds data
                   12738: to be plotted in a stacked bar chart.
                   12739: 
1.239     matthew  12740: =item If the final element of @Values is a hash reference the key/value
                   12741: pairs will be added to the graph definition.
                   12742: 
1.138     matthew  12743: =back
                   12744: 
                   12745: Returns:
                   12746: 
                   12747: An <img> tag which references graph.png and the appropriate identifying
                   12748: information for the plot.
                   12749: 
1.127     matthew  12750: =cut
                   12751: 
                   12752: ############################################################
                   12753: ############################################################
1.134     matthew  12754: sub DrawBarGraph {
1.178     matthew  12755:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12756:     #
                   12757:     if (! defined($colors)) {
                   12758:         $colors = ['#33ff00', 
                   12759:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12760:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12761:                   ]; 
                   12762:     }
1.228     matthew  12763:     my $extra_settings = {};
                   12764:     if (ref($Values[-1]) eq 'HASH') {
                   12765:         $extra_settings = pop(@Values);
                   12766:     }
1.127     matthew  12767:     #
1.136     matthew  12768:     my $identifier = &get_cgi_id();
                   12769:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12770:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12771:         return '';
                   12772:     }
1.225     matthew  12773:     #
                   12774:     my @Labels;
                   12775:     if (defined($labels)) {
                   12776:         @Labels = @$labels;
                   12777:     } else {
                   12778:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12779:             push (@Labels,$i+1);
                   12780:         }
                   12781:     }
                   12782:     #
1.129     matthew  12783:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12784:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12785:     my %ValuesHash;
                   12786:     my $NumSets=1;
                   12787:     foreach my $array (@Values) {
                   12788:         next if (! ref($array));
1.136     matthew  12789:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12790:             join(',',@$array);
1.129     matthew  12791:     }
1.127     matthew  12792:     #
1.136     matthew  12793:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12794:     if ($NumBars < 3) {
                   12795:         $width = 120+$NumBars*32;
1.220     matthew  12796:         $xskip = 1;
1.225     matthew  12797:         $bar_width = 30;
                   12798:     } elsif ($NumBars < 5) {
                   12799:         $width = 120+$NumBars*20;
                   12800:         $xskip = 1;
                   12801:         $bar_width = 20;
1.220     matthew  12802:     } elsif ($NumBars < 10) {
1.136     matthew  12803:         $width = 120+$NumBars*15;
                   12804:         $xskip = 1;
                   12805:         $bar_width = 15;
                   12806:     } elsif ($NumBars <= 25) {
                   12807:         $width = 120+$NumBars*11;
                   12808:         $xskip = 5;
                   12809:         $bar_width = 8;
                   12810:     } elsif ($NumBars <= 50) {
                   12811:         $width = 120+$NumBars*8;
                   12812:         $xskip = 5;
                   12813:         $bar_width = 4;
                   12814:     } else {
                   12815:         $width = 120+$NumBars*8;
                   12816:         $xskip = 5;
                   12817:         $bar_width = 4;
                   12818:     }
                   12819:     #
1.137     matthew  12820:     $Max = 1 if ($Max < 1);
                   12821:     if ( int($Max) < $Max ) {
                   12822:         $Max++;
                   12823:         $Max = int($Max);
                   12824:     }
1.127     matthew  12825:     $Title  = '' if (! defined($Title));
                   12826:     $xlabel = '' if (! defined($xlabel));
                   12827:     $ylabel = '' if (! defined($ylabel));
1.369     www      12828:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12829:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12830:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12831:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12832:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12833:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12834:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12835:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12836:     $ValuesHash{$id.'.height'}   = $height;
                   12837:     $ValuesHash{$id.'.width'}    = $width;
                   12838:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12839:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12840:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12841:     #
1.228     matthew  12842:     # Deal with other parameters
                   12843:     while (my ($key,$value) = each(%$extra_settings)) {
                   12844:         $ValuesHash{$id.'.'.$key} = $value;
                   12845:     }
                   12846:     #
1.646     raeburn  12847:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12848:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12849: }
                   12850: 
                   12851: ############################################################
                   12852: ############################################################
                   12853: 
                   12854: =pod
                   12855: 
1.648     raeburn  12856: =item * &DrawXYGraph()
1.137     matthew  12857: 
1.138     matthew  12858: Facilitates the plotting of data in an XY graph.
                   12859: Puts plot definition data into the users environment in order for 
                   12860: graph.png to plot it.  Returns an <img> tag for the plot.
                   12861: 
                   12862: Inputs:
                   12863: 
                   12864: =over 4
                   12865: 
                   12866: =item $Title: string, the title of the plot
                   12867: 
                   12868: =item $xlabel: string, text describing the X-axis of the plot
                   12869: 
                   12870: =item $ylabel: string, text describing the Y-axis of the plot
                   12871: 
                   12872: =item $Max: scalar, the maximum Y value to use in the plot
                   12873: If $Max is < any data point, the graph will not be rendered.
                   12874: 
                   12875: =item $colors: Array ref containing the hex color codes for the data to be 
                   12876: plotted in.  If undefined, default values will be used.
                   12877: 
                   12878: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12879: 
                   12880: =item $Ydata: Array ref containing Array refs.  
1.185     www      12881: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12882: 
                   12883: =item %Values: hash indicating or overriding any default values which are 
                   12884: passed to graph.png.  
                   12885: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12886: 
                   12887: =back
                   12888: 
                   12889: Returns:
                   12890: 
                   12891: An <img> tag which references graph.png and the appropriate identifying
                   12892: information for the plot.
                   12893: 
1.137     matthew  12894: =cut
                   12895: 
                   12896: ############################################################
                   12897: ############################################################
                   12898: sub DrawXYGraph {
                   12899:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12900:     #
                   12901:     # Create the identifier for the graph
                   12902:     my $identifier = &get_cgi_id();
                   12903:     my $id = 'cgi.'.$identifier;
                   12904:     #
                   12905:     $Title  = '' if (! defined($Title));
                   12906:     $xlabel = '' if (! defined($xlabel));
                   12907:     $ylabel = '' if (! defined($ylabel));
                   12908:     my %ValuesHash = 
                   12909:         (
1.369     www      12910:          $id.'.title'  => &escape($Title),
                   12911:          $id.'.xlabel' => &escape($xlabel),
                   12912:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12913:          $id.'.y_max_value'=> $Max,
                   12914:          $id.'.labels'     => join(',',@$Xlabels),
                   12915:          $id.'.PlotType'   => 'XY',
                   12916:          );
                   12917:     #
                   12918:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12919:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12920:     }
                   12921:     #
                   12922:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12923:         return '';
                   12924:     }
                   12925:     my $NumSets=1;
1.138     matthew  12926:     foreach my $array (@{$Ydata}){
1.137     matthew  12927:         next if (! ref($array));
                   12928:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12929:     }
1.138     matthew  12930:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12931:     #
                   12932:     # Deal with other parameters
                   12933:     while (my ($key,$value) = each(%Values)) {
                   12934:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12935:     }
                   12936:     #
1.646     raeburn  12937:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12938:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12939: }
                   12940: 
                   12941: ############################################################
                   12942: ############################################################
                   12943: 
                   12944: =pod
                   12945: 
1.648     raeburn  12946: =item * &DrawXYYGraph()
1.138     matthew  12947: 
                   12948: Facilitates the plotting of data in an XY graph with two Y axes.
                   12949: Puts plot definition data into the users environment in order for 
                   12950: graph.png to plot it.  Returns an <img> tag for the plot.
                   12951: 
                   12952: Inputs:
                   12953: 
                   12954: =over 4
                   12955: 
                   12956: =item $Title: string, the title of the plot
                   12957: 
                   12958: =item $xlabel: string, text describing the X-axis of the plot
                   12959: 
                   12960: =item $ylabel: string, text describing the Y-axis of the plot
                   12961: 
                   12962: =item $colors: Array ref containing the hex color codes for the data to be 
                   12963: plotted in.  If undefined, default values will be used.
                   12964: 
                   12965: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12966: 
                   12967: =item $Ydata1: The first data set
                   12968: 
                   12969: =item $Min1: The minimum value of the left Y-axis
                   12970: 
                   12971: =item $Max1: The maximum value of the left Y-axis
                   12972: 
                   12973: =item $Ydata2: The second data set
                   12974: 
                   12975: =item $Min2: The minimum value of the right Y-axis
                   12976: 
                   12977: =item $Max2: The maximum value of the left Y-axis
                   12978: 
                   12979: =item %Values: hash indicating or overriding any default values which are 
                   12980: passed to graph.png.  
                   12981: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12982: 
                   12983: =back
                   12984: 
                   12985: Returns:
                   12986: 
                   12987: An <img> tag which references graph.png and the appropriate identifying
                   12988: information for the plot.
1.136     matthew  12989: 
                   12990: =cut
                   12991: 
                   12992: ############################################################
                   12993: ############################################################
1.137     matthew  12994: sub DrawXYYGraph {
                   12995:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12996:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12997:     #
                   12998:     # Create the identifier for the graph
                   12999:     my $identifier = &get_cgi_id();
                   13000:     my $id = 'cgi.'.$identifier;
                   13001:     #
                   13002:     $Title  = '' if (! defined($Title));
                   13003:     $xlabel = '' if (! defined($xlabel));
                   13004:     $ylabel = '' if (! defined($ylabel));
                   13005:     my %ValuesHash = 
                   13006:         (
1.369     www      13007:          $id.'.title'  => &escape($Title),
                   13008:          $id.'.xlabel' => &escape($xlabel),
                   13009:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13010:          $id.'.labels' => join(',',@$Xlabels),
                   13011:          $id.'.PlotType' => 'XY',
                   13012:          $id.'.NumSets' => 2,
1.137     matthew  13013:          $id.'.two_axes' => 1,
                   13014:          $id.'.y1_max_value' => $Max1,
                   13015:          $id.'.y1_min_value' => $Min1,
                   13016:          $id.'.y2_max_value' => $Max2,
                   13017:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13018:          );
                   13019:     #
1.137     matthew  13020:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13021:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13022:     }
                   13023:     #
                   13024:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13025:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13026:         return '';
                   13027:     }
                   13028:     my $NumSets=1;
1.137     matthew  13029:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13030:         next if (! ref($array));
                   13031:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13032:     }
                   13033:     #
                   13034:     # Deal with other parameters
                   13035:     while (my ($key,$value) = each(%Values)) {
                   13036:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13037:     }
                   13038:     #
1.646     raeburn  13039:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13040:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13041: }
                   13042: 
                   13043: ############################################################
                   13044: ############################################################
                   13045: 
                   13046: =pod
                   13047: 
1.157     matthew  13048: =back 
                   13049: 
1.139     matthew  13050: =head1 Statistics helper routines?  
                   13051: 
                   13052: Bad place for them but what the hell.
                   13053: 
1.157     matthew  13054: =over 4
                   13055: 
1.648     raeburn  13056: =item * &chartlink()
1.139     matthew  13057: 
                   13058: Returns a link to the chart for a specific student.  
                   13059: 
                   13060: Inputs:
                   13061: 
                   13062: =over 4
                   13063: 
                   13064: =item $linktext: The text of the link
                   13065: 
                   13066: =item $sname: The students username
                   13067: 
                   13068: =item $sdomain: The students domain
                   13069: 
                   13070: =back
                   13071: 
1.157     matthew  13072: =back
                   13073: 
1.139     matthew  13074: =cut
                   13075: 
                   13076: ############################################################
                   13077: ############################################################
                   13078: sub chartlink {
                   13079:     my ($linktext, $sname, $sdomain) = @_;
                   13080:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13081:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13082:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13083:        '">'.$linktext.'</a>';
1.153     matthew  13084: }
                   13085: 
                   13086: #######################################################
                   13087: #######################################################
                   13088: 
                   13089: =pod
                   13090: 
                   13091: =head1 Course Environment Routines
1.157     matthew  13092: 
                   13093: =over 4
1.153     matthew  13094: 
1.648     raeburn  13095: =item * &restore_course_settings()
1.153     matthew  13096: 
1.648     raeburn  13097: =item * &store_course_settings()
1.153     matthew  13098: 
                   13099: Restores/Store indicated form parameters from the course environment.
                   13100: Will not overwrite existing values of the form parameters.
                   13101: 
                   13102: Inputs: 
                   13103: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13104: 
                   13105: a hash ref describing the data to be stored.  For example:
                   13106:    
                   13107: %Save_Parameters = ('Status' => 'scalar',
                   13108:     'chartoutputmode' => 'scalar',
                   13109:     'chartoutputdata' => 'scalar',
                   13110:     'Section' => 'array',
1.373     raeburn  13111:     'Group' => 'array',
1.153     matthew  13112:     'StudentData' => 'array',
                   13113:     'Maps' => 'array');
                   13114: 
                   13115: Returns: both routines return nothing
                   13116: 
1.631     raeburn  13117: =back
                   13118: 
1.153     matthew  13119: =cut
                   13120: 
                   13121: #######################################################
                   13122: #######################################################
                   13123: sub store_course_settings {
1.496     albertel 13124:     return &store_settings($env{'request.course.id'},@_);
                   13125: }
                   13126: 
                   13127: sub store_settings {
1.153     matthew  13128:     # save to the environment
                   13129:     # appenv the same items, just to be safe
1.300     albertel 13130:     my $udom  = $env{'user.domain'};
                   13131:     my $uname = $env{'user.name'};
1.496     albertel 13132:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13133:     my %SaveHash;
                   13134:     my %AppHash;
                   13135:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13136:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13137:         my $envname = 'environment.'.$basename;
1.258     albertel 13138:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13139:             # Save this value away
                   13140:             if ($type eq 'scalar' &&
1.258     albertel 13141:                 (! exists($env{$envname}) || 
                   13142:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13143:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13144:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13145:             } elsif ($type eq 'array') {
                   13146:                 my $stored_form;
1.258     albertel 13147:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13148:                     $stored_form = join(',',
                   13149:                                         map {
1.369     www      13150:                                             &escape($_);
1.258     albertel 13151:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13152:                 } else {
                   13153:                     $stored_form = 
1.369     www      13154:                         &escape($env{'form.'.$setting});
1.153     matthew  13155:                 }
                   13156:                 # Determine if the array contents are the same.
1.258     albertel 13157:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13158:                     $SaveHash{$basename} = $stored_form;
                   13159:                     $AppHash{$envname}   = $stored_form;
                   13160:                 }
                   13161:             }
                   13162:         }
                   13163:     }
                   13164:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13165:                                           $udom,$uname);
1.153     matthew  13166:     if ($put_result !~ /^(ok|delayed)/) {
                   13167:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13168:                                  'got error:'.$put_result);
                   13169:     }
                   13170:     # Make sure these settings stick around in this session, too
1.646     raeburn  13171:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13172:     return;
                   13173: }
                   13174: 
                   13175: sub restore_course_settings {
1.499     albertel 13176:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13177: }
                   13178: 
                   13179: sub restore_settings {
                   13180:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13181:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13182:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13183:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13184:             '.'.$setting;
1.258     albertel 13185:         if (exists($env{$envname})) {
1.153     matthew  13186:             if ($type eq 'scalar') {
1.258     albertel 13187:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13188:             } elsif ($type eq 'array') {
1.258     albertel 13189:                 $env{'form.'.$setting} = [ 
1.153     matthew  13190:                                            map { 
1.369     www      13191:                                                &unescape($_); 
1.258     albertel 13192:                                            } split(',',$env{$envname})
1.153     matthew  13193:                                            ];
                   13194:             }
                   13195:         }
                   13196:     }
1.127     matthew  13197: }
                   13198: 
1.618     raeburn  13199: #######################################################
                   13200: #######################################################
                   13201: 
                   13202: =pod
                   13203: 
                   13204: =head1 Domain E-mail Routines  
                   13205: 
                   13206: =over 4
                   13207: 
1.648     raeburn  13208: =item * &build_recipient_list()
1.618     raeburn  13209: 
1.1075.2.44  raeburn  13210: Build recipient lists for following types of e-mail:
1.766     raeburn  13211: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13212: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13213: module change checking, student/employee ID conflict checks, as
                   13214: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13215: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13216: 
                   13217: Inputs:
1.1075.2.44  raeburn  13218: defmail (scalar - email address of default recipient),
                   13219: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13220: requestsmail, updatesmail, or idconflictsmail).
                   13221: 
1.619     raeburn  13222: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13223: 
                   13224: origmail (scalar - email address of recipient from loncapa.conf,
                   13225: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13226: 
1.655     raeburn  13227: Returns: comma separated list of addresses to which to send e-mail.
                   13228: 
                   13229: =back
1.618     raeburn  13230: 
                   13231: =cut
                   13232: 
                   13233: ############################################################
                   13234: ############################################################
                   13235: sub build_recipient_list {
1.619     raeburn  13236:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13237:     my @recipients;
                   13238:     my $otheremails;
                   13239:     my %domconfig =
                   13240:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13241:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13242:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13243:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13244:                 my @contacts = ('adminemail','supportemail');
                   13245:                 foreach my $item (@contacts) {
                   13246:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13247:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13248:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13249:                             push(@recipients,$addr);
                   13250:                         }
1.619     raeburn  13251:                     }
1.766     raeburn  13252:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13253:                 }
                   13254:             }
1.766     raeburn  13255:         } elsif ($origmail ne '') {
                   13256:             push(@recipients,$origmail);
1.618     raeburn  13257:         }
1.619     raeburn  13258:     } elsif ($origmail ne '') {
                   13259:         push(@recipients,$origmail);
1.618     raeburn  13260:     }
1.688     raeburn  13261:     if (defined($defmail)) {
                   13262:         if ($defmail ne '') {
                   13263:             push(@recipients,$defmail);
                   13264:         }
1.618     raeburn  13265:     }
                   13266:     if ($otheremails) {
1.619     raeburn  13267:         my @others;
                   13268:         if ($otheremails =~ /,/) {
                   13269:             @others = split(/,/,$otheremails);
1.618     raeburn  13270:         } else {
1.619     raeburn  13271:             push(@others,$otheremails);
                   13272:         }
                   13273:         foreach my $addr (@others) {
                   13274:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13275:                 push(@recipients,$addr);
                   13276:             }
1.618     raeburn  13277:         }
                   13278:     }
1.619     raeburn  13279:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13280:     return $recipientlist;
                   13281: }
                   13282: 
1.127     matthew  13283: ############################################################
                   13284: ############################################################
1.154     albertel 13285: 
1.655     raeburn  13286: =pod
                   13287: 
                   13288: =head1 Course Catalog Routines
                   13289: 
                   13290: =over 4
                   13291: 
                   13292: =item * &gather_categories()
                   13293: 
                   13294: Converts category definitions - keys of categories hash stored in  
                   13295: coursecategories in configuration.db on the primary library server in a 
                   13296: domain - to an array.  Also generates javascript and idx hash used to 
                   13297: generate Domain Coordinator interface for editing Course Categories.
                   13298: 
                   13299: Inputs:
1.663     raeburn  13300: 
1.655     raeburn  13301: categories (reference to hash of category definitions).
1.663     raeburn  13302: 
1.655     raeburn  13303: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13304:       categories and subcategories).
1.663     raeburn  13305: 
1.655     raeburn  13306: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13307:       editing Course Categories).
1.663     raeburn  13308: 
1.655     raeburn  13309: jsarray (reference to array of categories used to create Javascript arrays for
                   13310:          Domain Coordinator interface for editing Course Categories).
                   13311: 
                   13312: Returns: nothing
                   13313: 
                   13314: Side effects: populates cats, idx and jsarray. 
                   13315: 
                   13316: =cut
                   13317: 
                   13318: sub gather_categories {
                   13319:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13320:     my %counters;
                   13321:     my $num = 0;
                   13322:     foreach my $item (keys(%{$categories})) {
                   13323:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13324:         if ($container eq '' && $depth == 0) {
                   13325:             $cats->[$depth][$categories->{$item}] = $cat;
                   13326:         } else {
                   13327:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13328:         }
                   13329:         my ($escitem,$tail) = split(/:/,$item,2);
                   13330:         if ($counters{$tail} eq '') {
                   13331:             $counters{$tail} = $num;
                   13332:             $num ++;
                   13333:         }
                   13334:         if (ref($idx) eq 'HASH') {
                   13335:             $idx->{$item} = $counters{$tail};
                   13336:         }
                   13337:         if (ref($jsarray) eq 'ARRAY') {
                   13338:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13339:         }
                   13340:     }
                   13341:     return;
                   13342: }
                   13343: 
                   13344: =pod
                   13345: 
                   13346: =item * &extract_categories()
                   13347: 
                   13348: Used to generate breadcrumb trails for course categories.
                   13349: 
                   13350: Inputs:
1.663     raeburn  13351: 
1.655     raeburn  13352: categories (reference to hash of category definitions).
1.663     raeburn  13353: 
1.655     raeburn  13354: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13355:       categories and subcategories).
1.663     raeburn  13356: 
1.655     raeburn  13357: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13358: 
1.655     raeburn  13359: allitems (reference to hash - key is category key 
                   13360:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13361: 
1.655     raeburn  13362: idx (reference to hash of counters used in Domain Coordinator interface for
                   13363:       editing Course Categories).
1.663     raeburn  13364: 
1.655     raeburn  13365: jsarray (reference to array of categories used to create Javascript arrays for
                   13366:          Domain Coordinator interface for editing Course Categories).
                   13367: 
1.665     raeburn  13368: subcats (reference to hash of arrays containing all subcategories within each 
                   13369:          category, -recursive)
                   13370: 
1.655     raeburn  13371: Returns: nothing
                   13372: 
                   13373: Side effects: populates trails and allitems hash references.
                   13374: 
                   13375: =cut
                   13376: 
                   13377: sub extract_categories {
1.665     raeburn  13378:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13379:     if (ref($categories) eq 'HASH') {
                   13380:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13381:         if (ref($cats->[0]) eq 'ARRAY') {
                   13382:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13383:                 my $name = $cats->[0][$i];
                   13384:                 my $item = &escape($name).'::0';
                   13385:                 my $trailstr;
                   13386:                 if ($name eq 'instcode') {
                   13387:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13388:                 } elsif ($name eq 'communities') {
                   13389:                     $trailstr = &mt('Communities');
1.655     raeburn  13390:                 } else {
                   13391:                     $trailstr = $name;
                   13392:                 }
                   13393:                 if ($allitems->{$item} eq '') {
                   13394:                     push(@{$trails},$trailstr);
                   13395:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13396:                 }
                   13397:                 my @parents = ($name);
                   13398:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13399:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13400:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13401:                         if (ref($subcats) eq 'HASH') {
                   13402:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13403:                         }
                   13404:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13405:                     }
                   13406:                 } else {
                   13407:                     if (ref($subcats) eq 'HASH') {
                   13408:                         $subcats->{$item} = [];
1.655     raeburn  13409:                     }
                   13410:                 }
                   13411:             }
                   13412:         }
                   13413:     }
                   13414:     return;
                   13415: }
                   13416: 
                   13417: =pod
                   13418: 
1.1075.2.56  raeburn  13419: =item * &recurse_categories()
1.655     raeburn  13420: 
                   13421: Recursively used to generate breadcrumb trails for course categories.
                   13422: 
                   13423: Inputs:
1.663     raeburn  13424: 
1.655     raeburn  13425: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13426:       categories and subcategories).
1.663     raeburn  13427: 
1.655     raeburn  13428: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13429: 
                   13430: category (current course category, for which breadcrumb trail is being generated).
                   13431: 
                   13432: trails (reference to array of breadcrumb trails for each category).
                   13433: 
1.655     raeburn  13434: allitems (reference to hash - key is category key
                   13435:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13436: 
1.655     raeburn  13437: parents (array containing containers directories for current category, 
                   13438:          back to top level). 
                   13439: 
                   13440: Returns: nothing
                   13441: 
                   13442: Side effects: populates trails and allitems hash references
                   13443: 
                   13444: =cut
                   13445: 
                   13446: sub recurse_categories {
1.665     raeburn  13447:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13448:     my $shallower = $depth - 1;
                   13449:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13450:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13451:             my $name = $cats->[$depth]{$category}[$k];
                   13452:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13453:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13454:             if ($allitems->{$item} eq '') {
                   13455:                 push(@{$trails},$trailstr);
                   13456:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13457:             }
                   13458:             my $deeper = $depth+1;
                   13459:             push(@{$parents},$category);
1.665     raeburn  13460:             if (ref($subcats) eq 'HASH') {
                   13461:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13462:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13463:                     my $higher;
                   13464:                     if ($j > 0) {
                   13465:                         $higher = &escape($parents->[$j]).':'.
                   13466:                                   &escape($parents->[$j-1]).':'.$j;
                   13467:                     } else {
                   13468:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13469:                     }
                   13470:                     push(@{$subcats->{$higher}},$subcat);
                   13471:                 }
                   13472:             }
                   13473:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13474:                                 $subcats);
1.655     raeburn  13475:             pop(@{$parents});
                   13476:         }
                   13477:     } else {
                   13478:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13479:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13480:         if ($allitems->{$item} eq '') {
                   13481:             push(@{$trails},$trailstr);
                   13482:             $allitems->{$item} = scalar(@{$trails})-1;
                   13483:         }
                   13484:     }
                   13485:     return;
                   13486: }
                   13487: 
1.663     raeburn  13488: =pod
                   13489: 
1.1075.2.56  raeburn  13490: =item * &assign_categories_table()
1.663     raeburn  13491: 
                   13492: Create a datatable for display of hierarchical categories in a domain,
                   13493: with checkboxes to allow a course to be categorized. 
                   13494: 
                   13495: Inputs:
                   13496: 
                   13497: cathash - reference to hash of categories defined for the domain (from
                   13498:           configuration.db)
                   13499: 
                   13500: currcat - scalar with an & separated list of categories assigned to a course. 
                   13501: 
1.919     raeburn  13502: type    - scalar contains course type (Course or Community).
                   13503: 
1.663     raeburn  13504: Returns: $output (markup to be displayed) 
                   13505: 
                   13506: =cut
                   13507: 
                   13508: sub assign_categories_table {
1.919     raeburn  13509:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13510:     my $output;
                   13511:     if (ref($cathash) eq 'HASH') {
                   13512:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13513:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13514:         $maxdepth = scalar(@cats);
                   13515:         if (@cats > 0) {
                   13516:             my $itemcount = 0;
                   13517:             if (ref($cats[0]) eq 'ARRAY') {
                   13518:                 my @currcategories;
                   13519:                 if ($currcat ne '') {
                   13520:                     @currcategories = split('&',$currcat);
                   13521:                 }
1.919     raeburn  13522:                 my $table;
1.663     raeburn  13523:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13524:                     my $parent = $cats[0][$i];
1.919     raeburn  13525:                     next if ($parent eq 'instcode');
                   13526:                     if ($type eq 'Community') {
                   13527:                         next unless ($parent eq 'communities');
                   13528:                     } else {
                   13529:                         next if ($parent eq 'communities');
                   13530:                     }
1.663     raeburn  13531:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13532:                     my $item = &escape($parent).'::0';
                   13533:                     my $checked = '';
                   13534:                     if (@currcategories > 0) {
                   13535:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13536:                             $checked = ' checked="checked"';
1.663     raeburn  13537:                         }
                   13538:                     }
1.919     raeburn  13539:                     my $parent_title = $parent;
                   13540:                     if ($parent eq 'communities') {
                   13541:                         $parent_title = &mt('Communities');
                   13542:                     }
                   13543:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13544:                               '<input type="checkbox" name="usecategory" value="'.
                   13545:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13546:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13547:                     my $depth = 1;
                   13548:                     push(@path,$parent);
1.919     raeburn  13549:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13550:                     pop(@path);
1.919     raeburn  13551:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13552:                     $itemcount ++;
                   13553:                 }
1.919     raeburn  13554:                 if ($itemcount) {
                   13555:                     $output = &Apache::loncommon::start_data_table().
                   13556:                               $table.
                   13557:                               &Apache::loncommon::end_data_table();
                   13558:                 }
1.663     raeburn  13559:             }
                   13560:         }
                   13561:     }
                   13562:     return $output;
                   13563: }
                   13564: 
                   13565: =pod
                   13566: 
1.1075.2.56  raeburn  13567: =item * &assign_category_rows()
1.663     raeburn  13568: 
                   13569: Create a datatable row for display of nested categories in a domain,
                   13570: with checkboxes to allow a course to be categorized,called recursively.
                   13571: 
                   13572: Inputs:
                   13573: 
                   13574: itemcount - track row number for alternating colors
                   13575: 
                   13576: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13577:       categories and subcategories.
                   13578: 
                   13579: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13580: 
                   13581: parent - parent of current category item
                   13582: 
                   13583: path - Array containing all categories back up through the hierarchy from the
                   13584:        current category to the top level.
                   13585: 
                   13586: currcategories - reference to array of current categories assigned to the course
                   13587: 
                   13588: Returns: $output (markup to be displayed).
                   13589: 
                   13590: =cut
                   13591: 
                   13592: sub assign_category_rows {
                   13593:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13594:     my ($text,$name,$item,$chgstr);
                   13595:     if (ref($cats) eq 'ARRAY') {
                   13596:         my $maxdepth = scalar(@{$cats});
                   13597:         if (ref($cats->[$depth]) eq 'HASH') {
                   13598:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13599:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13600:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  13601:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13602:                 for (my $j=0; $j<$numchildren; $j++) {
                   13603:                     $name = $cats->[$depth]{$parent}[$j];
                   13604:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13605:                     my $deeper = $depth+1;
                   13606:                     my $checked = '';
                   13607:                     if (ref($currcategories) eq 'ARRAY') {
                   13608:                         if (@{$currcategories} > 0) {
                   13609:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13610:                                 $checked = ' checked="checked"';
1.663     raeburn  13611:                             }
                   13612:                         }
                   13613:                     }
1.664     raeburn  13614:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13615:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13616:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13617:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13618:                              '</td><td>';
1.663     raeburn  13619:                     if (ref($path) eq 'ARRAY') {
                   13620:                         push(@{$path},$name);
                   13621:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13622:                         pop(@{$path});
                   13623:                     }
                   13624:                     $text .= '</td></tr>';
                   13625:                 }
                   13626:                 $text .= '</table></td>';
                   13627:             }
                   13628:         }
                   13629:     }
                   13630:     return $text;
                   13631: }
                   13632: 
1.655     raeburn  13633: ############################################################
                   13634: ############################################################
                   13635: 
                   13636: 
1.443     albertel 13637: sub commit_customrole {
1.664     raeburn  13638:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13639:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13640:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13641:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13642:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13643:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13644:                  '</b><br />';
                   13645:     return $output;
                   13646: }
                   13647: 
                   13648: sub commit_standardrole {
1.1075.2.31  raeburn  13649:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13650:     my ($output,$logmsg,$linefeed);
                   13651:     if ($context eq 'auto') {
                   13652:         $linefeed = "\n";
                   13653:     } else {
                   13654:         $linefeed = "<br />\n";
                   13655:     }  
1.443     albertel 13656:     if ($three eq 'st') {
1.541     raeburn  13657:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  13658:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13659:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13660:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13661:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13662:         } else {
1.541     raeburn  13663:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13664:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13665:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13666:             if ($context eq 'auto') {
                   13667:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13668:             } else {
                   13669:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13670:                &mt('Add to classlist').': <b>ok</b>';
                   13671:             }
                   13672:             $output .= $linefeed;
1.443     albertel 13673:         }
                   13674:     } else {
                   13675:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13676:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13677:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13678:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13679:         if ($context eq 'auto') {
                   13680:             $output .= $result.$linefeed;
                   13681:         } else {
                   13682:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13683:         }
1.443     albertel 13684:     }
                   13685:     return $output;
                   13686: }
                   13687: 
                   13688: sub commit_studentrole {
1.1075.2.31  raeburn  13689:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13690:         $credits) = @_;
1.626     raeburn  13691:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13692:     if ($context eq 'auto') {
                   13693:         $linefeed = "\n";
                   13694:     } else {
                   13695:         $linefeed = '<br />'."\n";
                   13696:     }
1.443     albertel 13697:     if (defined($one) && defined($two)) {
                   13698:         my $cid=$one.'_'.$two;
                   13699:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13700:         my $secchange = 0;
                   13701:         my $expire_role_result;
                   13702:         my $modify_section_result;
1.628     raeburn  13703:         if ($oldsec ne '-1') { 
                   13704:             if ($oldsec ne $sec) {
1.443     albertel 13705:                 $secchange = 1;
1.628     raeburn  13706:                 my $now = time;
1.443     albertel 13707:                 my $uurl='/'.$cid;
                   13708:                 $uurl=~s/\_/\//g;
                   13709:                 if ($oldsec) {
                   13710:                     $uurl.='/'.$oldsec;
                   13711:                 }
1.626     raeburn  13712:                 $oldsecurl = $uurl;
1.628     raeburn  13713:                 $expire_role_result = 
1.652     raeburn  13714:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13715:                 if ($env{'request.course.sec'} ne '') { 
                   13716:                     if ($expire_role_result eq 'refused') {
                   13717:                         my @roles = ('st');
                   13718:                         my @statuses = ('previous');
                   13719:                         my @roledoms = ($one);
                   13720:                         my $withsec = 1;
                   13721:                         my %roleshash = 
                   13722:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13723:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13724:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13725:                             my ($oldstart,$oldend) = 
                   13726:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13727:                             if ($oldend > 0 && $oldend <= $now) {
                   13728:                                 $expire_role_result = 'ok';
                   13729:                             }
                   13730:                         }
                   13731:                     }
                   13732:                 }
1.443     albertel 13733:                 $result = $expire_role_result;
                   13734:             }
                   13735:         }
                   13736:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  13737:             $modify_section_result = 
                   13738:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13739:                                                            undef,undef,undef,$sec,
                   13740:                                                            $end,$start,'','',$cid,
                   13741:                                                            '',$context,$credits);
1.443     albertel 13742:             if ($modify_section_result =~ /^ok/) {
                   13743:                 if ($secchange == 1) {
1.628     raeburn  13744:                     if ($sec eq '') {
                   13745:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13746:                     } else {
                   13747:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13748:                     }
1.443     albertel 13749:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13750:                     if ($sec eq '') {
                   13751:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13752:                     } else {
                   13753:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13754:                     }
1.443     albertel 13755:                 } else {
1.628     raeburn  13756:                     if ($sec eq '') {
                   13757:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13758:                     } else {
                   13759:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13760:                     }
1.443     albertel 13761:                 }
                   13762:             } else {
1.628     raeburn  13763:                 if ($secchange) {       
                   13764:                     $$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;
                   13765:                 } else {
                   13766:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13767:                 }
1.443     albertel 13768:             }
                   13769:             $result = $modify_section_result;
                   13770:         } elsif ($secchange == 1) {
1.628     raeburn  13771:             if ($oldsec eq '') {
1.1075.2.20  raeburn  13772:                 $$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  13773:             } else {
                   13774:                 $$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;
                   13775:             }
1.626     raeburn  13776:             if ($expire_role_result eq 'refused') {
                   13777:                 my $newsecurl = '/'.$cid;
                   13778:                 $newsecurl =~ s/\_/\//g;
                   13779:                 if ($sec ne '') {
                   13780:                     $newsecurl.='/'.$sec;
                   13781:                 }
                   13782:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13783:                     if ($sec eq '') {
                   13784:                         $$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;
                   13785:                     } else {
                   13786:                         $$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;
                   13787:                     }
                   13788:                 }
                   13789:             }
1.443     albertel 13790:         }
                   13791:     } else {
1.626     raeburn  13792:         $$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 13793:         $result = "error: incomplete course id\n";
                   13794:     }
                   13795:     return $result;
                   13796: }
                   13797: 
1.1075.2.25  raeburn  13798: sub show_role_extent {
                   13799:     my ($scope,$context,$role) = @_;
                   13800:     $scope =~ s{^/}{};
                   13801:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13802:     push(@courseroles,'co');
                   13803:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13804:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13805:         $scope =~ s{/}{_};
                   13806:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13807:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13808:         my ($audom,$auname) = split(/\//,$scope);
                   13809:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13810:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13811:     } else {
                   13812:         $scope =~ s{/$}{};
                   13813:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13814:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13815:     }
                   13816: }
                   13817: 
1.443     albertel 13818: ############################################################
                   13819: ############################################################
                   13820: 
1.566     albertel 13821: sub check_clone {
1.578     raeburn  13822:     my ($args,$linefeed) = @_;
1.566     albertel 13823:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13824:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13825:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13826:     my $clonemsg;
                   13827:     my $can_clone = 0;
1.944     raeburn  13828:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13829:     if ($lctype ne 'community') {
                   13830:         $lctype = 'course';
                   13831:     }
1.566     albertel 13832:     if ($clonehome eq 'no_host') {
1.944     raeburn  13833:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13834:             $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'});
                   13835:         } else {
                   13836:             $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'});
                   13837:         }     
1.566     albertel 13838:     } else {
                   13839: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13840:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13841:             if ($clonedesc{'type'} ne 'Community') {
                   13842:                  $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'});
                   13843:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13844:             }
                   13845:         }
1.882     raeburn  13846: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13847:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13848: 	    $can_clone = 1;
                   13849: 	} else {
                   13850: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13851: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13852: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13853:             if (grep(/^\*$/,@cloners)) {
                   13854:                 $can_clone = 1;
                   13855:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13856:                 $can_clone = 1;
                   13857:             } else {
1.908     raeburn  13858:                 my $ccrole = 'cc';
1.944     raeburn  13859:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13860:                     $ccrole = 'co';
                   13861:                 }
1.578     raeburn  13862: 	        my %roleshash =
                   13863: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13864: 					 $args->{'ccdomain'},
1.908     raeburn  13865:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13866: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13867: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13868:                     $can_clone = 1;
                   13869:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13870:                     $can_clone = 1;
                   13871:                 } else {
1.944     raeburn  13872:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13873:                         $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'});
                   13874:                     } else {
                   13875:                         $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'});
                   13876:                     }
1.578     raeburn  13877: 	        }
1.566     albertel 13878: 	    }
1.578     raeburn  13879:         }
1.566     albertel 13880:     }
                   13881:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13882: }
                   13883: 
1.444     albertel 13884: sub construct_course {
1.1075.2.59  raeburn  13885:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 13886:     my $outcome;
1.541     raeburn  13887:     my $linefeed =  '<br />'."\n";
                   13888:     if ($context eq 'auto') {
                   13889:         $linefeed = "\n";
                   13890:     }
1.566     albertel 13891: 
                   13892: #
                   13893: # Are we cloning?
                   13894: #
                   13895:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13896:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13897: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13898: 	if ($context ne 'auto') {
1.578     raeburn  13899:             if ($clonemsg ne '') {
                   13900: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13901:             }
1.566     albertel 13902: 	}
                   13903: 	$outcome .= $clonemsg.$linefeed;
                   13904: 
                   13905:         if (!$can_clone) {
                   13906: 	    return (0,$outcome);
                   13907: 	}
                   13908:     }
                   13909: 
1.444     albertel 13910: #
                   13911: # Open course
                   13912: #
                   13913:     my $crstype = lc($args->{'crstype'});
                   13914:     my %cenv=();
                   13915:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13916:                                              $args->{'cdescr'},
                   13917:                                              $args->{'curl'},
                   13918:                                              $args->{'course_home'},
                   13919:                                              $args->{'nonstandard'},
                   13920:                                              $args->{'crscode'},
                   13921:                                              $args->{'ccuname'}.':'.
                   13922:                                              $args->{'ccdomain'},
1.882     raeburn  13923:                                              $args->{'crstype'},
1.885     raeburn  13924:                                              $cnum,$context,$category);
1.444     albertel 13925: 
                   13926:     # Note: The testing routines depend on this being output; see 
                   13927:     # Utils::Course. This needs to at least be output as a comment
                   13928:     # if anyone ever decides to not show this, and Utils::Course::new
                   13929:     # will need to be suitably modified.
1.541     raeburn  13930:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13931:     if ($$courseid =~ /^error:/) {
                   13932:         return (0,$outcome);
                   13933:     }
                   13934: 
1.444     albertel 13935: #
                   13936: # Check if created correctly
                   13937: #
1.479     albertel 13938:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13939:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13940:     if ($crsuhome eq 'no_host') {
                   13941:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13942:         return (0,$outcome);
                   13943:     }
1.541     raeburn  13944:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13945: 
1.444     albertel 13946: #
1.566     albertel 13947: # Do the cloning
                   13948: #   
                   13949:     if ($can_clone && $cloneid) {
                   13950: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13951: 	if ($context ne 'auto') {
                   13952: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13953: 	}
                   13954: 	$outcome .= $clonemsg.$linefeed;
                   13955: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13956: # Copy all files
1.637     www      13957: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13958: # Restore URL
1.566     albertel 13959: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13960: # Restore title
1.566     albertel 13961: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13962: # Restore creation date, creator and creation context.
                   13963:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13964:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13965:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13966: # Mark as cloned
1.566     albertel 13967: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13968: # Need to clone grading mode
                   13969:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13970:         $cenv{'grading'}=$newenv{'grading'};
                   13971: # Do not clone these environment entries
                   13972:         &Apache::lonnet::del('environment',
                   13973:                   ['default_enrollment_start_date',
                   13974:                    'default_enrollment_end_date',
                   13975:                    'question.email',
                   13976:                    'policy.email',
                   13977:                    'comment.email',
                   13978:                    'pch.users.denied',
1.725     raeburn  13979:                    'plc.users.denied',
                   13980:                    'hidefromcat',
1.1075.2.36  raeburn  13981:                    'checkforpriv',
1.1075.2.59  raeburn  13982:                    'categories',
                   13983:                    'internal.uniquecode'],
1.638     www      13984:                    $$crsudom,$$crsunum);
1.444     albertel 13985:     }
1.566     albertel 13986: 
1.444     albertel 13987: #
                   13988: # Set environment (will override cloned, if existing)
                   13989: #
                   13990:     my @sections = ();
                   13991:     my @xlists = ();
                   13992:     if ($args->{'crstype'}) {
                   13993:         $cenv{'type'}=$args->{'crstype'};
                   13994:     }
                   13995:     if ($args->{'crsid'}) {
                   13996:         $cenv{'courseid'}=$args->{'crsid'};
                   13997:     }
                   13998:     if ($args->{'crscode'}) {
                   13999:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14000:     }
                   14001:     if ($args->{'crsquota'} ne '') {
                   14002:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14003:     } else {
                   14004:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14005:     }
                   14006:     if ($args->{'ccuname'}) {
                   14007:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14008:                                         ':'.$args->{'ccdomain'};
                   14009:     } else {
                   14010:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14011:     }
1.1075.2.31  raeburn  14012:     if ($args->{'defaultcredits'}) {
                   14013:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14014:     }
1.444     albertel 14015:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14016:     if ($args->{'crssections'}) {
                   14017:         $cenv{'internal.sectionnums'} = '';
                   14018:         if ($args->{'crssections'} =~ m/,/) {
                   14019:             @sections = split/,/,$args->{'crssections'};
                   14020:         } else {
                   14021:             $sections[0] = $args->{'crssections'};
                   14022:         }
                   14023:         if (@sections > 0) {
                   14024:             foreach my $item (@sections) {
                   14025:                 my ($sec,$gp) = split/:/,$item;
                   14026:                 my $class = $args->{'crscode'}.$sec;
                   14027:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14028:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14029:                 unless ($addcheck eq 'ok') {
                   14030:                     push @badclasses, $class;
                   14031:                 }
                   14032:             }
                   14033:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14034:         }
                   14035:     }
                   14036: # do not hide course coordinator from staff listing, 
                   14037: # even if privileged
                   14038:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14039: # add course coordinator's domain to domains to check for privileged users
                   14040: # if different to course domain
                   14041:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14042:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14043:     }
1.444     albertel 14044: # add crosslistings
                   14045:     if ($args->{'crsxlist'}) {
                   14046:         $cenv{'internal.crosslistings'}='';
                   14047:         if ($args->{'crsxlist'} =~ m/,/) {
                   14048:             @xlists = split/,/,$args->{'crsxlist'};
                   14049:         } else {
                   14050:             $xlists[0] = $args->{'crsxlist'};
                   14051:         }
                   14052:         if (@xlists > 0) {
                   14053:             foreach my $item (@xlists) {
                   14054:                 my ($xl,$gp) = split/:/,$item;
                   14055:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14056:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14057:                 unless ($addcheck eq 'ok') {
                   14058:                     push @badclasses, $xl;
                   14059:                 }
                   14060:             }
                   14061:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14062:         }
                   14063:     }
                   14064:     if ($args->{'autoadds'}) {
                   14065:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14066:     }
                   14067:     if ($args->{'autodrops'}) {
                   14068:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14069:     }
                   14070: # check for notification of enrollment changes
                   14071:     my @notified = ();
                   14072:     if ($args->{'notify_owner'}) {
                   14073:         if ($args->{'ccuname'} ne '') {
                   14074:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14075:         }
                   14076:     }
                   14077:     if ($args->{'notify_dc'}) {
                   14078:         if ($uname ne '') { 
1.630     raeburn  14079:             push(@notified,$uname.':'.$udom);
1.444     albertel 14080:         }
                   14081:     }
                   14082:     if (@notified > 0) {
                   14083:         my $notifylist;
                   14084:         if (@notified > 1) {
                   14085:             $notifylist = join(',',@notified);
                   14086:         } else {
                   14087:             $notifylist = $notified[0];
                   14088:         }
                   14089:         $cenv{'internal.notifylist'} = $notifylist;
                   14090:     }
                   14091:     if (@badclasses > 0) {
                   14092:         my %lt=&Apache::lonlocal::texthash(
                   14093:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   14094:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14095:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14096:         );
1.541     raeburn  14097:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14098:                            ' ('.$lt{'adby'}.')';
                   14099:         if ($context eq 'auto') {
                   14100:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14101:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14102:             foreach my $item (@badclasses) {
                   14103:                 if ($context eq 'auto') {
                   14104:                     $outcome .= " - $item\n";
                   14105:                 } else {
                   14106:                     $outcome .= "<li>$item</li>\n";
                   14107:                 }
                   14108:             }
                   14109:             if ($context eq 'auto') {
                   14110:                 $outcome .= $linefeed;
                   14111:             } else {
1.566     albertel 14112:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14113:             }
                   14114:         } 
1.444     albertel 14115:     }
                   14116:     if ($args->{'no_end_date'}) {
                   14117:         $args->{'endaccess'} = 0;
                   14118:     }
                   14119:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14120:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14121:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14122:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14123:     if ($args->{'showphotos'}) {
                   14124:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14125:     }
                   14126:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14127:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14128:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14129:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14130:             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'); 
                   14131:             if ($context eq 'auto') {
                   14132:                 $outcome .= $krb_msg;
                   14133:             } else {
1.566     albertel 14134:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14135:             }
                   14136:             $outcome .= $linefeed;
1.444     albertel 14137:         }
                   14138:     }
                   14139:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14140:        if ($args->{'setpolicy'}) {
                   14141:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14142:        }
                   14143:        if ($args->{'setcontent'}) {
                   14144:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14145:        }
                   14146:     }
                   14147:     if ($args->{'reshome'}) {
                   14148: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14149: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14150:     }
                   14151: #
                   14152: # course has keyed access
                   14153: #
                   14154:     if ($args->{'setkeys'}) {
                   14155:        $cenv{'keyaccess'}='yes';
                   14156:     }
                   14157: # if specified, key authority is not course, but user
                   14158: # only active if keyaccess is yes
                   14159:     if ($args->{'keyauth'}) {
1.487     albertel 14160: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14161: 	$user = &LONCAPA::clean_username($user);
                   14162: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14163: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14164: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14165: 	}
                   14166:     }
                   14167: 
1.1075.2.59  raeburn  14168: #
                   14169: #  generate and store uniquecode (available to course requester), if course should have one.
                   14170: #
                   14171:     if ($args->{'uniquecode'}) {
                   14172:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14173:         if ($code) {
                   14174:             $cenv{'internal.uniquecode'} = $code;
                   14175:             my %crsinfo =
                   14176:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14177:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14178:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14179:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14180:             }
                   14181:             if (ref($coderef)) {
                   14182:                 $$coderef = $code;
                   14183:             }
                   14184:         }
                   14185:     }
                   14186: 
1.444     albertel 14187:     if ($args->{'disresdis'}) {
                   14188:         $cenv{'pch.roles.denied'}='st';
                   14189:     }
                   14190:     if ($args->{'disablechat'}) {
                   14191:         $cenv{'plc.roles.denied'}='st';
                   14192:     }
                   14193: 
                   14194:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14195:     # course
                   14196:     $cenv{'course.helper.not.run'} = 1;
                   14197:     #
                   14198:     # Use new Randomseed
                   14199:     #
                   14200:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14201:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14202:     #
                   14203:     # The encryption code and receipt prefix for this course
                   14204:     #
                   14205:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14206:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14207:     #
                   14208:     # By default, use standard grading
                   14209:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14210: 
1.541     raeburn  14211:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14212:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14213: #
                   14214: # Open all assignments
                   14215: #
                   14216:     if ($args->{'openall'}) {
                   14217:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14218:        my %storecontent = ($storeunder         => time,
                   14219:                            $storeunder.'.type' => 'date_start');
                   14220:        
                   14221:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14222:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14223:    }
                   14224: #
                   14225: # Set first page
                   14226: #
                   14227:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14228: 	    || ($cloneid)) {
1.445     albertel 14229: 	use LONCAPA::map;
1.444     albertel 14230: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14231: 
                   14232: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14233:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14234: 
1.444     albertel 14235:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14236:         my $title; my $url;
                   14237:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14238: 	    $title=&mt('Syllabus');
1.444     albertel 14239:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14240:         } else {
1.963     raeburn  14241:             $title=&mt('Table of Contents');
1.444     albertel 14242:             $url='/adm/navmaps';
                   14243:         }
1.445     albertel 14244: 
                   14245:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14246: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14247: 
                   14248: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14249:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14250:     }
1.566     albertel 14251: 
                   14252:     return (1,$outcome);
1.444     albertel 14253: }
                   14254: 
1.1075.2.59  raeburn  14255: sub make_unique_code {
                   14256:     my ($cdom,$cnum) = @_;
                   14257:     # get lock on uniquecodes db
                   14258:     my $lockhash = {
                   14259:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14260:                                                   ':'.$env{'user.domain'},
                   14261:                    };
                   14262:     my $tries = 0;
                   14263:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14264:     my ($code,$error);
                   14265: 
                   14266:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14267:         $tries ++;
                   14268:         sleep 1;
                   14269:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14270:     }
                   14271:     if ($gotlock eq 'ok') {
                   14272:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14273:         my $gotcode;
                   14274:         my $attempts = 0;
                   14275:         while ((!$gotcode) && ($attempts < 100)) {
                   14276:             $code = &generate_code();
                   14277:             if (!exists($currcodes{$code})) {
                   14278:                 $gotcode = 1;
                   14279:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14280:                     $error = 'nostore';
                   14281:                 }
                   14282:             }
                   14283:             $attempts ++;
                   14284:         }
                   14285:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14286:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14287:     } else {
                   14288:         $error = 'nolock';
                   14289:     }
                   14290:     return ($code,$error);
                   14291: }
                   14292: 
                   14293: sub generate_code {
                   14294:     my $code;
                   14295:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14296:     for (my $i=0; $i<6; $i++) {
                   14297:         my $lettnum = int (rand 2);
                   14298:         my $item = '';
                   14299:         if ($lettnum) {
                   14300:             $item = $letts[int( rand(18) )];
                   14301:         } else {
                   14302:             $item = 1+int( rand(8) );
                   14303:         }
                   14304:         $code .= $item;
                   14305:     }
                   14306:     return $code;
                   14307: }
                   14308: 
1.444     albertel 14309: ############################################################
                   14310: ############################################################
                   14311: 
1.953     droeschl 14312: #SD
                   14313: # only Community and Course, or anything else?
1.378     raeburn  14314: sub course_type {
                   14315:     my ($cid) = @_;
                   14316:     if (!defined($cid)) {
                   14317:         $cid = $env{'request.course.id'};
                   14318:     }
1.404     albertel 14319:     if (defined($env{'course.'.$cid.'.type'})) {
                   14320:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14321:     } else {
                   14322:         return 'Course';
1.377     raeburn  14323:     }
                   14324: }
1.156     albertel 14325: 
1.406     raeburn  14326: sub group_term {
                   14327:     my $crstype = &course_type();
                   14328:     my %names = (
                   14329:                   'Course' => 'group',
1.865     raeburn  14330:                   'Community' => 'group',
1.406     raeburn  14331:                 );
                   14332:     return $names{$crstype};
                   14333: }
                   14334: 
1.902     raeburn  14335: sub course_types {
1.1075.2.59  raeburn  14336:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14337:     my %typename = (
                   14338:                          official   => 'Official course',
                   14339:                          unofficial => 'Unofficial course',
                   14340:                          community  => 'Community',
1.1075.2.59  raeburn  14341:                          textbook   => 'Textbook course',
1.902     raeburn  14342:                    );
                   14343:     return (\@types,\%typename);
                   14344: }
                   14345: 
1.156     albertel 14346: sub icon {
                   14347:     my ($file)=@_;
1.505     albertel 14348:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14349:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14350:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14351:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14352: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14353: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14354: 	            $curfext.".gif") {
                   14355: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14356: 		$curfext.".gif";
                   14357: 	}
                   14358:     }
1.249     albertel 14359:     return &lonhttpdurl($iconname);
1.154     albertel 14360: } 
1.84      albertel 14361: 
1.575     albertel 14362: sub lonhttpdurl {
1.692     www      14363: #
                   14364: # Had been used for "small fry" static images on separate port 8080.
                   14365: # Modify here if lightweight http functionality desired again.
                   14366: # Currently eliminated due to increasing firewall issues.
                   14367: #
1.575     albertel 14368:     my ($url)=@_;
1.692     www      14369:     return $url;
1.215     albertel 14370: }
                   14371: 
1.213     albertel 14372: sub connection_aborted {
                   14373:     my ($r)=@_;
                   14374:     $r->print(" ");$r->rflush();
                   14375:     my $c = $r->connection;
                   14376:     return $c->aborted();
                   14377: }
                   14378: 
1.221     foxr     14379: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14380: #    strings as 'strings'.
                   14381: sub escape_single {
1.221     foxr     14382:     my ($input) = @_;
1.223     albertel 14383:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14384:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14385:     return $input;
                   14386: }
1.223     albertel 14387: 
1.222     foxr     14388: #  Same as escape_single, but escape's "'s  This 
                   14389: #  can be used for  "strings"
                   14390: sub escape_double {
                   14391:     my ($input) = @_;
                   14392:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14393:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14394:     return $input;
                   14395: }
1.223     albertel 14396:  
1.222     foxr     14397: #   Escapes the last element of a full URL.
                   14398: sub escape_url {
                   14399:     my ($url)   = @_;
1.238     raeburn  14400:     my @urlslices = split(/\//, $url,-1);
1.369     www      14401:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 14402:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     14403: }
1.462     albertel 14404: 
1.820     raeburn  14405: sub compare_arrays {
                   14406:     my ($arrayref1,$arrayref2) = @_;
                   14407:     my (@difference,%count);
                   14408:     @difference = ();
                   14409:     %count = ();
                   14410:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14411:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14412:         foreach my $element (keys(%count)) {
                   14413:             if ($count{$element} == 1) {
                   14414:                 push(@difference,$element);
                   14415:             }
                   14416:         }
                   14417:     }
                   14418:     return @difference;
                   14419: }
                   14420: 
1.817     bisitz   14421: # -------------------------------------------------------- Initialize user login
1.462     albertel 14422: sub init_user_environment {
1.463     albertel 14423:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14424:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14425: 
                   14426:     my $public=($username eq 'public' && $domain eq 'public');
                   14427: 
                   14428: # See if old ID present, if so, remove
                   14429: 
1.1062    raeburn  14430:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14431:     my $now=time;
                   14432: 
                   14433:     if ($public) {
                   14434: 	my $max_public=100;
                   14435: 	my $oldest;
                   14436: 	my $oldest_time=0;
                   14437: 	for(my $next=1;$next<=$max_public;$next++) {
                   14438: 	    if (-e $lonids."/publicuser_$next.id") {
                   14439: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14440: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14441: 		    $oldest_time=$mtime;
                   14442: 		    $oldest=$next;
                   14443: 		}
                   14444: 	    } else {
                   14445: 		$cookie="publicuser_$next";
                   14446: 		last;
                   14447: 	    }
                   14448: 	}
                   14449: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14450:     } else {
1.463     albertel 14451: 	# if this isn't a robot, kill any existing non-robot sessions
                   14452: 	if (!$args->{'robot'}) {
                   14453: 	    opendir(DIR,$lonids);
                   14454: 	    while ($filename=readdir(DIR)) {
                   14455: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14456: 		    unlink($lonids.'/'.$filename);
                   14457: 		}
1.462     albertel 14458: 	    }
1.463     albertel 14459: 	    closedir(DIR);
1.462     albertel 14460: 	}
                   14461: # Give them a new cookie
1.463     albertel 14462: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14463: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14464: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14465:     
                   14466: # Initialize roles
                   14467: 
1.1062    raeburn  14468: 	($userroles,$firstaccenv,$timerintenv) = 
                   14469:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14470:     }
                   14471: # ------------------------------------ Check browser type and MathML capability
                   14472: 
                   14473:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.42  raeburn  14474:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
1.462     albertel 14475: 
                   14476: # ------------------------------------------------------------- Get environment
                   14477: 
                   14478:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14479:     my ($tmp) = keys(%userenv);
                   14480:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14481:     } else {
                   14482: 	undef(%userenv);
                   14483:     }
                   14484:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14485: 	$form->{'interface'}=$userenv{'interface'};
                   14486:     }
                   14487:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14488: 
                   14489: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14490:     foreach my $option ('interface','localpath','localres') {
                   14491:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14492:     }
                   14493: # --------------------------------------------------------- Write first profile
                   14494: 
                   14495:     {
                   14496: 	my %initial_env = 
                   14497: 	    ("user.name"          => $username,
                   14498: 	     "user.domain"        => $domain,
                   14499: 	     "user.home"          => $authhost,
                   14500: 	     "browser.type"       => $clientbrowser,
                   14501: 	     "browser.version"    => $clientversion,
                   14502: 	     "browser.mathml"     => $clientmathml,
                   14503: 	     "browser.unicode"    => $clientunicode,
                   14504: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  14505:              "browser.mobile"     => $clientmobile,
                   14506:              "browser.info"       => $clientinfo,
1.462     albertel 14507: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14508: 	     "request.course.fn"  => '',
                   14509: 	     "request.course.uri" => '',
                   14510: 	     "request.course.sec" => '',
                   14511: 	     "request.role"       => 'cm',
                   14512: 	     "request.role.adv"   => $env{'user.adv'},
                   14513: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14514: 
                   14515:         if ($form->{'localpath'}) {
                   14516: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14517: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14518:         }
                   14519: 	
                   14520: 	if ($form->{'interface'}) {
                   14521: 	    $form->{'interface'}=~s/\W//gs;
                   14522: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14523: 	    $env{'browser.interface'}=$form->{'interface'};
                   14524: 	}
                   14525: 
1.1075.2.54  raeburn  14526:         if ($form->{'iptoken'}) {
                   14527:             my $lonhost = $r->dir_config('lonHostID');
                   14528:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14529:             $env{'user.noloadbalance'} = $lonhost;
                   14530:         }
                   14531: 
1.981     raeburn  14532:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14533:         my %domdef;
                   14534:         unless ($domain eq 'public') {
                   14535:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14536:         }
1.980     raeburn  14537: 
1.1075.2.7  raeburn  14538:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14539:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14540:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14541:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14542:         }
                   14543: 
1.1075.2.59  raeburn  14544:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14545:             $userenv{'canrequest.'.$crstype} =
                   14546:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14547:                                                   'reload','requestcourses',
                   14548:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14549:         }
                   14550: 
1.1075.2.14  raeburn  14551:         $userenv{'canrequest.author'} =
                   14552:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14553:                                         'reload','requestauthor',
                   14554:                                         \%userenv,\%domdef,\%is_adv);
                   14555:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14556:                                              $domain,$username);
                   14557:         my $reqstatus = $reqauthor{'author_status'};
                   14558:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14559:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14560:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14561:                                                   $reqauthor{'author'}{'timestamp'};
                   14562:             }
                   14563:         }
                   14564: 
1.462     albertel 14565: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14566: 
1.462     albertel 14567: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14568: 		 &GDBM_WRCREAT(),0640)) {
                   14569: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14570: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14571: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14572:             if (ref($firstaccenv) eq 'HASH') {
                   14573:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14574:             }
                   14575:             if (ref($timerintenv) eq 'HASH') {
                   14576:                 &_add_to_env(\%disk_env,$timerintenv);
                   14577:             }
1.463     albertel 14578: 	    if (ref($args->{'extra_env'})) {
                   14579: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14580: 	    }
1.462     albertel 14581: 	    untie(%disk_env);
                   14582: 	} else {
1.705     tempelho 14583: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14584: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14585: 	    return 'error: '.$!;
                   14586: 	}
                   14587:     }
                   14588:     $env{'request.role'}='cm';
                   14589:     $env{'request.role.adv'}=$env{'user.adv'};
                   14590:     $env{'browser.type'}=$clientbrowser;
                   14591: 
                   14592:     return $cookie;
                   14593: 
                   14594: }
                   14595: 
                   14596: sub _add_to_env {
                   14597:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14598:     if (ref($env_data) eq 'HASH') {
                   14599:         while (my ($key,$value) = each(%$env_data)) {
                   14600: 	    $idf->{$prefix.$key} = $value;
                   14601: 	    $env{$prefix.$key}   = $value;
                   14602:         }
1.462     albertel 14603:     }
                   14604: }
                   14605: 
1.685     tempelho 14606: # --- Get the symbolic name of a problem and the url
                   14607: sub get_symb {
                   14608:     my ($request,$silent) = @_;
1.726     raeburn  14609:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14610:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14611:     if ($symb eq '') {
                   14612:         if (!$silent) {
1.1071    raeburn  14613:             if (ref($request)) { 
                   14614:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14615:             }
1.685     tempelho 14616:             return ();
                   14617:         }
                   14618:     }
                   14619:     &Apache::lonenc::check_decrypt(\$symb);
                   14620:     return ($symb);
                   14621: }
                   14622: 
                   14623: # --------------------------------------------------------------Get annotation
                   14624: 
                   14625: sub get_annotation {
                   14626:     my ($symb,$enc) = @_;
                   14627: 
                   14628:     my $key = $symb;
                   14629:     if (!$enc) {
                   14630:         $key =
                   14631:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14632:     }
                   14633:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14634:     return $annotation{$key};
                   14635: }
                   14636: 
                   14637: sub clean_symb {
1.731     raeburn  14638:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14639: 
                   14640:     &Apache::lonenc::check_decrypt(\$symb);
                   14641:     my $enc = $env{'request.enc'};
1.731     raeburn  14642:     if ($delete_enc) {
1.730     raeburn  14643:         delete($env{'request.enc'});
                   14644:     }
1.685     tempelho 14645: 
                   14646:     return ($symb,$enc);
                   14647: }
1.462     albertel 14648: 
1.990     raeburn  14649: sub build_release_hashes {
                   14650:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14651:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14652:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14653:                   (ref($randomizetry) eq 'HASH'));
                   14654:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14655:         my ($item,$name,$value) = split(/:/,$key);
                   14656:         if ($item eq 'parameter') {
                   14657:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14658:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14659:                     push(@{$checkparms->{$name}},$value);
                   14660:                 }
                   14661:             } else {
                   14662:                 push(@{$checkparms->{$name}},$value);
                   14663:             }
                   14664:         } elsif ($item eq 'resourcetag') {
                   14665:             if ($name eq 'responsetype') {
                   14666:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14667:             }
                   14668:         } elsif ($item eq 'course') {
                   14669:             if ($name eq 'crstype') {
                   14670:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14671:             }
                   14672:         }
                   14673:     }
                   14674:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14675:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14676:     return;
                   14677: }
                   14678: 
1.1075.2.11  raeburn  14679: sub update_content_constraints {
                   14680:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14681:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14682:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14683:     my %checkresponsetypes;
                   14684:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14685:         my ($item,$name,$value) = split(/:/,$key);
                   14686:         if ($item eq 'resourcetag') {
                   14687:             if ($name eq 'responsetype') {
                   14688:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14689:             }
                   14690:         }
                   14691:     }
                   14692:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14693:     if (defined($navmap)) {
                   14694:         my %allresponses;
                   14695:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14696:             my %responses = $res->responseTypes();
                   14697:             foreach my $key (keys(%responses)) {
                   14698:                 next unless(exists($checkresponsetypes{$key}));
                   14699:                 $allresponses{$key} += $responses{$key};
                   14700:             }
                   14701:         }
                   14702:         foreach my $key (keys(%allresponses)) {
                   14703:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14704:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14705:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14706:             }
                   14707:         }
                   14708:         undef($navmap);
                   14709:     }
                   14710:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14711:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14712:     }
                   14713:     return;
                   14714: }
                   14715: 
1.1075.2.27  raeburn  14716: sub allmaps_incourse {
                   14717:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14718:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14719:         $cid = $env{'request.course.id'};
                   14720:         $cdom = $env{'course.'.$cid.'.domain'};
                   14721:         $cnum = $env{'course.'.$cid.'.num'};
                   14722:         $chome = $env{'course.'.$cid.'.home'};
                   14723:     }
                   14724:     my %allmaps = ();
                   14725:     my $lastchange =
                   14726:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14727:     if ($lastchange > $env{'request.course.tied'}) {
                   14728:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14729:         unless ($ferr) {
                   14730:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14731:         }
                   14732:     }
                   14733:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14734:     if (defined($navmap)) {
                   14735:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14736:             $allmaps{$res->src()} = 1;
                   14737:         }
                   14738:     }
                   14739:     return \%allmaps;
                   14740: }
                   14741: 
1.1075.2.11  raeburn  14742: sub parse_supplemental_title {
                   14743:     my ($title) = @_;
                   14744: 
                   14745:     my ($foldertitle,$renametitle);
                   14746:     if ($title =~ /&amp;&amp;&amp;/) {
                   14747:         $title = &HTML::Entites::decode($title);
                   14748:     }
                   14749:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14750:         $renametitle=$4;
                   14751:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14752:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14753:         my $name =  &plainname($uname,$udom);
                   14754:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14755:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14756:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14757:             $name.': <br />'.$foldertitle;
                   14758:     }
                   14759:     if (wantarray) {
                   14760:         return ($title,$foldertitle,$renametitle);
                   14761:     }
                   14762:     return $title;
                   14763: }
                   14764: 
1.1075.2.43  raeburn  14765: sub recurse_supplemental {
                   14766:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   14767:     if ($suppmap) {
                   14768:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   14769:         if ($fatal) {
                   14770:             $errors ++;
                   14771:         } else {
                   14772:             if ($#LONCAPA::map::resources > 0) {
                   14773:                 foreach my $res (@LONCAPA::map::resources) {
                   14774:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   14775:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  14776:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   14777:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  14778:                         } else {
                   14779:                             $numfiles ++;
                   14780:                         }
                   14781:                     }
                   14782:                 }
                   14783:             }
                   14784:         }
                   14785:     }
                   14786:     return ($numfiles,$errors);
                   14787: }
                   14788: 
1.1075.2.18  raeburn  14789: sub symb_to_docspath {
                   14790:     my ($symb) = @_;
                   14791:     return unless ($symb);
                   14792:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14793:     if ($resurl=~/\.(sequence|page)$/) {
                   14794:         $mapurl=$resurl;
                   14795:     } elsif ($resurl eq 'adm/navmaps') {
                   14796:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14797:     }
                   14798:     my $mapresobj;
                   14799:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14800:     if (ref($navmap)) {
                   14801:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14802:     }
                   14803:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14804:     my $type=$2;
                   14805:     my $path;
                   14806:     if (ref($mapresobj)) {
                   14807:         my $pcslist = $mapresobj->map_hierarchy();
                   14808:         if ($pcslist ne '') {
                   14809:             foreach my $pc (split(/,/,$pcslist)) {
                   14810:                 next if ($pc <= 1);
                   14811:                 my $res = $navmap->getByMapPc($pc);
                   14812:                 if (ref($res)) {
                   14813:                     my $thisurl = $res->src();
                   14814:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14815:                     my $thistitle = $res->title();
                   14816:                     $path .= '&'.
                   14817:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  14818:                              &escape($thistitle).
1.1075.2.18  raeburn  14819:                              ':'.$res->randompick().
                   14820:                              ':'.$res->randomout().
                   14821:                              ':'.$res->encrypted().
                   14822:                              ':'.$res->randomorder().
                   14823:                              ':'.$res->is_page();
                   14824:                 }
                   14825:             }
                   14826:         }
                   14827:         $path =~ s/^\&//;
                   14828:         my $maptitle = $mapresobj->title();
                   14829:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  14830:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14831:         }
                   14832:         $path .= (($path ne '')? '&' : '').
                   14833:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  14834:                  &escape($maptitle).
1.1075.2.18  raeburn  14835:                  ':'.$mapresobj->randompick().
                   14836:                  ':'.$mapresobj->randomout().
                   14837:                  ':'.$mapresobj->encrypted().
                   14838:                  ':'.$mapresobj->randomorder().
                   14839:                  ':'.$mapresobj->is_page();
                   14840:     } else {
                   14841:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14842:         my $ispage = (($type eq 'page')? 1 : '');
                   14843:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  14844:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14845:         }
                   14846:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  14847:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  14848:     }
                   14849:     unless ($mapurl eq 'default') {
                   14850:         $path = 'default&'.
1.1075.2.46  raeburn  14851:                 &escape('Main Content').
1.1075.2.18  raeburn  14852:                 ':::::&'.$path;
                   14853:     }
                   14854:     return $path;
                   14855: }
                   14856: 
1.1075.2.14  raeburn  14857: sub captcha_display {
                   14858:     my ($context,$lonhost) = @_;
                   14859:     my ($output,$error);
                   14860:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14861:     if ($captcha eq 'original') {
                   14862:         $output = &create_captcha();
                   14863:         unless ($output) {
                   14864:             $error = 'captcha';
                   14865:         }
                   14866:     } elsif ($captcha eq 'recaptcha') {
                   14867:         $output = &create_recaptcha($pubkey);
                   14868:         unless ($output) {
                   14869:             $error = 'recaptcha';
                   14870:         }
                   14871:     }
                   14872:     return ($output,$error);
                   14873: }
                   14874: 
                   14875: sub captcha_response {
                   14876:     my ($context,$lonhost) = @_;
                   14877:     my ($captcha_chk,$captcha_error);
                   14878:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14879:     if ($captcha eq 'original') {
                   14880:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14881:     } elsif ($captcha eq 'recaptcha') {
                   14882:         $captcha_chk = &check_recaptcha($privkey);
                   14883:     } else {
                   14884:         $captcha_chk = 1;
                   14885:     }
                   14886:     return ($captcha_chk,$captcha_error);
                   14887: }
                   14888: 
                   14889: sub get_captcha_config {
                   14890:     my ($context,$lonhost) = @_;
                   14891:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   14892:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14893:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14894:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   14895:     if ($context eq 'usercreation') {
                   14896:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14897:         if (ref($domconfig{$context}) eq 'HASH') {
                   14898:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14899:             if (ref($hashtocheck) eq 'HASH') {
                   14900:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14901:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14902:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14903:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14904:                     }
                   14905:                     if ($privkey && $pubkey) {
                   14906:                         $captcha = 'recaptcha';
                   14907:                     } else {
                   14908:                         $captcha = 'original';
                   14909:                     }
                   14910:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14911:                     $captcha = 'original';
                   14912:                 }
                   14913:             }
                   14914:         } else {
                   14915:             $captcha = 'captcha';
                   14916:         }
                   14917:     } elsif ($context eq 'login') {
                   14918:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14919:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14920:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14921:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   14922:             if ($privkey && $pubkey) {
                   14923:                 $captcha = 'recaptcha';
                   14924:             } else {
                   14925:                 $captcha = 'original';
                   14926:             }
                   14927:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14928:             $captcha = 'original';
                   14929:         }
                   14930:     }
                   14931:     return ($captcha,$pubkey,$privkey);
                   14932: }
                   14933: 
                   14934: sub create_captcha {
                   14935:     my %captcha_params = &captcha_settings();
                   14936:     my ($output,$maxtries,$tries) = ('',10,0);
                   14937:     while ($tries < $maxtries) {
                   14938:         $tries ++;
                   14939:         my $captcha = Authen::Captcha->new (
                   14940:                                            output_folder => $captcha_params{'output_dir'},
                   14941:                                            data_folder   => $captcha_params{'db_dir'},
                   14942:                                           );
                   14943:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14944: 
                   14945:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14946:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14947:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14948:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14949:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14950:             last;
                   14951:         }
                   14952:     }
                   14953:     return $output;
                   14954: }
                   14955: 
                   14956: sub captcha_settings {
                   14957:     my %captcha_params = (
                   14958:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14959:                            www_output_dir => "/captchaspool",
                   14960:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14961:                            numchars       => '5',
                   14962:                          );
                   14963:     return %captcha_params;
                   14964: }
                   14965: 
                   14966: sub check_captcha {
                   14967:     my ($captcha_chk,$captcha_error);
                   14968:     my $code = $env{'form.code'};
                   14969:     my $md5sum = $env{'form.crypt'};
                   14970:     my %captcha_params = &captcha_settings();
                   14971:     my $captcha = Authen::Captcha->new(
                   14972:                       output_folder => $captcha_params{'output_dir'},
                   14973:                       data_folder   => $captcha_params{'db_dir'},
                   14974:                   );
1.1075.2.26  raeburn  14975:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  14976:     my %captcha_hash = (
                   14977:                         0       => 'Code not checked (file error)',
                   14978:                        -1      => 'Failed: code expired',
                   14979:                        -2      => 'Failed: invalid code (not in database)',
                   14980:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   14981:     );
                   14982:     if ($captcha_chk != 1) {
                   14983:         $captcha_error = $captcha_hash{$captcha_chk}
                   14984:     }
                   14985:     return ($captcha_chk,$captcha_error);
                   14986: }
                   14987: 
                   14988: sub create_recaptcha {
                   14989:     my ($pubkey) = @_;
1.1075.2.51  raeburn  14990:     my $use_ssl;
                   14991:     if ($ENV{'SERVER_PORT'} == 443) {
                   14992:         $use_ssl = 1;
                   14993:     }
1.1075.2.14  raeburn  14994:     my $captcha = Captcha::reCAPTCHA->new;
                   14995:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1075.2.51  raeburn  14996:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1075.2.14  raeburn  14997:            &mt('If either word is hard to read, [_1] will replace them.',
1.1075.2.39  raeburn  14998:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1075.2.14  raeburn  14999:            '<br /><br />';
                   15000: }
                   15001: 
                   15002: sub check_recaptcha {
                   15003:     my ($privkey) = @_;
                   15004:     my $captcha_chk;
                   15005:     my $captcha = Captcha::reCAPTCHA->new;
                   15006:     my $captcha_result =
                   15007:         $captcha->check_answer(
                   15008:                                 $privkey,
                   15009:                                 $ENV{'REMOTE_ADDR'},
                   15010:                                 $env{'form.recaptcha_challenge_field'},
                   15011:                                 $env{'form.recaptcha_response_field'},
                   15012:                               );
                   15013:     if ($captcha_result->{is_valid}) {
                   15014:         $captcha_chk = 1;
                   15015:     }
                   15016:     return $captcha_chk;
                   15017: }
                   15018: 
1.1075.2.56  raeburn  15019: sub cleanup_html {
                   15020:     my ($incoming) = @_;
                   15021:     my $outgoing;
                   15022:     if ($incoming ne '') {
                   15023:         $outgoing = $incoming;
                   15024:         $outgoing =~ s/;/&#059;/g;
                   15025:         $outgoing =~ s/\#/&#035;/g;
                   15026:         $outgoing =~ s/\&/&#038;/g;
                   15027:         $outgoing =~ s/</&#060;/g;
                   15028:         $outgoing =~ s/>/&#062;/g;
                   15029:         $outgoing =~ s/\(/&#040/g;
                   15030:         $outgoing =~ s/\)/&#041;/g;
                   15031:         $outgoing =~ s/"/&#034;/g;
                   15032:         $outgoing =~ s/'/&#039;/g;
                   15033:         $outgoing =~ s/\$/&#036;/g;
                   15034:         $outgoing =~ s{/}{&#047;}g;
                   15035:         $outgoing =~ s/=/&#061;/g;
                   15036:         $outgoing =~ s/\\/&#092;/g
                   15037:     }
                   15038:     return $outgoing;
                   15039: }
                   15040: 
1.41      ng       15041: =pod
                   15042: 
                   15043: =back
                   15044: 
1.112     bowersj2 15045: =cut
1.41      ng       15046: 
1.112     bowersj2 15047: 1;
                   15048: __END__;
1.41      ng       15049: 

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